public PacketBuffer(PoolableMemory buffer, bool writeable, bool clearBuffer = false)
 {
     this.buffer      = buffer.Memory;
     rented           = buffer.RentedBuffer;
     CanWrite         = writeable;
     this.clearBuffer = clearBuffer;
 }
        public PoolableMemory ReadPooledArray(int length)
        {
            PrepareRead(length);
            PoolableMemory value = PoolableMemory.Allocate(length, true);

            buffer.Slice(position, length).CopyTo(value.Memory);
            position += sizeof(ushort) + length;
            return(value);
        }
        public PoolableMemory ReadMediumPooledArray()
        {
            PrepareRead(sizeof(ushort));
            ushort length = Unsafe.ReadUnaligned <ushort>(ref buffer.Span[position]);

            if (!BitConverter.IsLittleEndian)
            {
                length = BinaryPrimitives.ReverseEndianness(length);
            }
            PrepareRead(sizeof(ushort) + length);
            PoolableMemory value = PoolableMemory.Allocate(length, true);

            buffer.Slice(position + sizeof(ushort), length).CopyTo(value.Memory);
            position += sizeof(ushort) + length;
            return(value);
        }
 private void Allocate(int length)
 {
     if (length > 0)
     {
         PoolableMemory old    = new PoolableMemory(buffer, rented);
         PoolableMemory memory = PoolableMemory.Allocate(length, false);
         old.Memory.CopyTo(memory.Memory);
         old.Return(clearBuffer);
         buffer = memory.Memory;
         rented = memory.RentedBuffer;
     }
     else
     {
         buffer = Memory <byte> .Empty;
     }
 }