ISpanEncoder<TValue>

Namespace: SnowBank.Data.Binary · interface

Defines methods to encode the binary representation of instances of type TValue into a span

Remarks

This type is expected to be implemented on structs ONLY, in order to achieve the best performance by using JIT inlining and other optimizations as much as possible.

Methods

TryEncode

static bool TryEncode(Span<byte> destination, out int bytesWritten, in TValue value)

Encodes the value to the destination buffer, if it is large enough.

  • destination — Destination buffer that will receive the encoded representation of the value
  • bytesWritten — Number of bytes that where written to the buffer, if the operation is successful
  • value — Value to encode

Returns: false if the buffer is not large enough, true if the operation was successful, or an exception if the encoding failed for other reasons

This method behaves similarly to TryFormat: the caller allocates a buffer with a safe initial capacity. If the buffer is too small, then the caller should retry with a larger buffer, until the method returns true or fails.

Please note that the method MUST NOT return false for a reason other than a buffer being too small, otherwise the caller may end up in an infinite retry loop, passing a larger and larger buffer.

TryGetSizeHint

static bool TryGetSizeHint(in TValue value, out int sizeHint)

Returns a hint for the minimum capacity required to format the value.

  • value — Value that needs to be encoded
  • sizeHint — Receives the minimum buffer size that should be passed to TryEncode

Returns: true if a minimum size is known, or false if computing this size would be too costly

The returned capacity MAY be smaller than the actual size required: some encoders may return a good estimate for 99%+ of the cases, in which case the capacity is a good starting point.

For example, a UTF-8 encoder may assume that each character will take 2 bytes on average, which is smaller than the maximum of 3 bytes.

TryGetSpan

static bool TryGetSpan(in TValue value, out ReadOnlySpan<byte> span)

Returns a span of the encoded representation of the value, if it can be done without any memory allocations

  • value — Value to encode
  • span — Receives a span with the encoded value

Returns: true if the span is available; otherwise, false

This should only return true when the in-memory layout of the value is the same as its encoded representation.

If this method returns false, use TryEncode to encode the value into a temporary buffer.