Skip to content

Commit 9848fe2

Browse files
committed
[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).
1 parent 18d980f commit 9848fe2

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

csharp/src/Google.Protobuf.Test/ByteStringTest.cs

+16
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,22 @@ public void UnsafeWrap()
210210
Assert.AreEqual(byte.MaxValue, s[0]);
211211
}
212212

213+
[Test]
214+
public void CreateCodedInput_FromArraySegment()
215+
{
216+
byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 };
217+
ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3));
218+
CodedInputStream codedInputStream = bs.CreateCodedInput();
219+
220+
byte[] bytes = codedInputStream.ReadRawBytes(3);
221+
222+
Assert.AreEqual(3, bytes.Length);
223+
Assert.AreEqual(2, bytes[0]);
224+
Assert.AreEqual(3, bytes[1]);
225+
Assert.AreEqual(4, bytes[2]);
226+
Assert.IsTrue(codedInputStream.IsAtEnd);
227+
}
228+
213229
[Test]
214230
public void WriteToStream()
215231
{

csharp/src/Google.Protobuf/ByteString.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ public CodedInputStream CreateCodedInput()
325325
if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment) && segment.Count == bytes.Length)
326326
{
327327
// Fast path. ByteString was created with a complete array.
328-
return new CodedInputStream(segment.Array);
328+
return new CodedInputStream(segment.Array, segment.Offset, segment.Count);
329329
}
330330
else
331331
{

0 commit comments

Comments
 (0)