Skip to content

Commit 94e7a21

Browse files
committed
CSHARP-1117: Fix issue in ByteBufferSlice AccessBackingBytes when slice spans multiple chunks.
1 parent 4a5f947 commit 94e7a21

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/MongoDB.Bson.Tests/IO/ByteBufferSliceTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@ public void AccessBackingBytes_should_adjust_count()
4141
result.Count.Should().Be(2); // not 3
4242
}
4343

44+
[Test]
45+
public void AccessBackingBytes_should_adjust_count_when_multiple_chunks_are_present()
46+
{
47+
var arrays = new[] { new byte[] { 1, 2 }, new byte[] { 3, 4 } };
48+
var chunks = arrays.Select(a => new ByteArrayChunk(a));
49+
var buffer = new MultiChunkBuffer(chunks, isReadOnly: true);
50+
var subject = new ByteBufferSlice(buffer, 1, 2);
51+
52+
var result = subject.AccessBackingBytes(0);
53+
54+
result.Array.Should().BeSameAs(arrays[0]);
55+
result.Offset.Should().Be(1);
56+
result.Count.Should().Be(1); // not 2 or 3
57+
}
58+
4459
[Test]
4560
public void AccessBackingBytes_should_adjust_position()
4661
{

src/MongoDB.Bson/IO/ByteBufferSlice.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ public ArraySegment<byte> AccessBackingBytes(int position)
114114
ThrowIfDisposed();
115115

116116
var segment = _buffer.AccessBackingBytes(position + _offset);
117-
return new ArraySegment<byte>(segment.Array, segment.Offset, _length - position);
117+
var count = Math.Min(segment.Count, _length - position);
118+
return new ArraySegment<byte>(segment.Array, segment.Offset, count);
118119
}
119120

120121
/// <inheritdoc/>

0 commit comments

Comments
 (0)