Skip to content

Commit

Permalink
Implement nullable bool encoding/decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Mar 21, 2024
1 parent 72c98b9 commit fb71e85
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/ArtemisNetCoreClient/ByteBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,28 @@ public bool ReadBool()
return value != 0;
}

public void WriteNullableBool(bool? value)
{
WriteBool(value.HasValue);
if (value.HasValue)
{
WriteBool(value.Value);
}
}

public bool? ReadNullableBool()
{
var isNotNull = ReadBool();
if (isNotNull)
{
return ReadBool();
}
else
{
return null;
}
}

public void WriteByte(byte value)
{
_memoryStream.WriteByte(value);
Expand Down
30 changes: 30 additions & 0 deletions test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,36 @@ public void should_decode_bool(byte[] encoded, bool expected)
Assert.That(expected, Is.EqualTo(value));
}

[TestCase(true, new[] { unchecked((byte) -1), unchecked((byte) -1) })]
[TestCase(false, new[] { unchecked((byte) -1), (byte) 0 })]
[TestCase(null, new byte[] { 0 })]
public void should_encode_nullable_bool(bool? value, byte[] encoded)
{
// Arrange
var byteBuffer = new ByteBuffer();

// Act
byteBuffer.WriteNullableBool(value);

// Assert
CollectionAssert.AreEqual(encoded, byteBuffer.GetBuffer().ToArray());
}

[TestCase(new[] { unchecked((byte) -1), unchecked((byte) -1) }, true)]
[TestCase(new[] { unchecked((byte) -1), (byte) 0 }, false)]
[TestCase(new byte[] { 0 }, null)]
public void should_decode_nullable_bool(byte[] encoded, bool? expected)
{
// Arrange
var byteBuffer = new ByteBuffer(encoded);

// Act
var value = byteBuffer.ReadNullableBool();

// Assert
Assert.That(expected, Is.EqualTo(value));
}

[Test]
public void should_encode_int()
{
Expand Down

0 comments on commit fb71e85

Please sign in to comment.