Skip to content

Commit 040f698

Browse files
authored
CSHARP-5663: Avoid RentedBuffer boxing in DisposableSegment (#1786)
1 parent fbb4139 commit 040f698

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/MongoDB.Bson/IO/EncodingHelper.cs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,33 @@ internal static class EncodingHelper
2525
{
2626
public readonly struct DisposableSegment : IDisposable
2727
{
28-
private IDisposable DisposableData { get; }
28+
private bool DisposeRentedBuffer { get; }
29+
private ThreadStaticBuffer.RentedBuffer RentedBuffer { get; }
2930
public ArraySegment<byte> Segment { get; }
3031

31-
public DisposableSegment(IDisposable disposableData, ArraySegment<byte> segment)
32+
public DisposableSegment(ThreadStaticBuffer.RentedBuffer rentedBuffer, ArraySegment<byte> segment)
3233
{
33-
DisposableData = disposableData;
34+
DisposeRentedBuffer = true;
35+
RentedBuffer = rentedBuffer;
36+
Segment = segment;
37+
}
38+
39+
public DisposableSegment(ArraySegment<byte> segment)
40+
{
41+
DisposeRentedBuffer = false;
3442
Segment = segment;
3543
}
3644

3745
public void Dispose()
3846
{
39-
DisposableData?.Dispose();
47+
if (DisposeRentedBuffer)
48+
{
49+
RentedBuffer.Dispose();
50+
}
4051
}
4152
}
4253

43-
private static readonly ArraySegment<byte> __emptySegment = new ArraySegment<byte>(new byte[0]);
54+
private static readonly ArraySegment<byte> __emptySegment = new(new byte[0]);
4455

4556
public static DisposableSegment GetBytesUsingThreadStaticBuffer(this Encoding encoding, string value)
4657
{
@@ -57,7 +68,7 @@ public static DisposableSegment GetBytesUsingThreadStaticBuffer(this Encoding en
5768
var length = value.Length;
5869
if (length == 0)
5970
{
60-
return new DisposableSegment(null, __emptySegment);
71+
return new DisposableSegment(__emptySegment);
6172
}
6273

6374
var maxSize = encoding.GetMaxByteCount(length);

0 commit comments

Comments
 (0)