Skip to content

[API Proposal]: CborReader - Provide a mechanism to read the length of Strings #115390

Closed as not planned
@AlgorithmsAreCool

Description

@AlgorithmsAreCool

Background and motivation

Today CborReader provides two APIs for reading definite length string and byte strings.

byte[] CborReader.ReadByteString()
string CborReader.ReadTextString()

bool TryReadByteString(Span<byte> destination, out int bytesWritten)
bool TryReadTextString(Span<char> destination, out int bytesWritten)

Developers are forced to either accept the allocation of a byte[]/string or do a stab in the dark TryRead* without feedback about the required length of the buffer. A developer could perform multiple TryRead* operations in a loop, growing the target buffer each iteration until the data fits, but it would be much better DX to be able to peek the size of the underlying data so that we could allocate or rent a correctly sized buffer.

API Proposal

Proposal

//returns the length, in bytes, of a byte string or text string that is at the current position of the reader
//throws InvalidOperationException if a byte string, or text string is not the current position of the reader
int CborReader.PeekDefiniteLengthStringByteCount()


### API Usage

```csharp
var reader = new CborReader(...);

int bufferLength = reader.PeekDefiniteLengthStringByteCount();//new api

var array = arrayPool.Rent(bufferLength);
Assert.IsTrue(reader.TryReadByteString(array, out var bytesWritten));

Alternative Designs

Risks

More API complexity, but limited risk

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions