//-----------------------------------------------------------------------
// 
//     Copyright (c) Microsoft Corporation.
// 
//-----------------------------------------------------------------------
namespace Microsoft.Isam.Esent.Interop
{
    using System;
    /// 
    /// A cache for boxed values.
    /// 
    /// The type of object to cache.
    internal static class BoxedValueCache where T : struct, IEquatable
    {
        /// 
        /// Number of boxed values to cache.
        /// 
        private const int NumCachedBoxedValues = 257;
        /// 
        /// Cached boxed values.
        /// 
        private static readonly object[] BoxedValues = new object[NumCachedBoxedValues];
        /// 
        /// Gets a boxed version of the value. A cached copy is used if possible.
        /// 
        /// The value to box.
        /// A boxed version of the value.
        public static object GetBoxedValue(T? value)
        {
            if (!value.HasValue)
            {
                return null;
            }
            T valueToBox = value.Value;
            int index = (valueToBox.GetHashCode() & 0x7fffffff) % NumCachedBoxedValues;
            object boxedValue = BoxedValues[index];
            if (null == boxedValue || !((T)boxedValue).Equals(valueToBox))
            {
                boxedValue = valueToBox;
                BoxedValues[index] = boxedValue;
            }
            return boxedValue;
        }
    }
}