Esempio n. 1
0
        public void Test_MemoryBufferWriterOfT_AllocateAndGetMemoryAndSpan()
        {
            Memory <byte> memory = new byte[256];

            var writer = new MemoryBufferWriter <byte>(memory);

            Assert.AreEqual(writer.Capacity, 256);
            Assert.AreEqual(writer.FreeCapacity, 256);
            Assert.AreEqual(writer.WrittenCount, 0);
            Assert.IsTrue(writer.WrittenMemory.IsEmpty);
            Assert.IsTrue(writer.WrittenSpan.IsEmpty);

            Span <byte> span = writer.GetSpan(43);

            Assert.AreEqual(span.Length, memory.Length);

            writer.Advance(43);

            Assert.AreEqual(writer.Capacity, 256);
            Assert.AreEqual(writer.FreeCapacity, 256 - 43);
            Assert.AreEqual(writer.WrittenCount, 43);
            Assert.AreEqual(writer.WrittenMemory.Length, 43);
            Assert.AreEqual(writer.WrittenSpan.Length, 43);

            Assert.AreEqual(memory.Length - 43, writer.GetSpan().Length);
            Assert.AreEqual(memory.Length - 43, writer.GetMemory().Length);
            Assert.AreEqual(memory.Length - 43, writer.GetSpan(22).Length);
            Assert.AreEqual(memory.Length - 43, writer.GetMemory(22).Length);

            Assert.ThrowsException <ArgumentOutOfRangeException>(() => writer.Advance(-1));
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => writer.GetMemory(-1));
            Assert.ThrowsException <ArgumentException>(() => writer.GetSpan(1024));
            Assert.ThrowsException <ArgumentException>(() => writer.GetMemory(1024));
            Assert.ThrowsException <ArgumentException>(() => writer.Advance(1024));
        }
        public void GetMemoryAllocatesNewSegmentWhenInsufficientSpaceInCurrentSegment()
        {
            // Have the buffer writer rent only the minimum size segments from the pool.
            using (var bufferWriter = new MemoryBufferWriter(MinimumSegmentSize))
            {
                var data = new byte[MinimumSegmentSize];
                new Random().NextBytes(data);

                // Write half the minimum segment size
                bufferWriter.Write(data.AsSpan(0, MinimumSegmentSize / 2));

                // Request a new buffer of MinimumSegmentSize
                var buffer = bufferWriter.GetMemory(MinimumSegmentSize);
                Assert.Equal(MinimumSegmentSize, buffer.Length);

                // Write to the buffer
                bufferWriter.Write(data);

                // Verify the data was all written correctly
                var expectedOutput = new byte[MinimumSegmentSize + (MinimumSegmentSize / 2)];
                data.AsSpan(0, MinimumSegmentSize / 2).CopyTo(expectedOutput.AsSpan(0, MinimumSegmentSize / 2));
                data.CopyTo(expectedOutput, MinimumSegmentSize / 2);
                Assert.Equal(expectedOutput, bufferWriter.ToArray());
            }
        }