﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataStorage.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 reference counting base class for data storage.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

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

    using Strings = CtsResources.SharedStrings;

    /// <summary>
    /// A reference counting base class for data storage.
    /// </summary>
    internal abstract class DataStorage : RefCountable
    {
        /// <summary>
        /// Gets or sets a value indicating whether the stream is read only.
        /// </summary>
        protected bool IsReadOnly
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the lock object used when switching isReadOnly.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification="Uses default get/set syntax.")]
        protected object ReadOnlyLock
        {
            get;
            set;
        }

        /// <summary>
        /// Copies content into the storage stream.
        /// </summary>
        /// <param name="srcStream">The source stream to copy from.</param>
        /// <param name="destStream">The destination stream.</param>
        /// <param name="lengthToCopy">The maximum number of bytes to copy.</param>
        /// <param name="scratchBuffer">The scratch buffer to use.</param>
        /// <returns>The number of bytes copied.</returns>
        public static long CopyStreamToStream(
                            Stream srcStream,
                            Stream destStream,
                            long lengthToCopy,
                            ref byte[] scratchBuffer)
        {
            if (scratchBuffer == null || scratchBuffer.Length < 4096)
            {
                scratchBuffer = new byte[4096];
            }

            long written = 0;

            while (lengthToCopy != 0)
            {
                int toRead = (int)Math.Min(lengthToCopy, (long)scratchBuffer.Length);

                int read = srcStream.Read(scratchBuffer, 0, toRead);
                if (0 == read)
                {
                    InternalDebug.Assert(lengthToCopy == long.MaxValue);
                    break;
                }

                if (destStream != null)
                {
                    destStream.Write(scratchBuffer, 0, read);
                }

                written += read;

                if (lengthToCopy != long.MaxValue)
                {
                    lengthToCopy -= read;
                }
            }

            return written;
        }

// Orphaned WPL code.
#if false
        /// <summary>
        /// Creates a new empty stream for reading.
        /// </summary>
        /// <returns>A new empty stream for reading.</returns>
        public static Stream NewEmptyReadStream()
        {
            return new StreamOnReadableDataStorage(null, 0, 0);
        }
#endif

        /// <summary>
        /// Opens the read stream.
        /// </summary>
        /// <param name="start">The start position of the read stream.</param>
        /// <param name="end">The end position of the read stream.</param>
        /// <returns>The stream as a read-only stream</returns>
        public abstract Stream OpenReadStream(long start, long end);

        /// <summary>
        /// Copies content into the storage stream.
        /// </summary>
        /// <param name="start">The start position to copy from.</param>
        /// <param name="end">The end position to copy to.</param>
        /// <param name="destStream">The destination stream.</param>
        /// <param name="scratchBuffer">The scratch buffer to use.</param>
        /// <returns>The number of bytes copied.</returns>
        public virtual long CopyContentToStream(
                            long start,
                            long end,
                            Stream destStream,
                            ref byte[] scratchBuffer)
        {
            InternalDebug.Assert(0 <= start && start <= end);

            if (destStream == null && end != long.MaxValue)
            {
                return end - start;
            }

            using (Stream srcStream = this.OpenReadStream(start, end))
            {
                return CopyStreamToStream(srcStream, destStream, long.MaxValue, ref scratchBuffer);
            }
        }

        /// <summary>
        /// Sets the stream readonly flag.
        /// </summary>
        /// <param name="makeReadOnly">If true the stream is marked as read only.</param>
        internal virtual void SetReadOnly(bool makeReadOnly)
        {
            if (makeReadOnly == this.IsReadOnly)
            {
                return;
            }

            this.ReadOnlyLock = makeReadOnly ? new object() : null;

            this.IsReadOnly = makeReadOnly;
        }
    }
}