Skip to content

Commit

Permalink
Refactor memory copies in SafeBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
xtqqczze committed Jul 27, 2024
1 parent 7e429c2 commit a79a21d
Showing 1 changed file with 8 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -187,21 +187,18 @@ public T Read<T>(ulong byteOffset) where T : struct
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);

// return *(T*) (_ptr + byteOffset);
T value = default;
bool mustCallRelease = false;
try
{
DangerousAddRef(ref mustCallRelease);

SpanHelpers.Memmove(ref Unsafe.As<T, byte>(ref value), ref *ptr, sizeofT);
return Unsafe.ReadUnaligned<T>(ptr);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
return value;
}

/// <summary>
Expand Down Expand Up @@ -248,7 +245,9 @@ public void ReadSpan<T>(ulong byteOffset, Span<T> buffer)

ref T structure = ref MemoryMarshal.GetReference(buffer);
for (int i = 0; i < buffer.Length; i++)
Buffer.Memmove(ref Unsafe.Add(ref structure, i), ref Unsafe.AsRef<T>(ptr + alignedSizeofT * i), 1);
{
Unsafe.Add(ref structure, i) = Unsafe.ReadUnaligned<T>(ptr + alignedSizeofT * i);
}
}
finally
{
Expand All @@ -275,13 +274,12 @@ public void Write<T>(ulong byteOffset, T value) where T : struct
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);

// *((T*) (_ptr + byteOffset)) = value;
bool mustCallRelease = false;
try
{
DangerousAddRef(ref mustCallRelease);

SpanHelpers.Memmove(ref *ptr, ref Unsafe.As<T, byte>(ref value), sizeofT);
Unsafe.WriteUnaligned(ptr, value);
}
finally
{
Expand Down Expand Up @@ -336,7 +334,9 @@ public void WriteSpan<T>(ulong byteOffset, ReadOnlySpan<T> data)

ref T structure = ref MemoryMarshal.GetReference(data);
for (int i = 0; i < data.Length; i++)
Buffer.Memmove(ref Unsafe.AsRef<T>(ptr + alignedSizeofT * i), ref Unsafe.Add(ref structure, i), 1);
{
Unsafe.WriteUnaligned(ptr + alignedSizeofT * i, Unsafe.Add(ref structure, i));
}
}
finally
{
Expand Down

0 comments on commit a79a21d

Please sign in to comment.