Skip to content

Commit

Permalink
Add IBufferWriter.WriteGuidBigEndian
Browse files Browse the repository at this point in the history
  • Loading branch information
iamcarbon authored and abergs committed Jan 24, 2023
1 parent 52cd471 commit 5e72564
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions Src/Fido2/Extensions/IBufferWriterExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,43 @@ internal static class IBufferWriterExtensions
{
public static void WriteUInt16BigEndian(this IBufferWriter<byte> writer, ushort value)
{
Span<byte> buffer = stackalloc byte[2];
var buffer = writer.GetSpan(2);

BinaryPrimitives.WriteUInt16BigEndian(buffer, value);

writer.Write(buffer);
writer.Advance(2);
}

public static void WriteUInt32BigEndian(this IBufferWriter<byte> writer, uint value)
{
Span<byte> buffer = stackalloc byte[4];
var buffer = writer.GetSpan(4);

BinaryPrimitives.WriteUInt32BigEndian(buffer, value);

writer.Write(buffer);
writer.Advance(4);
}

public static void WriteGuidBigEndian(this IBufferWriter<byte> writer, Guid value)
{
var buffer = writer.GetSpan(16);

_ = value.TryWriteBytes(buffer);

if (BitConverter.IsLittleEndian)
{
SwapBytes(buffer, 0, 3);
SwapBytes(buffer, 1, 2);
SwapBytes(buffer, 4, 5);
SwapBytes(buffer, 6, 7);
}

writer.Advance(16);
}

private static void SwapBytes(Span<byte> bytes, int index1, int index2)
{
var temp = bytes[index1];
bytes[index1] = bytes[index2];
bytes[index2] = temp;
}
}

0 comments on commit 5e72564

Please sign in to comment.