Blizzardo1 icon

Memory<T> Testing

Blizzardo1 | PRO | 07/18/22 08:46:35 PM UTC | 0 ⭐ | 1300 👁️ | Never ⏰ | []
C# |

2.43 KB

|

None

|

0 👍

/

0 👎

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

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎