/* Copyright 2013-2015 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
{
///
/// Represents a chunk backed by a byte array.
///
public class ByteArrayChunk : IBsonChunk
{
#region static
private static byte[] CreateByteArray(int size)
{
if (size < 0)
{
throw new ArgumentOutOfRangeException("size");
}
return new byte[size];
}
#endregion
// fields
private byte[] _bytes;
private bool _disposed;
// constructors
///
/// Initializes a new instance of the class.
///
/// The size.
public ByteArrayChunk(int size)
: this(CreateByteArray(size))
{
}
///
/// Initializes a new instance of the class.
///
/// The bytes.
/// bytes
public ByteArrayChunk(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
_bytes = bytes;
}
// properties
///
public ArraySegment Bytes
{
get
{
ThrowIfDisposed();
return new ArraySegment(_bytes);
}
}
// methods
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
public IBsonChunk Fork()
{
ThrowIfDisposed();
return new ByteArrayChunk(_bytes);
}
///
/// Releases unmanaged and - optionally - managed resources.
///
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_bytes = null;
}
_disposed = true;
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
}
}