Skip to content

Commit

Permalink
Implement nullable int encoding/decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Mar 21, 2024
1 parent fb71e85 commit 6645d4e
Show file tree
Hide file tree
Showing 2 changed files with 50 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 @@ -82,6 +82,28 @@ public int ReadInt()
_ = _memoryStream.Read(buffer);
return BinaryPrimitives.ReadInt32BigEndian(buffer);
}

public void WriteNullableInt(int? value)
{
WriteBool(value.HasValue);
if (value.HasValue)
{
WriteInt(value.Value);
}
}

public int? ReadNullableInt()
{
var isNotNull = ReadBool();
if (isNotNull)
{
return ReadInt();
}
else
{
return null;
}
}

public void WriteLong(long value)
{
Expand Down
28 changes: 28 additions & 0 deletions test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,34 @@ public void should_decode_int()
// Assert
Assert.That(value, Is.EqualTo(170));
}

[TestCase(170, new byte[] { unchecked((byte) -1), 0, 0, 0, unchecked((byte) -86) })]
[TestCase(null, new byte[] { 0 })]
public void should_encode_nullable_int(int? value, byte[] encoded)
{
// Arrange
var byteBuffer = new ByteBuffer();

// Act
byteBuffer.WriteNullableInt(value);

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

[TestCase(new byte[] { unchecked((byte) -1), 0, 0, 0, unchecked((byte) -86) }, 170)]
[TestCase(new byte[] { 0 }, null)]
public void should_decode_nullable_int(byte[] encoded, int? expected)
{
// Arrange
var byteBuffer = new ByteBuffer(encoded);

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

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

[Test]
public void should_encode_long()
Expand Down

0 comments on commit 6645d4e

Please sign in to comment.