steve-warren / luna-db

A specialized JSON document store.
0 stars 0 forks source link

Binary Primitives Reader/Writer #7

Closed steve-warren closed 2 weeks ago

steve-warren commented 3 weeks ago

Build a BinaryPrimitives wrapper class to reduce boilerplate code.

e.g.

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteUInt16(Stream stream, ushort value)
{
    Span<byte> buffer = stackalloc byte[2];
    BinaryPrimitives.WriteUInt16LittleEndian(buffer, value);
    stream.Write(buffer);
}
steve-warren commented 2 weeks ago

BinaryPrimitives uses MemoryMarshal under the hood:

/// <summary>
/// Reads a UInt16 out of a read-only span of bytes as little endian.
/// </summary>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ushort ReadUInt16LittleEndian(ReadOnlySpan<byte> source)
{
    ushort result = MemoryMarshal.Read<ushort>(source);
    if (!BitConverter.IsLittleEndian)
    {
        result = ReverseEndianness(result);
    }
    return result;
}

See https://github.com/dotnet/corert/blob/c6af4cfc8b625851b91823d9be746c4f7abdc667/src/System.Private.CoreLib/shared/System/Buffers/Binary/ReaderLittleEndian.cs#L92

It checks for endianness on every call. We can avoid this by implementing our own by: