Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This should comply and be a safe way to handle Memory<T>.
- // This can actually be used in a class implementation such as:
- // public class MemoryBlock<T> {
- // private Memory<T> block;
- // public MemoryBlock<T>(int size) {
- // block = new(new T[size], 0, size);
- // }
- // }
- // Thus all operations can be wrapped in the class for better memory management.
- // It would be better to just use a MemoryPool<T> and create an owner for proper disposal instead of this hack.
- namespace MemoryTest
- {
- internal static class Program
- {
- private static Memory<byte> _memoryBuffer;
- private static void Alloc(int size)
- {
- byte[] bytes = new byte[size];
- _memoryBuffer = new(bytes, 0, size);
- }
- private static bool Free()
- {
- if(!_memoryBuffer.IsEmpty)
- {
- byte[] nbuff = new byte[_memoryBuffer.Length];
- Memory<byte> destroy = new(nbuff, 0, _memoryBuffer.Length);
- destroy.CopyTo(_memoryBuffer);
- _memoryBuffer = _memoryBuffer.Trim<byte>(0);
- }
- Console.WriteLine("Memory Freed");
- return true;
- }
- private static byte GetMemoryByte(int location)
- {
- return _memoryBuffer.Span[location];
- }
- private static void SetMemory(byte[] buffer)
- {
- var tmp = new Memory<byte>(buffer);
- if(!tmp.TryCopyTo(_memoryBuffer))
- {
- Console.WriteLine("Could not place memory");
- }
- }
- private static void PrintMemory()
- {
- for (int i = 0; i < _memoryBuffer.Length; i++)
- {
- var b = GetMemoryByte(i);
- Console.Write((char)b);
- }
- Console.WriteLine();
- }
- private static void Main(string[] args)
- {
- string msg = "This is a test.";
- Alloc(msg.Length);
- SetMemory(System.Text.Encoding.ASCII.GetBytes(msg));
- PrintMemory();
- Free();
- PrintMemory();
- msg = "Oh look, another test";
- Alloc(msg.Length);
- SetMemory(System.Text.Encoding.ASCII.GetBytes(msg));
- PrintMemory();
- Free();
- PrintMemory();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement