|
3 | 3 |
|
4 | 4 | namespace SpacetimeDB; |
5 | 5 |
|
| 6 | +using System.Buffers.Binary; |
6 | 7 | using System.Numerics; |
7 | 8 | using System.Runtime.InteropServices; |
8 | 9 |
|
@@ -33,6 +34,33 @@ public U128(ulong upper, ulong lower) |
33 | 34 |
|
34 | 35 | internal ulong Upper => _upper; |
35 | 36 |
|
| 37 | + /// Returns a <see cref="U128" /> from a big-endian byte array. |
| 38 | + public static U128 FromBytesBigEndian(ReadOnlySpan<byte> bytes) |
| 39 | + { |
| 40 | + if (bytes.Length != Size) |
| 41 | + { |
| 42 | + throw new ArgumentException( |
| 43 | + $"Byte array must be exactly {Size} bytes long.", |
| 44 | + nameof(bytes) |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + var upper = BinaryPrimitives.ReadUInt64BigEndian(bytes.Slice(0, 8)); |
| 49 | + var lower = BinaryPrimitives.ReadUInt64BigEndian(bytes.Slice(8, 8)); |
| 50 | + |
| 51 | + return new U128(upper, lower); |
| 52 | + } |
| 53 | + |
| 54 | + public byte[] ToBytesBigEndian() |
| 55 | + { |
| 56 | + var bytes = new byte[Size]; |
| 57 | + |
| 58 | + BinaryPrimitives.WriteUInt64BigEndian(bytes.AsSpan(0, 8), _upper); |
| 59 | + BinaryPrimitives.WriteUInt64BigEndian(bytes.AsSpan(8, 8), _lower); |
| 60 | + |
| 61 | + return bytes; |
| 62 | + } |
| 63 | + |
36 | 64 | /// <inheritdoc cref="IComparable.CompareTo(object)" /> |
37 | 65 | public int CompareTo(object? value) |
38 | 66 | { |
@@ -90,4 +118,17 @@ private BigInteger AsBigInt() => |
90 | 118 |
|
91 | 119 | /// <inheritdoc cref="object.ToString()" /> |
92 | 120 | public override string ToString() => AsBigInt().ToString(); |
| 121 | + |
| 122 | + public Guid ToGuid() |
| 123 | + { |
| 124 | + var bytes = ToBytesBigEndian(); |
| 125 | + return new Guid(bytes); |
| 126 | + } |
| 127 | + |
| 128 | + public static U128 FromGuid(Guid guid) |
| 129 | + { |
| 130 | + Span<byte> bytes = stackalloc byte[16]; |
| 131 | + guid.TryWriteBytes(bytes); |
| 132 | + return FromBytesBigEndian(bytes); |
| 133 | + } |
93 | 134 | } |
0 commit comments