A BSON buffer that is backed by a byte array.
Inheritance: IByteBuffer
Exemplo n.º 1
0
        public void AccessBackingBytes_should_adjust_count()
        {
            var bytes = new byte[4];
            var buffer = new ByteArrayBuffer(bytes, isReadOnly: true);
            var subject = new ByteBufferSlice(buffer, 1, 2);

            var result = subject.AccessBackingBytes(0);

            result.Count.Should().Be(2); // not 3
        }
 public void TestAccessBackingBytes()
 {
     var backingBytes = new byte[100];
     using (var buffer = new ByteArrayBuffer(backingBytes, 10, 80, false))
     {
         var segment = buffer.AccessBackingBytes(20);
         Assert.AreSame(backingBytes, segment.Array);
         Assert.AreEqual(30, segment.Offset);
         Assert.AreEqual(60, segment.Count);
     }
 }
 public void TestWriteByte()
 {
     var backingBytes = new byte[100];
     using (var buffer = new ByteArrayBuffer(backingBytes, 10, 80, false))
     {
         Assert.AreEqual(0, backingBytes[30]);
         Assert.AreEqual(0, backingBytes[31]);
         buffer.WriteByte(20, 1);
         Assert.AreEqual(1, backingBytes[30]);
         Assert.AreEqual(0, backingBytes[31]);
     }
 }
 public void TestWriteBackingBytes()
 {
     var backingBytes = new byte[100];
     using (var buffer = new ByteArrayBuffer(backingBytes, 0, 0, false))
     {
         var segment = buffer.WriteBackingBytes(10);
         Assert.AreSame(backingBytes, segment.Array);
         Assert.AreEqual(0, segment.Offset);
         Assert.AreEqual(10, segment.Count);
         buffer.Position += 1;
         Assert.AreEqual(1, buffer.Position);
         Assert.AreEqual(1, buffer.Length);
     }
 }
 public void TestWriteByte()
 {
     var backingBytes = new byte[100];
     using (var buffer = new ByteArrayBuffer(backingBytes, 0, 0, false))
     {
         Assert.AreEqual(0, backingBytes[0]);
         Assert.AreEqual(0, backingBytes[1]);
         buffer.WriteByte(1);
         Assert.AreEqual(1, backingBytes[0]);
         Assert.AreEqual(0, backingBytes[1]);
         Assert.AreEqual(1, buffer.Position);
         Assert.AreEqual(1, buffer.Length);
     }
 }
        public void TestWriteTo()
        {
            var backingBytes = new byte[100];
            using (var buffer = new ByteArrayBuffer(backingBytes, 10, 80, false))
            {
                buffer.WriteBytes(0, new[] { (byte)1, (byte)2 }, 0, 2);
                buffer.Length = 2;

                using (var memoryStream = new MemoryStream())
                {
                    buffer.WriteTo(memoryStream);
                    Assert.AreEqual(2, memoryStream.Length);
                }
            }
        }
        public void TestWriteBytes()
        {
            var bytes = new[] { (byte)1, (byte)2 };

            var backingBytes = new byte[100];
            using (var buffer = new ByteArrayBuffer(backingBytes, 10, 80, false))
            {
                Assert.AreEqual(0, backingBytes[30]);
                Assert.AreEqual(0, backingBytes[31]);
                Assert.AreEqual(0, backingBytes[32]);
                buffer.WriteBytes(20, bytes, 0, bytes.Length);
                Assert.AreEqual(1, backingBytes[30]);
                Assert.AreEqual(2, backingBytes[31]);
                Assert.AreEqual(0, backingBytes[32]);
            }
        }
        public void TestWriteBytesFromByteBuffer()
        {
            var bytes = new[] { (byte)1, (byte)2 };
            var source = new ByteArrayBuffer(bytes, 0, bytes.Length, true);

            var backingBytes = new byte[100];
            using (var buffer = new ByteArrayBuffer(backingBytes, 0, 0, false))
            {
                Assert.AreEqual(0, backingBytes[0]);
                Assert.AreEqual(0, backingBytes[1]);
                Assert.AreEqual(0, backingBytes[2]);
                buffer.WriteBytes(source);
                Assert.AreEqual(1, backingBytes[0]);
                Assert.AreEqual(2, backingBytes[1]);
                Assert.AreEqual(0, backingBytes[2]);
                Assert.AreEqual(2, buffer.Position);
                Assert.AreEqual(2, buffer.Length);
            }
        }
Exemplo n.º 9
0
        public void constructor_should_initialize_subject()
        {
            var buffer = new ByteArrayBuffer(new byte[3], isReadOnly: true);

            var subject = new ByteBufferSlice(buffer, 1, 2);

            var reflector = new Reflector(subject);
            subject.Buffer.Should().BeSameAs(buffer);
            reflector._disposed.Should().BeFalse();
            reflector._offset.Should().Be(1);
            reflector._length.Should().Be(2);
        }
 public Reflector(ByteArrayBuffer instance)
 {
     _instance = instance;
 }
        public void constructor_with_bytes_should_initialize_subject(
            [Values(false, true)]
            bool isReadOnly)
        {
            var bytes = new byte[1];

            var subject = new ByteArrayBuffer(bytes, isReadOnly);

            var reflector = new Reflector(subject);
            subject.IsReadOnly.Should().Be(isReadOnly);
            subject.Length.Should().Be(bytes.Length);
            reflector._bytes.Should().BeSameAs(bytes);
            reflector._disposed.Should().BeFalse();
        }
        public async Task WriteBytesAsync_should_have_expected_effect_for_offset(int offset, byte[] expectedBytes)
        {
            var stream = new MemoryStream();
            var source = new ByteArrayBuffer(new byte[] { 1, 2, 3 });

            await stream.WriteBytesAsync(source, offset, 1, CancellationToken.None);

            stream.ToArray().Should().Equal(expectedBytes);
        }
Exemplo n.º 13
0
        public void constructor_should_throw_when_offset_is_out_of_range(
            [Values(-1, 2)]
            int offset)
        {
            var buffer = new ByteArrayBuffer(new byte[1], isReadOnly: true);

            Action action = () => new ByteBufferSlice(buffer, offset, 0);

            action.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be("offset");
        }
        /// <inheritdoc/>
        public IByteBuffer GetSlice(int position, int length)
        {
            ThrowIfDisposed();
            if (position < 0 || position > _length)
            {
                throw new ArgumentOutOfRangeException("position");
            }
            if (length < 0 || position + length > _length)
            {
                throw new ArgumentOutOfRangeException("length");
            }
            EnsureIsReadOnly();

            var forkedBuffer = new ByteArrayBuffer(_bytes, _length, isReadOnly: true);
            return new ByteBufferSlice(forkedBuffer, position, length);
        }
        public async Task ReadBytesAsync_with_byte_buffer_should_have_expected_effect_for_partial_reads(int testCase, int[] partition)
        {
            var bytes = new byte[] { 1, 2, 3 };
            var mockStream = new Mock<Stream>();
            var destination = new ByteArrayBuffer(new byte[3], 3);
            var n = 0;
            var position = 0;
            mockStream.Setup(s => s.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
                .Returns((byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
                {
                    var length = partition[n++];
                    Buffer.BlockCopy(bytes, position, buffer, offset, length);
                    position += length;
                    return Task.FromResult(length);
                });

            await mockStream.Object.ReadBytesAsync(destination, 0, 3, CancellationToken.None);

            destination.AccessBackingBytes(0).Array.Should().Equal(bytes);
        }
        public void WriteSlice_should_have_expected_effect(
            [Values(0, 1, 2, 16)]
            int length)
        {
            using (var memoryStream = new MemoryStream())
            using (var stream = new BsonStreamAdapter(memoryStream))
            {
                var bytes = Enumerable.Range(0, length).Select(n => (byte)n).ToArray();
                var slice = new ByteArrayBuffer(bytes, isReadOnly: true);

                stream.WriteSlice(slice);

                memoryStream.ToArray().Should().Equal(bytes);
            }
        }
Exemplo n.º 17
0
        public void constructor_should_throw_when_buffer_is_not_readonly()
        {
            var buffer = new ByteArrayBuffer(new byte[1], isReadOnly: false);

            Action action = () => new ByteBufferSlice(buffer, 0, 0);

            action.ShouldThrow<ArgumentException>().And.ParamName.Should().Be("buffer");
        }
Exemplo n.º 18
0
        public void constructor_should_throw_when_length_is_out_of_range(int size, int offset, int length)
        {
            var buffer = new ByteArrayBuffer(new byte[size], isReadOnly: true);

            Action action = () => new ByteBufferSlice(buffer, offset, length);

            action.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be("length");
        }
Exemplo n.º 19
0
 // helper methods
 public ByteBufferSlice CreateSubject(int size = 3, int offset = 1, int length = 2)
 {
     var buffer = new ByteArrayBuffer(new byte[size], isReadOnly: true);
     return new ByteBufferSlice(buffer, offset, length);
 }
        public void ThrowIfEndOfStream_should_throw_when_position_plus_length_exceeds_2GB()
        {
            using (var buffer = new ByteArrayBuffer(new byte[1024]))
            using (var subject = new ByteBufferStream(buffer))
            {
                subject.Position = 1024;
                subject.WriteInt32(int.MaxValue - 128);
                subject.Position = 1024;

                Action action = () => subject.ReadSlice(); // indirectly calls private ThrowIfEndOfStream method

                action.ShouldThrow<EndOfStreamException>();
            }
        }
            private IByteBuffer RemoveOverflow(BsonBuffer buffer)
            {
                var lastRequestLength = buffer.Position - _lastRequestPosition;
                buffer.Position = _lastRequestPosition;
                var lastArrayItem = buffer.ReadBytes(lastRequestLength);
                if ((BsonType)lastArrayItem[0] != BsonType.Document)
                {
                    throw new MongoInternalException("Expected overflow item to be a BsonDocument.");
                }
                var sliceOffset = Array.IndexOf<byte>(lastArrayItem, 0) + 1; // skip over type and array index
                var overflow = new ByteArrayBuffer(lastArrayItem, sliceOffset, lastArrayItem.Length - sliceOffset, true);
                buffer.Position = _lastRequestPosition;
                buffer.Length = _lastRequestPosition;

                _batchCount--;
                _batchLength = buffer.Position - _batchStartPosition;

                return overflow;
            }
        public void WriteSlice_should_have_expected_effect(
            [Values(0, 1, 2, 16)]
            int length,
            [Values(1, 2, 3)]
            int numberOfChunks)
        {
            numberOfChunks = length == 0 ? 1 : length < numberOfChunks ? length : numberOfChunks;

            using (var memoryStream = new MemoryStream())
            using (var stream = new BsonStreamAdapter(memoryStream))
            {
                IByteBuffer slice;
                var bytes = Enumerable.Range(0, length).Select(n => (byte)n).ToArray();
                if (numberOfChunks == 1)
                {
                    slice = new ByteArrayBuffer(bytes, isReadOnly: true);
                }
                else
                {
                    var chunkSize = length / numberOfChunks;
                    var chunks = Enumerable.Range(0, numberOfChunks)
                        .Select(i => bytes.Skip(i * chunkSize).Take(i < numberOfChunks - 1 ? chunkSize : int.MaxValue).ToArray())
                        .Select(b => new ByteArrayChunk(b));
                    slice = new MultiChunkBuffer(chunks);
                }

                stream.WriteSlice(slice);

                memoryStream.ToArray().Should().Equal(bytes);
            }
        }
        public async Task ReadBytesAsync_with_byte_buffer_should_have_expected_effect_for_offset(int offset, byte[] expectedBytes)
        {
            var bytes = new byte[] { 1 };
            var stream = new MemoryStream(bytes);
            var destination = new ByteArrayBuffer(new byte[3]);

            await stream.ReadBytesAsync(destination, offset, 1, CancellationToken.None);

            destination.AccessBackingBytes(0).Array.Should().Equal(expectedBytes);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Reads a raw BSON array.
        /// </summary>
        /// <returns>The raw BSON array.</returns>
        public virtual IByteBuffer ReadRawBsonArray()
        {
            // overridden in BsonBinaryReader to read the raw bytes from the stream
            // for all other streams, deserialize the array and reserialize it using a BsonBinaryWriter to get the raw bytes

            var deserializationContext = BsonDeserializationContext.CreateRoot(this);
            var array = BsonArraySerializer.Instance.Deserialize(deserializationContext);

            using (var memoryStream = new MemoryStream())
            using (var bsonWriter = new BsonBinaryWriter(memoryStream, BsonBinaryWriterSettings.Defaults))
            {
                var serializationContext = BsonSerializationContext.CreateRoot(bsonWriter);
                bsonWriter.WriteStartDocument();
                var startPosition = memoryStream.Position + 3; // just past BsonType, "x" and null byte
                bsonWriter.WriteName("x");
                BsonArraySerializer.Instance.Serialize(serializationContext, array);
                var endPosition = memoryStream.Position;
                bsonWriter.WriteEndDocument();

                byte[] memoryStreamBuffer;
#if NETSTANDARD1_5 || NETSTANDARD1_6
                memoryStreamBuffer = memoryStream.ToArray();
#else
                memoryStreamBuffer = memoryStream.GetBuffer();
#endif
                var buffer = new ByteArrayBuffer(memoryStreamBuffer, (int)memoryStream.Length, isReadOnly: true);
                return new ByteBufferSlice(buffer, (int)startPosition, (int)(endPosition - startPosition));
            }
        }
        public async Task ReadBytesAsync_with_byte_buffer_should_have_expected_effect_for_partial_reads(int testCase, int[] partition)
        {
            var bytes = new byte[] { 1, 2, 3 };
            var stream = Substitute.For<Stream>();
            var destination = new ByteArrayBuffer(new byte[3], 3);
            var n = 0;
            var p = 0;
            stream.ReadAsync(Arg.Any<byte[]>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(x =>
            {
                var l = partition[n++];
                var b = (byte[])x[0];
                var o = (int)x[1];
                Buffer.BlockCopy(bytes, p, b, o, l);
                p += l;
                return Task.FromResult(l);
            });

            await stream.ReadBytesAsync(destination, 0, 3, CancellationToken.None);

            destination.AccessBackingBytes(0).Array.Should().Equal(bytes);
        }