[CSHARP-2959] Refactor PinnedBuffer and PinnedBufferWalker Created: 08/Feb/20  Updated: 28/Jul/22  Resolved: 28/Jul/22

Status: Closed
Project: C# Driver
Component/s: Wire Protocol
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Dmitry Lukyanov (Inactive) Assignee: Unassigned
Resolution: Won't Do Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

This ticket is based on the discussion which I and Robert had in the scope of the CSHARP-2486.

We need to consider the refactoring of PinnedBuffer and PinnedBufferWalker. Currently, PinnedBuffer and PinnedBufferWalker are designed for a similar purpose with the difference that PinnedBuffer is immutable, but PinnedBufferWalker is mutable (this class has a state based on offset).

For example, it can be a solution which will allow removing offset from the initial arguments of PinnedBuffer for example similar to:

using (var pinnedBuffer = new PinnedBuffer(bytes))
{
 var intPtr = pinnedBuffer.GetIntPtrToOffset(offset);
 SomeInteropMethod(intPtr);
}

It also means that we will need to track offset in some other place.

Another solution can be leaving PinnedBuffer responsible only for bytes array and disposing memory. The whole offset processing can be moved into a new separate class which will take a PinnedBuffer in initial arguments similar to how .net streams work:

internal class PinnedBufferWalker : IDisposable
{
	private IntPtr _intPtr;
	private int _offset;
	private readonly PinnedBuffer _pinnedBuffer;
	public PinnedBufferWalker(PinnedBuffer pinnedBuffer, int offset)
	{
		_offset = offset;
		_pinnedBuffer = pinnedBuffer;
		RefreshIntPtr();
	}
	public int Offset
	{
		get => _offset;
		set
		{
			_offset = value;
			RefreshIntPtr();
		}
	}
	public IntPtr IntPtr => _intPtr;
	protected void RefreshIntPtr()
	{
		_intPtr = Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedBuffer.Bytes, _offset);
	}
	public void Dispose()
	{
		_pinnedBuffer.Dispose();
	}
}



 Comments   
Comment by Adelin Mbida Owona [ 28/Jul/22 ]

Won't do as a result of https://jira.mongodb.org/browse/CSHARP-4271

Comment by Robert Stam [ 12/Mar/20 ]

I would recommend eliminating PinnedBufferWalker altogether and keep the position state outside any class having to do with pinning memory.

Generated at Wed Feb 07 21:43:58 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.