[csharp] ByteString.CreateCodedInput should use ArraySegment offset and 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).
pull/8740/head
Mark Young 4 years ago
parent 18d980f380
commit 9848fe2bf7
  1. 16
      csharp/src/Google.Protobuf.Test/ByteStringTest.cs
  2. 2
      csharp/src/Google.Protobuf/ByteString.cs

@ -210,6 +210,22 @@ namespace Google.Protobuf
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()
{

@ -325,7 +325,7 @@ namespace Google.Protobuf
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
{

Loading…
Cancel
Save