Skip to content

Commit

Permalink
Final comments addressed
Browse files Browse the repository at this point in the history
  • Loading branch information
kazimuth committed Nov 13, 2024
1 parent 6619575 commit 882bb54
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 43 deletions.
65 changes: 22 additions & 43 deletions crates/bindings-csharp/BSATN.Runtime.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,18 @@ public static void AddressRoundtrips()
Assert.Equal(addr3, addr);

var memoryStream = new MemoryStream();
var writer = new BinaryWriter(memoryStream);
var bsatn = new Address.BSATN();
if (addr is { } addrNotNull)
{
bsatn.Write(writer, addrNotNull);
}
else
using (var writer = new BinaryWriter(memoryStream))
{
Assert.Fail("Impossible");
if (addr is { } addrNotNull)
{
bsatn.Write(writer, addrNotNull);
}
else
{
Assert.Fail("Impossible");
}
}
writer.Flush();

var littleEndianBytes = memoryStream.ToArray();
var reader = new BinaryReader(new MemoryStream(littleEndianBytes));
Expand Down Expand Up @@ -96,41 +97,10 @@ public static void IdentityRoundtrips()

Assert.Equal(ident.ToString(), str);

byte[] bytes =
[
0x00,
0x11,
0x22,
0x33,
0x44,
0x55,
0x66,
0x77,
0x88,
0x99,
0xaa,
0xbb,
0xcc,
0xdd,
0xee,
0xff,
0x00,
0x11,
0x22,
0x33,
0x44,
0x55,
0x66,
0x77,
0x88,
0x99,
0xaa,
0xbb,
0xcc,
0xdd,
0xee,
0xff,
];
// We can't use this in the implementation because it isn't available
// in Unity's .NET. But we can use it in tests.
var bytes = Convert.FromHexString(str);

var ident2 = Identity.FromBigEndian(bytes);
Assert.Equal(ident2, ident);

Expand Down Expand Up @@ -176,4 +146,13 @@ public static void IdentityLengthCheck()
Assert.ThrowsAny<Exception>(() => Identity.From(arr));
});
}

[Fact]
public static void NonHexStrings()
{
// n.b. 32 chars long
Assert.ThrowsAny<Exception>(
() => Address.FromHexString("these are not hex characters....")
);
}
}
13 changes: 13 additions & 0 deletions crates/bindings-csharp/BSATN.Runtime/Builtins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,19 @@ static byte[] AsBytes<T>(T source, bool reverse)
/// <returns></returns>
public static byte[] StringToByteArray(string hex)
{
Debug.Assert(
hex.Length % 2 == 0,
$"Expected input string (\"{hex}\") to be of even length"
);

foreach (var c in hex)
{
Debug.Assert(
(c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'),
$"Expected input string (\"{hex}\") to be hexadecimal"
);
}

var NumberChars = hex.Length;
var bytes = new byte[NumberChars / 2];
for (var i = 0; i < NumberChars; i += 2)
Expand Down

0 comments on commit 882bb54

Please sign in to comment.