Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-2959

Refactor PinnedBuffer and PinnedBufferWalker

    • Type: Icon: Improvement Improvement
    • Resolution: Won't Do
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Wire Protocol
    • None

      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();
      	}
      }
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            dmitry.lukyanov@mongodb.com Dmitry Lukyanov (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: