public void BsonBinaryReader_should_support_reading_multiple_documents(
            [Range(0, 3)]
            int numberOfDocuments)
        {
            var document = new BsonDocument("x", 1);
            var bson = document.ToBson();
            var input = Enumerable.Repeat(bson, numberOfDocuments).Aggregate(Enumerable.Empty<byte>(), (a, b) => a.Concat(b)).ToArray();
            var expectedResult = Enumerable.Repeat(document, numberOfDocuments);

            using (var stream = new MemoryStream(input))
            using (var binaryReader = new BsonBinaryReader(stream))
            {
                var result = new List<BsonDocument>();

                while (!binaryReader.IsAtEndOfFile())
                {
                    binaryReader.ReadStartDocument();
                    var name = binaryReader.ReadName();
                    var value = binaryReader.ReadInt32();
                    binaryReader.ReadEndDocument();

                    var resultDocument = new BsonDocument(name, value);
                    result.Add(resultDocument);
                }

                result.Should().Equal(expectedResult);
            }
        }
        public void TestIsAtEndOfFileWithTwoDocuments()
        {
            var expected = new BsonDocument("x", 1);

            byte[] bson;
            using (var stream = new MemoryStream())
            using (var writer = new BsonBinaryWriter(stream))
            {
                BsonSerializer.Serialize(writer, expected);
                BsonSerializer.Serialize(writer, expected);
                bson = stream.ToArray();
            }

            using (var stream = new MemoryStream(bson))
            using (var reader = new BsonBinaryReader(stream))
            {
                var count = 0;
                while (!reader.IsAtEndOfFile())
                {
                    var document = BsonSerializer.Deserialize<BsonDocument>(reader);
                    Assert.AreEqual(expected, document);
                    count++;
                }
                Assert.AreEqual(2, count);
            }
        }
        public void BsonBinaryReader_should_support_reading_more_than_2GB()
        {
            RequireEnvironmentVariable.IsDefined("EXPLICIT");

            var binaryData = new BsonBinaryData(new byte[1024 * 1024]);

            var tempFileName = Path.GetTempFileName();
            try
            {
                using (var stream = new FileStream(tempFileName, FileMode.Open))
                {
                    using (var binaryWriter = new BsonBinaryWriter(stream))
                    {
                        while (stream.Position < (long)int.MaxValue * 4)
                        {
                            binaryWriter.WriteStartDocument();
                            binaryWriter.WriteName("x");
                            binaryWriter.WriteBinaryData(binaryData);
                            binaryWriter.WriteEndDocument();
                        }
                    }

                    var endOfFilePosition = stream.Position;
                    stream.Position = 0;

                    using (var binaryReader = new BsonBinaryReader(stream))
                    {
                        while (!binaryReader.IsAtEndOfFile())
                        {
                            binaryReader.ReadStartDocument();
                            var bookmark = binaryReader.GetBookmark();

                            binaryReader.ReadName("x");
                            binaryReader.ReturnToBookmark(bookmark);

                            binaryReader.ReadName("x");
                            var readBinaryData = binaryReader.ReadBinaryData();
                            Assert.Equal(binaryData.Bytes.Length, readBinaryData.Bytes.Length);

                            binaryReader.ReadEndDocument();
                        }
                    }

                    Assert.Equal(endOfFilePosition, stream.Position);
                }
            }
            finally
            {
                try
                {
                    File.Delete(tempFileName);
                }
                catch
                {
                    // ignore exceptions
                }
            }
        }
 public void Constructor_should_not_throw_if_only_binaryReader_is_provided()
 {
     using (var stream = new MemoryStream())
     using (var binaryReader = new BsonBinaryReader(stream))
     {
         Action action = () => new DeleteMessageBinaryEncoder(binaryReader, null);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_should_not_throw_if_only_binaryReader_is_provided()
 {
     using (var stream = new MemoryStream())
     using (var binaryReader = new BsonBinaryReader(stream))
     {
         Action action = () => new InsertMessageBinaryEncoder<BsonDocument>(binaryReader, null, __serializer);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_with_two_parameters_should_not_throw_if_only_binaryReader_is_provided()
 {
     using (var stream = new MemoryStream())
     using (var binaryReader = new BsonBinaryReader(stream))
     {
         Action action = () => new BinaryMessageEncoderFactory(binaryReader, null);
         action.ShouldNotThrow();
     }
 }
 public void Constructor_should_not_throw_if_binaryReader_and_binaryWriter_are_both_provided()
 {
     using (var stream = new MemoryStream())
     using (var binaryReader = new BsonBinaryReader(stream))
     using (var binaryWriter = new BsonBinaryWriter(stream))
     {
         Action action = () => new GetMoreMessageBinaryEncoder(binaryReader, binaryWriter);
         action.ShouldNotThrow();
     }
 }
 public void TestHelloWorld()
 {
     string byteString = @"\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00";
     byte[] bytes = DecodeByteString(byteString);
     var stream = new MemoryStream(bytes);
     using (var bsonReader = new BsonBinaryReader(stream))
     {
         bsonReader.ReadStartDocument();
         Assert.AreEqual(BsonType.String, bsonReader.ReadBsonType());
         Assert.AreEqual("hello", bsonReader.ReadName());
         Assert.AreEqual("world", bsonReader.ReadString());
         bsonReader.ReadEndDocument();
     }
 }
 public void TestBsonAwesome()
 {
     string byteString = @"1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00";
     byte[] bytes = DecodeByteString(byteString);
     var stream = new MemoryStream(bytes);
     using (var bsonReader = new BsonBinaryReader(stream))
     {
         bsonReader.ReadStartDocument();
         Assert.AreEqual(BsonType.Array, bsonReader.ReadBsonType());
         Assert.AreEqual("BSON", bsonReader.ReadName());
         bsonReader.ReadStartArray();
         Assert.AreEqual(BsonType.String, bsonReader.ReadBsonType());
         Assert.AreEqual("awesome", bsonReader.ReadString());
         Assert.AreEqual(BsonType.Double, bsonReader.ReadBsonType());
         Assert.AreEqual(5.05, bsonReader.ReadDouble());
         Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType());
         Assert.AreEqual(1986, bsonReader.ReadInt32());
         bsonReader.ReadEndArray();
         bsonReader.ReadEndDocument();
     }
 }
        /// <summary>
        /// Tests whether the array contains a value.
        /// </summary>
        /// <param name="value">The value to test for.</param>
        /// <returns>True if the array contains the value.</returns>
        public override bool Contains(BsonValue value)
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);

                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.SkipName();
                    if (DeserializeBsonValue(context).Equals(value))
                    {
                        return true;
                    }
                }
                bsonReader.ReadEndDocument();

                return false;
            }
        }
        public override void CopyTo(object[] array, int arrayIndex)
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);

                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.SkipName();
                    array[arrayIndex++] = DeserializeBsonValue(context).RawValue;
                }
                bsonReader.ReadEndDocument();
            }
        }
 // private methods
 private BsonDocument Deserialize(byte[] bson, PartiallyRawBsonDocumentSerializer serializer)
 {
     using (var stream = new MemoryStream(bson))
     using (var reader = new BsonBinaryReader(stream))
     {
         var context = BsonDeserializationContext.CreateRoot(reader);
         return serializer.Deserialize(context);
     }
 }
        // public indexers
        /// <summary>
        /// Gets or sets a value by position.
        /// </summary>
        /// <param name="index">The position.</param>
        /// <returns>The value.</returns>
        public override BsonValue this[int index]
        {
            get
            {
                if (index < 0)
                {
                    throw new ArgumentOutOfRangeException("index");
                }
                ThrowIfDisposed();

                using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
                using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
                {
                    bsonReader.ReadStartDocument();
                    var i = 0;
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        bsonReader.SkipName();
                        if (i == index)
                        {
                            var context = BsonDeserializationContext.CreateRoot(bsonReader);
                            return DeserializeBsonValue(context);
                        }

                        bsonReader.SkipValue();
                        i++;
                    }
                    bsonReader.ReadEndDocument();

                    throw new ArgumentOutOfRangeException("index");
                }
            }
            set
            {
                throw new NotSupportedException("RawBsonArray instances are immutable.");
            }
        }
 public void WriteMessage_should_throw_if_binaryWriter_was_not_provided()
 {
     using (var stream = new MemoryStream())
     using (var binaryReader = new BsonBinaryReader(stream))
     {
         var subject = new DeleteMessageBinaryEncoder(binaryReader, null);
         Action action = () => subject.WriteMessage(__testMessage);
         action.ShouldThrow<InvalidOperationException>();
     }
 }
 public override void CopyTo(object[] array, int arrayIndex)
 {
     ThrowIfDisposed();
     using (var bsonReader = new BsonBinaryReader(new BsonBuffer(CloneSlice(), false), true, _readerSettings))
     {
         bsonReader.ReadStartDocument();
         while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
         {
             bsonReader.SkipName();
             array[arrayIndex++] = DeserializeBsonValue(bsonReader).RawValue;
         }
         bsonReader.ReadEndDocument();
     }
 }
        /// <summary>
        /// Tries to get the value of an element of this document.
        /// </summary>
        /// <param name="name">The name of the element.</param>
        /// <param name="value">The value of the element.</param>
        /// <returns>
        /// True if an element with that name was found.
        /// </returns>
        public override bool TryGetValue(string name, out BsonValue value)
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);
                
                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    if (bsonReader.ReadName() == name)
                    {
                        value = DeserializeBsonValue(context);
                        return true;
                    }

                    bsonReader.SkipValue();
                }
                bsonReader.ReadEndDocument();

                value = null;
                return false;
            }
        }
 private BsonValue DeserializeBsonValue(BsonBinaryReader bsonReader)
 {
     switch (bsonReader.GetCurrentBsonType())
     {
         case BsonType.Array: return DeserializeRawBsonArray(bsonReader);
         case BsonType.Document: return DeserializeRawBsonDocument(bsonReader);
         default: return (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
     }
 }
        /// <summary>
        /// Writes a raw BSON array.
        /// </summary>
        /// <param name="slice">The byte buffer containing the raw BSON array.</param>
        public virtual void WriteRawBsonArray(IByteBuffer slice)
        {
            // overridden in BsonBinaryWriter

            using (var bsonBuffer = new BsonBuffer())
            {
                BsonArray array;

                // wrap the array in a fake document so we can deserialize it
                var arrayLength = slice.Length;
                var documentLength = arrayLength + 8;
                bsonBuffer.WriteInt32(documentLength);
                bsonBuffer.WriteByte((byte)BsonType.Array);
                bsonBuffer.WriteByte((byte)'x');
                bsonBuffer.WriteByte((byte)0);
                bsonBuffer.ByteBuffer.WriteBytes(slice);
                bsonBuffer.WriteByte((byte)0);

                bsonBuffer.Position = 0;
                using (var bsonReader = new BsonBinaryReader(bsonBuffer, true, BsonBinaryReaderSettings.Defaults))
                {
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadName("x");
                    array = (BsonArray)BsonArraySerializer.Instance.Deserialize(bsonReader, typeof(BsonArray), null);
                    bsonReader.ReadEndDocument();
                }

                BsonArraySerializer.Instance.Serialize(this, typeof(BsonArray), array, null);
            }
        }
 /// <summary>
 /// Gets an enumerator that can enumerate the elements of the array.
 /// </summary>
 /// <returns>An enumerator.</returns>
 public override IEnumerator<BsonValue> GetEnumerator()
 {
     ThrowIfDisposed();
     using (var bsonReader = new BsonBinaryReader(new BsonBuffer(CloneSlice(), false), true, _readerSettings))
     {
         bsonReader.ReadStartDocument();
         while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
         {
             bsonReader.SkipName();
             yield return DeserializeBsonValue(bsonReader);
         }
         bsonReader.ReadEndDocument();
     }
 }
        public void ReadMessage_should_decode_flags_correctly(int flags, bool isUpsert, bool isMulti)
        {
            var bytes = (byte[])__testMessageBytes.Clone();
            bytes[__flagsOffset] = (byte)flags;

            using (var stream = new MemoryStream(bytes))
            using (var binaryReader = new BsonBinaryReader(stream))
            {
                var subject = new UpdateMessageBinaryEncoder(stream, __messageEncoderSettings);
                var message = subject.ReadMessage();
                message.IsMulti.Should().Be(isMulti);
                message.IsUpsert.Should().Be(isUpsert);
            }
        }
        /// <summary>
        /// Gets the index of a value in the array.
        /// </summary>
        /// <param name="value">The value to search for.</param>
        /// <param name="index">The zero based index at which to start the search.</param>
        /// <param name="count">The number of elements to search.</param>
        /// <returns>The zero based index of the value (or -1 if not found).</returns>
        public override int IndexOf(BsonValue value, int index, int count)
        {
            ThrowIfDisposed();
            using (var bsonReader = new BsonBinaryReader(new BsonBuffer(CloneSlice(), false), true, _readerSettings))
            {
                bsonReader.ReadStartDocument();
                var i = 0;
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.SkipName();
                    if (i >= index)
                    {
                        if (count == 0)
                        {
                            return -1;
                        }

                        if (DeserializeBsonValue(bsonReader).Equals(value))
                        {
                            return i;
                        }

                        count--;
                    }
                    else
                    {
                        bsonReader.SkipValue();
                    }

                    i++;
                }
                bsonReader.ReadEndDocument();

                return -1;
            }
        }
 private RawBsonArray DeserializeRawBsonArray(BsonBinaryReader bsonReader)
 {
     var slice = bsonReader.ReadRawBsonArray();
     var nestedArray = new RawBsonArray(slice);
     _disposableItems.Add(nestedArray);
     return nestedArray;
 }
        /// <summary>
        /// Gets an enumerator that can enumerate the elements of the array.
        /// </summary>
        /// <returns>An enumerator.</returns>
        public override IEnumerator<BsonValue> GetEnumerator()
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);

                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.SkipName();
                    yield return DeserializeBsonValue(context);
                }
                bsonReader.ReadEndDocument();
            }
        }
 public void ReadMessage_should_read_a_message()
 {
     using (var stream = new MemoryStream(__testMessageBytes))
     using (var binaryReader = new BsonBinaryReader(stream))
     {
         var subject = new DeleteMessageBinaryEncoder(binaryReader, null);
         var message = subject.ReadMessage();
         message.CollectionName.Should().Be(__collectionName);
         message.DatabaseName.Should().Be(__databaseName);
         message.IsMulti.Should().Be(__isMulti);
         message.Query.Should().Be(__query);
         message.RequestId.Should().Be(__requestId);
     }
 }
        /// <summary>
        /// Gets the index of a value in the array.
        /// </summary>
        /// <param name="value">The value to search for.</param>
        /// <param name="index">The zero based index at which to start the search.</param>
        /// <param name="count">The number of elements to search.</param>
        /// <returns>The zero based index of the value (or -1 if not found).</returns>
        public override int IndexOf(BsonValue value, int index, int count)
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);

                bsonReader.ReadStartDocument();
                var i = 0;
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    bsonReader.SkipName();
                    if (i >= index)
                    {
                        if (count == 0)
                        {
                            return -1;
                        }

                        if (DeserializeBsonValue(context).Equals(value))
                        {
                            return i;
                        }

                        count--;
                    }
                    else
                    {
                        bsonReader.SkipValue();
                    }

                    i++;
                }
                bsonReader.ReadEndDocument();

                return -1;
            }
        }
 private RawBsonDocument DeserializeRawBsonDocument(BsonBinaryReader bsonReader)
 {
     var slice = bsonReader.ReadRawBsonDocument();
     var nestedDocument = new RawBsonDocument(slice);
     _disposableItems.Add(nestedDocument);
     return nestedDocument;
 }
 /// <summary>
 /// Creates a BsonReader for a BSON Stream.
 /// </summary>
 /// <param name="stream">The BSON Stream.</param>
 /// <param name="settings">Optional reader settings.</param>
 /// <returns>A BsonReader.</returns>
 public static BsonReader Create(Stream stream, BsonBinaryReaderSettings settings)
 {
     var reader = new BsonBinaryReader(null, settings);
     reader.Buffer.LoadFrom(stream);
     return reader;
 }
        /// <summary>
        /// Tests whether the document contains an element with the specified name.
        /// </summary>
        /// <param name="name">The name of the element to look for.</param>
        /// <returns>
        /// True if the document contains an element with the specified name.
        /// </returns>
        public override bool Contains(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            ThrowIfDisposed();

            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    if (bsonReader.ReadName() == name)
                    {
                        return true;
                    }
                    bsonReader.SkipValue();
                }
                bsonReader.ReadEndDocument();

                return false;
            }
        }
 /// <summary>
 /// Writes a raw BSON document.
 /// </summary>
 /// <param name="slice">The byte buffer containing the raw BSON document.</param>
 public virtual void WriteRawBsonDocument(IByteBuffer slice)
 {
     // overridden in BsonBinaryWriter
     using (var bsonReader = new BsonBinaryReader(new BsonBuffer(slice, false), true, BsonBinaryReaderSettings.Defaults))
     {
         var document = BsonSerializer.Deserialize<BsonDocument>(bsonReader);
         BsonDocumentSerializer.Instance.Serialize(this, typeof(BsonDocument), document, null);
     }
 }
        /// <summary>
        /// Gets an element of this document.
        /// </summary>
        /// <param name="index">The zero based index of the element.</param>
        /// <returns>
        /// The element.
        /// </returns>
        public override BsonElement GetElement(int index)
        {
            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }
            ThrowIfDisposed();

            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);
                
                bsonReader.ReadStartDocument();
                var i = 0;
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    if (i == index)
                    {
                        var name = bsonReader.ReadName();
                        var value = DeserializeBsonValue(context);
                        return new BsonElement(name, value);
                    }

                    bsonReader.SkipName();
                    bsonReader.SkipValue();
                    i++;
                }
                bsonReader.ReadEndDocument();

                throw new ArgumentOutOfRangeException("index");
            }
        }