Skip to content

Commit

Permalink
[csharp] ByteString.CreateCodedInput should use ArraySegment offset a…
Browse files Browse the repository at this point in the history
…nd count

CreateCodedInput is created from the underlying array behind the ByteString.
If this was created from a larger array (via Memory<byte> or ArrayPool etc)
then the CodedInput refers to the wrong section of memory.

Change is to add the offset and count like the other methods that use the
ArraySegment (ToString, ToBase64, WriteTo).
  • Loading branch information
kiwidev committed Jun 16, 2021
1 parent 5ab8239 commit 2d9d5f8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
16 changes: 16 additions & 0 deletions csharp/src/Google.Protobuf.Test/ByteStringTest.cs
Expand Up @@ -210,6 +210,22 @@ public void UnsafeWrap()
Assert.AreEqual(byte.MaxValue, s[0]);
}

[Test]
public void CreateCodedInput_FromArraySegment()
{
byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 };
ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3));
CodedInputStream codedInputStream = bs.CreateCodedInput();

byte[] bytes = codedInputStream.ReadRawBytes(3);

Assert.AreEqual(3, bytes.Length);
Assert.AreEqual(2, bytes[0]);
Assert.AreEqual(3, bytes[1]);
Assert.AreEqual(4, bytes[2]);
Assert.IsTrue(codedInputStream.IsAtEnd);
}

[Test]
public void WriteToStream()
{
Expand Down
2 changes: 1 addition & 1 deletion csharp/src/Google.Protobuf/ByteString.cs
Expand Up @@ -325,7 +325,7 @@ public CodedInputStream CreateCodedInput()
if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment) && segment.Count == bytes.Length)
{
// Fast path. ByteString was created with a complete array.
return new CodedInputStream(segment.Array);
return new CodedInputStream(segment.Array, segment.Offset, segment.Count);
}
else
{
Expand Down

0 comments on commit 2d9d5f8

Please sign in to comment.