diff --git a/src/ArtemisNetCoreClient/ByteBuffer.cs b/src/ArtemisNetCoreClient/ByteBuffer.cs index 998fb1b..741d48d 100644 --- a/src/ArtemisNetCoreClient/ByteBuffer.cs +++ b/src/ArtemisNetCoreClient/ByteBuffer.cs @@ -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) { diff --git a/test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs b/test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs index c9753df..50e54d9 100644 --- a/test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs +++ b/test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs @@ -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()