Skip to content

OnixLabs.Core.ISpanBinaryConvertible

matthew edited this page May 27, 2026 · 1 revision

ISpanBinaryConvertible Interface

Defines a type that is convertible to an instance of ReadOnlySpan<byte>.

Namespace OnixLabs.Core
Assembly OnixLabs.Core.dll (NuGet)

Definition

public interface ISpanBinaryConvertible
{
    ReadOnlySpan<byte> AsReadOnlySpan();
}

Remarks

ISpanBinaryConvertible exposes the underlying binary representation of a type as a ReadOnlySpan<byte>. A span is a stack-only, non-allocating window over contiguous memory, making it the most efficient representation for immediate, synchronous reads — no heap allocation is required beyond whatever the implementer already holds.

Because ReadOnlySpan<byte> is a ref struct, it carries important limitations: it cannot be stored in a field, captured by a lambda, boxed, or used across await boundaries. In those scenarios, use IMemoryBinaryConvertible instead, whose AsReadOnlyMemory() returns a heap-storable ReadOnlyMemory<byte> from which a span can always be obtained via its Span property.

IBinaryConvertible composes this interface with IMemoryBinaryConvertible. A type that implements IBinaryConvertible also satisfies ISpanBinaryConvertible, so any API constrained to ISpanBinaryConvertible accepts any binary-convertible type in the library.

Note Implementers typically hold an immutable backing byte[] and return a view over a defensive copy so that the caller cannot mutate the original data through the returned span.

Examples

Implementing ISpanBinaryConvertible

using System;
using OnixLabs.Core;

public sealed class ByteBuffer : ISpanBinaryConvertible
{
    private readonly byte[] value;

    public ByteBuffer(ReadOnlySpan<byte> value)
    {
        this.value = value.ToArray();
    }

    // Returns a view over a defensive copy; the caller cannot corrupt backing data.
    public ReadOnlySpan<byte> AsReadOnlySpan() => value.ToArray();
}

Constraining an API to the minimum capability

An API that only reads bytes synchronously can accept ISpanBinaryConvertible rather than the broader IBinaryConvertible, making its requirements explicit and keeping it compatible with any binary-convertible type.

static int CountNonZero(ISpanBinaryConvertible source)
{
    ReadOnlySpan<byte> bytes = source.AsReadOnlySpan();
    int count = 0;

    foreach (byte b in bytes)
    {
        if (b != 0) count++;
    }

    return count;
}

Methods

Method Returns Description
AsReadOnlySpan() ReadOnlySpan<byte> Gets the current instance as a new ReadOnlySpan<byte>.

AsReadOnlySpan()

ReadOnlySpan<byte> AsReadOnlySpan();

Gets the current ISpanBinaryConvertible instance as a new ReadOnlySpan<byte> instance.

Returns — The current instance as a new ReadOnlySpan<byte>.

See Also

ONIXLabs .NET Library


Clone this wiki locally