Skip to content

You're viewing documentation for a pre-release version. View the latest stable version

Instance Method

withStreamingBytes(_:)

Read the body’s bytes incrementally, without buffering the whole thing.
func withStreamingBytes(_ body: @escaping (Span<UInt8>) async throws -> Void) async throws

Discussion

The closure is called once per chunk, in order, and is backpressured: a streaming body only produces the next chunk once the closure returns. Each span is only valid for the duration of that call - RawSpan is non-escapable, so the compiler enforces that: the closure cannot stash a span and read it later.

Works for every kind of body - a buffered one is handed over as a single chunk, and an empty one calls the closure not at all - so callers do not need to branch on storage.

Note this consumes a streaming body: it runs the stream’s callback, so it has that closure’s side effects and must not be called twice on the same body. A streaming body can also throw part-way, after the closure has already seen chunks.

Use collect() instead when the whole body is genuinely needed in memory.