/* Copyright 2010-2014 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace MongoDB.Bson.IO { /// /// An IBsonBuffer that only has a single chunk. /// public class SingleChunkBuffer : ByteArrayBuffer { // private fields private BsonChunk _chunk; // constructors /// /// Initializes a new instance of the class. /// /// The chunk. /// The slice offset. /// The length. /// Whether the buffer is read only. public SingleChunkBuffer(BsonChunk chunk, int sliceOffset, int length, bool isReadOnly) : base(GetChunkBytes(chunk), sliceOffset, length, isReadOnly) { _chunk = chunk; chunk.IncrementReferenceCount(); } // public methods /// /// Gets a slice of this buffer. /// /// The position of the start of the slice. /// The length of the slice. /// /// A slice of this buffer. /// /// SingleChunkBuffer /// GetSlice can only be called for read only buffers. /// /// position /// or /// length /// public override IByteBuffer GetSlice(int position, int length) { ThrowIfDisposed(); EnsureIsReadOnly(); if (position < 0 || position >= Length) { throw new ArgumentOutOfRangeException("position"); } if (length <= 0 || length > Length - position) { throw new ArgumentOutOfRangeException("length"); } return new SingleChunkBuffer(_chunk, SliceOffset + position, length, true); } // protected methods /// /// Clears this instance. /// /// SingleChunkBuffer /// Write operations are not allowed for read only buffers. public override void Clear() { ThrowIfDisposed(); EnsureIsWritable(); Length = 0; } /// /// Releases unmanaged and - optionally - managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected override void Dispose(bool disposing) { if (!Disposed) { if (disposing) { if (_chunk != null) { _chunk.DecrementReferenceCount(); _chunk = null; } } } base.Dispose(disposing); } // private static methods private static byte[] GetChunkBytes(BsonChunk chunk) { if (chunk == null) { throw new ArgumentNullException("chunk"); } return chunk.Bytes; } } }