Skip to content

Instantly share code, notes, and snippets.

@israellot
Created March 26, 2024 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save israellot/f7a39a299c64dcbad9023514ed574bb5 to your computer and use it in GitHub Desktop.
Save israellot/f7a39a299c64dcbad9023514ed574bb5 to your computer and use it in GitHub Desktop.
public unsafe class UnsafeUIntArray
{
public int Length { get; init; }
private readonly uint[] _data;
private readonly uint* _dataPtr;
public UnsafeUIntArray(int length)
{
Length = length;
_data = GC.AllocateArray<uint>(length, pinned: true);
ref uint dataRef = ref MemoryMarshal.GetArrayDataReference(_data);
_dataPtr = (uint*)Unsafe.AsPointer<uint>(ref dataRef);
}
public uint this[int key]
{
get => Get(key);
set => Set(key, value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe uint Get(int index)
{
var ptr = (_dataPtr + (uint)index);
return *ptr;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Set(int index, uint value)
{
var ptr = (_dataPtr + (uint)index);
*ptr = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment