﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReadableWritableDataStorageOnStream.cs" company="Microsoft Corporation">
//   Copyright (c) 2008, 2009, 2010 All Rights Reserved, Microsoft Corporation
//
//   This source is subject to the Microsoft Permissive License.
//   Please see the License.txt file for more information.
//   All other rights reserved.
//
//   THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
//   KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//   IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//   PARTICULAR PURPOSE.
// </copyright>
// <summary>
//   A class encapsulating readable and writeable data stored within a stream.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Exchange.Data.Internal
{
    using System;
    using System.IO;

    /// <summary>
    /// A class encapsulating readable and writeable data stored within a stream.
    /// </summary>
    internal class ReadableWritableDataStorageOnStream : ReadableWritableDataStorage
    {
        /// <summary>
        /// Value indicating whether this class owns the stream and can dispose of it when the class disposes.
        /// </summary>
        private readonly bool ownsStream;

        /// <summary>
        /// The backing stream.
        /// </summary>
        private Stream stream;

        /// <summary>
        /// Initializes a new instance of the <see cref="ReadableWritableDataStorageOnStream"/> class.
        /// </summary>
        /// <param name="stream">The stream to wrap.</param>
        /// <param name="ownsStream">if set to <c>true</c> ownership of the stream is transfered to the new instance of this class.</param>
        public ReadableWritableDataStorageOnStream(Stream stream, bool ownsStream) 
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            InternalDebug.Assert(this.RefCount == 1);
            InternalDebug.Assert(stream.CanSeek && stream.CanRead && stream.CanWrite);

            this.stream = stream;
            this.ownsStream = ownsStream;
        }

        /// <summary>
        /// Gets the length of the storage buffer.
        /// </summary>
        /// <value>The length.</value>
        public override long Length
        {
            get
            {
                return this.stream.Length;
            }
        }

        /// <summary>
        /// Reads from the storage at the specified position.
        /// </summary>
        /// <param name="position">The position to start reading at.</param>
        /// <param name="buffer">The buffer to read into.</param>
        /// <param name="offset">The offset to read into.</param>
        /// <param name="count">The number of bytes to read .</param>
        /// <returns>The actual number of bytes read.</returns>
        public override int Read(long position, byte[] buffer, int offset, int count)
        {
            InternalDebug.Assert(this.RefCount > 0);

            if (this.IsReadOnly)
            {
                lock (this.ReadOnlyLock)
                {
                    return this.InternalRead(position, buffer, offset, count);
                }
            }

            return this.InternalRead(position, buffer, offset, count);
        }

        /// <summary>
        /// Writes the specified buffer into the stream.
        /// </summary>
        /// <param name="position">The position in the stream to write at.</param>
        /// <param name="buffer">The buffer to write.</param>
        /// <param name="offset">The offset within the buffer to write from.</param>
        /// <param name="count">The number of bytes to write.</param>
        public override void Write(long position, byte[] buffer, int offset, int count)
        {
            InternalDebug.Assert(this.RefCount > 0);

            if (this.IsReadOnly)
            {
                throw new InvalidOperationException("Write to read-only DataStorage");
            }

            this.stream.Position = position;
            this.stream.Write(buffer, offset, count);
        }

        /// <summary>
        /// Sets the length of the stream.
        /// </summary>
        /// <param name="length">The length of the stream.</param>
        public override void SetLength(long length)
        {
            InternalDebug.Assert(this.RefCount > 0);

            if (this.IsReadOnly)
            {
                throw new InvalidOperationException("Write to read-only DataStorage");
            }

            this.stream.SetLength(length);
        }

        /// <summary>
        /// Destroys this instance.
        /// </summary>
        protected override void Destroy()
        {
            InternalDebug.Assert(this.RefCount == 0);

            if (this.ownsStream)
            {
                this.stream.Close();
            }

            this.stream = null;

            base.Destroy();
        }

        /// <summary>
        /// Reads from the internal stream.
        /// </summary>
        /// <param name="position">The position to read from.</param>
        /// <param name="buffer">The buffer to read into.</param>
        /// <param name="offset">The offset in the buffer to read into.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <returns>The actual number of bytes read.</returns>
        private int InternalRead(long position, byte[] buffer, int offset, int count)
        {
            this.stream.Position = position;
            return this.stream.Read(buffer, offset, count);
        }
    }
}