Last active
March 27, 2022 00:30
-
-
Save Frityet/70bc35a05e08c5cfdb990e51f0b6bbe5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public unsafe class Memory : IDisposable | |
{ | |
public int Count { get; private set; } | |
public int MaxCount { get; private set; } | |
private byte* _pointer; | |
public byte[] Bytes | |
{ | |
get | |
{ | |
var arr = new byte[Count]; | |
for (int i = 0; i < Count; i++) | |
arr[i] = _pointer[i]; | |
return arr; | |
} | |
} | |
public Memory(int count) | |
{ | |
Count = 0; | |
MaxCount = 0; | |
if (count < 1) | |
{ | |
_pointer = new Pointer<byte>(); | |
return; | |
} | |
MaxCount = (int)((UInt32) count).To2ndPower(); | |
_pointer = new Pointer<byte>(Marshal.AllocHGlobal(sizeof(byte) * MaxCount)); | |
} | |
private void Grow(int count) | |
{ | |
if (count < 1) | |
return; | |
Marshal.ReAllocHGlobal((IntPtr)_pointer, (IntPtr)(sizeof(byte) * (MaxCount += (int)((UInt32)count).To2ndPower()))); | |
} | |
private void Grow() => Grow(MaxCount); | |
public void Write(byte b) | |
{ | |
if (Count >= MaxCount - 1) | |
Grow(); | |
_pointer[Count++] = b; | |
} | |
public void Write(byte b, int index) | |
{ | |
if (index >= MaxCount - 1) | |
Grow(index - MaxCount); | |
_pointer[index] = b; | |
} | |
public void Write(byte[] bytes) | |
{ | |
if (Count + bytes.Length >= MaxCount - 1) | |
Grow(); | |
foreach (byte b in bytes) | |
_pointer[Count++] = b; | |
} | |
public void Write(byte[] bytes, int index) | |
{ | |
if (index + bytes.Length >= MaxCount - 1) | |
Grow(index + bytes.Length - MaxCount); | |
for (int i = index, j = 0; j < bytes.Length; j++, i++) | |
_pointer[i] = bytes[j]; | |
} | |
public void Reset() => Count = 0; | |
public void Clear() | |
{ | |
Reset(); | |
for (int i = 0; i < MaxCount; i++) | |
_pointer[i] = 0; | |
} | |
public byte this[int index] | |
{ | |
get => index > MaxCount ? throw new IndexOutOfRangeException($"Index {index} is out of range for memory (max {MaxCount} bytes)") | |
: _pointer[index]; | |
set | |
{ | |
if (index > MaxCount) | |
Grow(index - MaxCount); | |
_pointer[index] = value; | |
} | |
} | |
public void Dispose() | |
{ | |
Marshal.FreeHGlobal((IntPtr)_pointer); | |
GC.SuppressFinalize(this); | |
} | |
} |
Author
Frityet
commented
Mar 27, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment