Skip to content

Commit 5e72564

Browse files
iamcarbonabergs
authored andcommitted
Add IBufferWriter.WriteGuidBigEndian
1 parent 52cd471 commit 5e72564

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

Src/Fido2/Extensions/IBufferWriterExtensions.cs

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,43 @@ internal static class IBufferWriterExtensions
88
{
99
public static void WriteUInt16BigEndian(this IBufferWriter<byte> writer, ushort value)
1010
{
11-
Span<byte> buffer = stackalloc byte[2];
11+
var buffer = writer.GetSpan(2);
1212

1313
BinaryPrimitives.WriteUInt16BigEndian(buffer, value);
1414

15-
writer.Write(buffer);
15+
writer.Advance(2);
1616
}
1717

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

2222
BinaryPrimitives.WriteUInt32BigEndian(buffer, value);
2323

24-
writer.Write(buffer);
24+
writer.Advance(4);
25+
}
26+
27+
public static void WriteGuidBigEndian(this IBufferWriter<byte> writer, Guid value)
28+
{
29+
var buffer = writer.GetSpan(16);
30+
31+
_ = value.TryWriteBytes(buffer);
32+
33+
if (BitConverter.IsLittleEndian)
34+
{
35+
SwapBytes(buffer, 0, 3);
36+
SwapBytes(buffer, 1, 2);
37+
SwapBytes(buffer, 4, 5);
38+
SwapBytes(buffer, 6, 7);
39+
}
40+
41+
writer.Advance(16);
42+
}
43+
44+
private static void SwapBytes(Span<byte> bytes, int index1, int index2)
45+
{
46+
var temp = bytes[index1];
47+
bytes[index1] = bytes[index2];
48+
bytes[index2] = temp;
2549
}
2650
}

0 commit comments

Comments
 (0)