Header menu logo TDesu.FSharp

Stream Module

Bounded stream copy utilities.

Types

Type Description

MaxBytesExceeded

The outcome of copyUpTo when the source produced more bytes than the configured limit.

Functions and values

Function or value Description

Stream.copyUpTo maxBytes destination cancellationToken source

Full Usage: Stream.copyUpTo maxBytes destination cancellationToken source

Parameters:
    maxBytes : int64 - The maximum number of bytes allowed to be read from source.
    destination : Stream - The stream to write to. Not disposed by this function.
    cancellationToken : CancellationToken - Token observed on every read and write.
    source : Stream - The stream to read from. Not disposed by this function.

Returns: Task<Result<int64, MaxBytesExceeded>>

Copies source into destination, stopping and returning Error instead of throwing once more than maxBytes would be read from source. The chunk that would push the total over the limit is discarded rather than partially written, so destination never receives more than maxBytes bytes.

Uses an 81920-byte buffer rented from Shared, always returned in a finally — including when cancellationToken cancels the copy or either stream throws. Neither source nor destination is disposed by this function; the caller owns both. The repo's own ArrayPool helpers in Buffers.fs are not used here: Buffers.fs compiles after this file in TDesu.FSharp.fsproj, so this module cannot reference it.

Deviates from the usual "null collection is empty" policy: a null stream cannot stand in for an empty one without silently changing where bytes go (a null destination would silently discard writes), so a null source or destination is treated like a null function argument — a programmer error that throws immediately, before any I/O or task is started.

maxBytes : int64

The maximum number of bytes allowed to be read from source.

destination : Stream

The stream to write to. Not disposed by this function.

cancellationToken : CancellationToken

Token observed on every read and write.

source : Stream

The stream to read from. Not disposed by this function.

Returns: Task<Result<int64, MaxBytesExceeded>>
ArgumentNullException When source or destination is null.
Example

 match! request.Body |> Stream.copyUpTo (10L * 1024L * 1024L) buffer ct with
 | Ok bytesWritten -> ...
 | Error e -> failwithf "payload too large: wrote %d of %d allowed bytes" e.BytesWritten e.MaxBytes
union case Result.Ok: ResultValue: 'T -> Result<'T,'TError>
union case Result.Error: ErrorValue: 'TError -> Result<'T,'TError>
val failwithf: format: Printf.StringFormat<'T,'Result> -> 'T

Type something to start searching.