Skip to content

Commit

Permalink
Decode long strings
Browse files Browse the repository at this point in the history
  • Loading branch information
Havret committed Mar 6, 2024
1 parent c317b03 commit fe5ec9a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
24 changes: 22 additions & 2 deletions src/ArtemisNetCoreClient/ByteBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -198,18 +198,38 @@ public string ReadString()

private string ReadAsBytes()
{
return string.Empty;
var actualByteCount = ReadInt();

var length = actualByteCount >> 1;

var chars = new char[length];

for (var i = 0; i < length; i++)
{
var low = _memoryStream.ReadByte(); // Low byte
var high = _memoryStream.ReadByte(); // High byte
var combined = (high << 8) | low;
chars[i] = (char) combined;
}

return new string(chars);
}

private string ReadAsShorts(int length)
{
Span<char> chars = stackalloc char[length];
for (int i = 0; i < length; i++)
for (var i = 0; i < length; i++)
{
var c = (char) ReadShort();
chars[i] = c;
}

return new string(chars);
}

public string? ReadNullableString()
{
var value = _memoryStream.ReadByte();
return value == DataConstants.NotNull ? ReadString() : null;
}
}
18 changes: 16 additions & 2 deletions test/ArtemisNetCoreClient.Tests/ByteBufferTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public void should_encode_long_string()
CollectionAssert.AreEqual(expected, byteBuffer.GetBuffer().ToArray());
}

[Test, Ignore("TODO")]
[Test]
public void should_decode_long_string()
{
// Arrange
Expand All @@ -247,7 +247,7 @@ public void should_decode_long_string()

[TestCase("abcdefgh", new byte[] { 1, 0, 0, 0, 8, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104 })]
[TestCase(null, new byte[] { 0 })]
public void should_nullable_string(string value, byte[] encoded)
public void should_encode_nullable_string(string value, byte[] encoded)
{
// Arrange
var byteBuffer = new ByteBuffer();
Expand All @@ -258,4 +258,18 @@ public void should_nullable_string(string value, byte[] encoded)
// Assert
CollectionAssert.AreEqual(encoded, byteBuffer.GetBuffer().ToArray());
}

[TestCase(new byte[] { 1, 0, 0, 0, 8, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104 }, "abcdefgh")]
[TestCase(new byte[] { 0 }, null)]
public void should_decode_nullable_string(byte[] encoded, string? expected)
{
// Arrange
var byteBuffer = new ByteBuffer(encoded);

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

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

0 comments on commit fe5ec9a

Please sign in to comment.