lucenenet-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mhern...@apache.org
Subject [2/3] git commit: porting initial code for RamUsageEstimater, SystemProps, Constants and HashMap. Changing the portable library version to use .net 4.5.1 in order to use the pcl version of Microsoft.Framework.Configuration.
Date Thu, 24 Jul 2014 03:15:38 GMT
porting initial code for RamUsageEstimater, SystemProps, Constants and HashMap. Changing the portable library version to use .net 4.5.1 in order to use the pcl version of Microsoft.Framework.Configuration.


Project: http://git-wip-us.apache.org/repos/asf/lucenenet/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucenenet/commit/612b6d00
Tree: http://git-wip-us.apache.org/repos/asf/lucenenet/tree/612b6d00
Diff: http://git-wip-us.apache.org/repos/asf/lucenenet/diff/612b6d00

Branch: refs/heads/pcl
Commit: 612b6d00a9fb68f852e83b2ec230026633442655
Parents: d72389b
Author: Michael Herndon <mherndon@michaelherndon.com>
Authored: Wed Jul 23 02:46:57 2014 -0400
Committer: Michael Herndon <mherndon@michaelherndon.com>
Committed: Wed Jul 23 02:46:57 2014 -0400

----------------------------------------------------------------------
 src/Lucene.Net.Core/Support/HashMap.cs        | 589 +++++++++++++++++++++
 src/Lucene.Net.Core/Util/Constants.cs         | 133 +++++
 src/Lucene.Net.Core/Util/RamUsageEstimator.cs | 537 +++++++++++++++++++
 src/Lucene.Net.Core/Util/SystemProp.cs        |  76 +++
 src/Lucene.Net.Core/packages.config           |   4 +
 5 files changed, 1339 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/lucenenet/blob/612b6d00/src/Lucene.Net.Core/Support/HashMap.cs
----------------------------------------------------------------------
diff --git a/src/Lucene.Net.Core/Support/HashMap.cs b/src/Lucene.Net.Core/Support/HashMap.cs
new file mode 100644
index 0000000..492de3e
--- /dev/null
+++ b/src/Lucene.Net.Core/Support/HashMap.cs
@@ -0,0 +1,589 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ *
+*/
+
+
+
+namespace Lucene.Net.Support
+{
+    using System;
+    using System.Collections;
+    using System.Collections.Generic;
+    using System.Diagnostics.CodeAnalysis;
+    using System.Reflection;
+
+    /// <summary>
+    /// A C# emulation of the <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html">Java Hashmap</a>
+    /// <para>
+    /// A <see cref="Dictionary{TKey, TValue}" /> is a close equivalent to the Java
+    /// Hashmap.  One difference java implementation of the class is that
+    /// the Hashmap supports both null keys and values, where the C# Dictionary
+    /// only supports null values not keys.  Also, <c>V Get(TKey)</c>
+    /// method in Java returns null if the key doesn't exist, instead of throwing
+    /// an exception.  This implementation doesn't throw an exception when a key 
+    /// doesn't exist, it will return null.  This class is slower than using a 
+    /// <see cref="Dictionary{TKey, TValue}"/>, because of extra checks that have to be
+    /// done on each access, to check for null.
+    /// </para>
+    /// <para>
+    /// <b>NOTE:</b> This class works best with nullable types.  default(T) is returned
+    /// when a key doesn't exist in the collection (this being similar to how Java returns
+    /// null).  Therefore, if the expected behavior of the java code is to execute code
+    /// based on if the key exists, when the key is an integer type, it will return 0 instead of null.
+    /// </para>
+    /// <remaks>
+    /// Consider also implementing IDictionary, IEnumerable, and ICollection
+    /// like <see cref="Dictionary{TKey, TValue}" /> does, so HashMap can be
+    /// used in substituted in place for the same interfaces it implements.
+    /// </remaks>
+    /// </summary>
+    /// <typeparam name="TKey">The type of keys in the dictionary</typeparam>
+    /// <typeparam name="TValue">The type of values in the dictionary</typeparam>
+    [Serializable]
+    public class HashMap<TKey, TValue> : IDictionary<TKey, TValue>
+    {
+        internal IEqualityComparer<TKey> _comparer;
+        internal IDictionary<TKey, TValue> _dict;
+
+        // Indicates if a null key has been assigned, used for iteration
+        private bool _hasNullValue;
+        // stores the value for the null key
+        private TValue _nullValue;
+        // Indicates the type of key is a non-nullable valuetype
+        private bool _isValueType;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="HashMap{TKey, TValue}"/> class.
+        /// </summary>
+        public HashMap()
+            : this(0)
+        { }
+
+        public HashMap(IEqualityComparer<TKey> comparer)
+            : this(0, comparer)
+        {
+
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="HashMap{TKey, TValue}"/> class with an initial capacity
+        /// </summary>
+        /// <param name="initialCapacity">The number of elements that the new <see cref="HashMap{TKey, TValue}"/> can store.</param>
+        public HashMap(int initialCapacity)
+            : this(initialCapacity, EqualityComparer<TKey>.Default)
+        {
+
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="HashMap{TKey, TValue}"/> class with an initial capacity and an alternative
+        /// comparer.
+        /// </summary>
+        /// <param name="initialCapacity">The number of elements that the new <see cref="HashMap{TKey, TValue}"/> can store.</param>
+        /// <param name="comparer">The </param>
+        public HashMap(int initialCapacity, IEqualityComparer<TKey> comparer)
+            : this(new Dictionary<TKey, TValue>(initialCapacity, comparer), comparer)
+        {
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="HashMap{TKey, TValue}"/> class that contains elements copied from a collection.
+        /// </summary>
+        /// <param name="collection">The collection of elements that will be copied into the instance.</param>
+        [SuppressMessage("Microsoft.Usage","CA2214", Justification = "By Design")]
+        public HashMap(IEnumerable<KeyValuePair<TKey, TValue>> collection)
+            : this(0)
+        {
+            foreach (var kvp in collection)
+            {
+                Add(kvp.Key, kvp.Value);
+            }
+        }
+
+        internal HashMap(IDictionary<TKey, TValue> wrappedDict, IEqualityComparer<TKey> comparer)
+        {
+            _comparer = EqualityComparer<TKey>.Default;
+            _dict = wrappedDict;
+            _hasNullValue = false;
+
+
+            if (typeof(TKey).GetTypeInfo().IsValueType)
+            {
+                _isValueType = Nullable.GetUnderlyingType(typeof(TKey)) == null;
+            }
+        }
+
+        /// <summary>
+        ///  Determines whether the <see cref="HashMap{TKey, TValue}"/> contains an element
+        ///  with the specified value.
+        /// </summary>
+        /// <param name="value">The object that the <see cref="HashMap{TKey, TValue}"/> may contain.</param>
+        /// <returns>True, if the <see cref="HashMap{TKey, TValue}"/> contains the value; otherwise, false.</returns>
+        public bool ContainsValue(TValue value)
+        {
+            if (!_isValueType && _hasNullValue && _nullValue.Equals(value))
+                return true;
+
+            return _dict.Values.Contains(value);
+        }
+
+        /*
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="key"></param>
+        /// <param name="value"></param>
+        /// <returns></returns>
+        public TValue AddIfAbsent(TKey key, TValue value)
+        {
+            if (!ContainsKey(key))
+            {
+                Add(key, value);
+                return default(TValue);
+            }
+            return this[key];
+        } */
+
+        #region Implementation of IEnumerable
+
+        /// <summary>
+        ///   Returns an enumerator that iterates through the collection.
+        /// </summary>
+        /// <returns>
+        /// A <see cref="System.Collections.Generic.IEnumerator{T}"/> that can be used to iterate through
+        //./    the collection.
+        /// </returns>
+        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
+        {
+            if (!_isValueType && _hasNullValue)
+            {
+                yield return new KeyValuePair<TKey, TValue>(default(TKey), _nullValue);
+            }
+            foreach (var kvp in _dict)
+            {
+                yield return kvp;
+            }
+        }
+
+        IEnumerator IEnumerable.GetEnumerator()
+        {
+            return GetEnumerator();
+        }
+
+        #endregion
+
+        #region Implementation of ICollection<KeyValuePair<TKey,TValue>>
+
+        void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
+        {
+            Add(item.Key, item.Value);
+        }
+
+        /// <summary>
+        /// Removes all items from the <see cref="HashMap{TKey, TValue}"/>.
+        /// </summary>
+        public void Clear()
+        {
+            _hasNullValue = false;
+            _nullValue = default(TValue);
+            _dict.Clear();
+        }
+
+
+        /// <summary>
+        ///  Determines whether the <see cref="HashMap{TKey, TValue}"/> contains a specific
+        ///     value.
+        /// </summary>
+        /// <param name="item">The object to locate in the <see cref="HashMap{TKey, TValue}"/></param>
+        /// <returns>  True, if item is found in the <see cref="HashMap{TKey, TValue}"/> otherwise,
+        ///     false.</returns>
+        public bool Contains(KeyValuePair<TKey, TValue> item)
+        {
+            if (!_isValueType && _comparer.Equals(item.Key, default(TKey)))
+            {
+                return _hasNullValue && EqualityComparer<TValue>.Default.Equals(item.Value, _nullValue);
+            }
+
+            return ((ICollection<KeyValuePair<TKey, TValue>>)_dict).Contains(item);
+        }
+
+        /// <summary>
+        /// Copies the elements of the <see cref="HashMap{TKey, TValue}"/> to an <see cref="System.Array"/>,
+        /// starting at a particular <see cref="System.Array"/>y index.
+        /// </summary>
+        /// <param name="array">
+        ///  The one-dimensional <see cref="System.Array"/> that is the destination of the elements copied
+        ///  from <see cref="HashMap{TKey, TValue}"> . The <see cref="System.Array"/> must have zero-based
+        ///     indexing.
+        /// </param>
+        /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
+        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
+        {
+            Check.NotNull("array", array);
+
+            if (arrayIndex < 0)
+                throw new ArgumentOutOfRangeException("arrayIndex is must be 0 or greater.");
+
+            ((ICollection<KeyValuePair<TKey, TValue>>)_dict).CopyTo(array, arrayIndex);
+            if (!_isValueType && _hasNullValue)
+            {
+                array[array.Length - 1] = new KeyValuePair<TKey, TValue>(default(TKey), _nullValue);
+            }
+
+
+        }
+
+        /// <summary>
+        /// Removes the first occurrence of a specific object from the <see cref="HashMap{TKey, TValue}"/>
+        /// </summary>
+        /// <param name="item">The object to remove from the <see cref="HashMap{TKey, TValue}"/></param>
+        /// <returns>
+        /// True if item was successfully removed from the <see cref="HashMap{TKey, TValue}"/>
+        /// otherwise, false.
+        /// </returns>
+        public bool Remove(KeyValuePair<TKey, TValue> item)
+        {
+            if (!_isValueType && _comparer.Equals(item.Key, default(TKey)))
+            {
+                if (!_hasNullValue)
+                    return false;
+
+                _hasNullValue = false;
+                _nullValue = default(TValue);
+                return true;
+            }
+
+            return ((ICollection<KeyValuePair<TKey, TValue>>)_dict).Remove(item);
+        }
+
+        /// <summary>
+        ///  Gets the number of elements contained in the <see cref="HashMap{TKey, TValue}"/>
+        /// </summary>
+        public int Count
+        {
+            get { return _dict.Count + (_hasNullValue ? 1 : 0); }
+        }
+
+        /// <summary>
+        /// Gets a value indicating whether the <see cref="HashMap{TKey, TValue}"/>
+        /// is read-only.
+        /// </summary>
+        public bool IsReadOnly
+        {
+            get { return false; }
+        }
+
+        #endregion
+
+        #region Implementation of IDictionary<TKey,TValue>
+
+        /// <summary>
+        /// Determines whether the <see cref="HashMap{TKey, TValue}"/> contains an element
+        ///  with the specified key.
+        /// </summary>
+        /// <param name="key">
+        ///  An identifier that is used to retrieve the value.  
+        /// </param>
+        /// <returns>
+        /// True, if the <see cref="HashMap{TKey, TValue}"/> contains an element with
+        /// the key; otherwise, false.
+        /// </returns>
+        public bool ContainsKey(TKey key)
+        {
+            if (!_isValueType && _comparer.Equals(key, default(TKey)))
+            {
+                if (_hasNullValue)
+                {
+                    return true;
+                }
+                return false;
+            }
+
+            return _dict.ContainsKey(key);
+        }
+
+        /// <summary>
+        /// Adds an element with the provided key and value to the <see cref="HashMap{TKey, TValue}"/>
+        /// </summary>
+        /// <param name="key">An identifier that is used to lookup the value.</param>
+        /// <param name="value">The object associated with the key.</param>
+        public virtual void Add(TKey key, TValue value)
+        {
+            if (!_isValueType && _comparer.Equals(key, default(TKey)))
+            {
+                _hasNullValue = true;
+                _nullValue = value;
+            }
+            else
+            {
+                _dict[key] = value;
+            }
+        }
+
+        /// <summary>
+        /// Removes the element with the specified key from the <see cref="HashMap{TKey, TValue}"/>
+        /// </summary>
+        /// <param name="key">An identifier that is used to specify which <see cref="KeyValuePair{TKey, TValue}"/> should be removed.</param>
+        /// <returns>True, if the element is successfully removed; otherwise, false. </returns>
+        public bool Remove(TKey key)
+        {
+            
+           
+            if (!_isValueType && _comparer.Equals(key, default(TKey)))
+            {
+                _hasNullValue = false;
+                _nullValue = default(TValue);
+                return true;
+            }
+            else
+            {
+                return _dict.Remove(key);
+            }
+        }
+
+        /// <summary>
+        /// Gets the value associated with the specified key.
+        /// </summary>
+        /// <param name="key">An identifier that is used to retrieve the value.</param>
+        /// <param name="value">When this method returns, the value associated with the specified key, if the
+        ///     key is found; otherwise, the default value for the type of the value parameter.
+        ///     This parameter is passed uninitialized.
+        ///  </param>
+        /// <returns>True, if the <see cref="HashMap{TKey, TValue}"/> contains
+        ///     an element with the specified key; otherwise, false.
+        /// </returns>
+        public bool TryGetValue(TKey key, out TValue value)
+        {
+            if (!_isValueType && _comparer.Equals(key, default(TKey)))
+            {
+                if (_hasNullValue)
+                {
+                    value = _nullValue;
+                    return true;
+                }
+
+                value = default(TValue);
+                return false;
+            }
+            else
+            {
+                return _dict.TryGetValue(key, out value);
+            }
+        }
+
+        /// <summary>
+        /// Gets or sets the element with the specified key.
+        /// </summary>
+        /// <param name="key">An identifier that is used to retrieve the value.</param>
+        /// <returns>The element specified by the key.</returns>
+        public TValue this[TKey key]
+        {
+            get
+            {
+                if (!_isValueType && _comparer.Equals(key, default(TKey)))
+                {
+                    if (!_hasNullValue)
+                    {
+                        return default(TValue);
+                    }
+                    return _nullValue;
+                }
+                return _dict.ContainsKey(key) ? _dict[key] : default(TValue);
+            }
+            set { Add(key, value); }
+        }
+
+        public ICollection<TKey> Keys
+        {
+            get
+            {
+                if (!_hasNullValue) return _dict.Keys;
+
+                // Using a List<T> to generate an ICollection<TKey>
+                // would incur a costly copy of the dict's KeyCollection
+                // use out own wrapper instead
+                return new NullKeyCollection(_dict);
+            }
+        }
+
+        public ICollection<TValue> Values
+        {
+            get
+            {
+                if (!_hasNullValue) return _dict.Values;
+
+                // Using a List<T> to generate an ICollection<TValue>
+                // would incur a costly copy of the dict's ValueCollection
+                // use out own wrapper instead
+                return new NullValueCollection(_dict, _nullValue);
+            }
+        }
+
+        #endregion
+
+        #region NullValueCollection
+
+        /// <summary>
+        /// Wraps a dictionary and adds the value
+        /// represented by the null key
+        /// </summary>
+        class NullValueCollection : ICollection<TValue>
+        {
+            private readonly TValue _nullValue;
+            private readonly IDictionary<TKey, TValue> _internalDict;
+
+            public NullValueCollection(IDictionary<TKey, TValue> dict, TValue nullValue)
+            {
+                _internalDict = dict;
+                _nullValue = nullValue;
+            }
+
+            #region Implementation of IEnumerable
+
+            public IEnumerator<TValue> GetEnumerator()
+            {
+                yield return _nullValue;
+
+                foreach (var val in _internalDict.Values)
+                {
+                    yield return val;
+                }
+            }
+
+            IEnumerator IEnumerable.GetEnumerator()
+            {
+                return GetEnumerator();
+            }
+
+            #endregion
+
+            #region Implementation of ICollection<TValue>
+
+            public void CopyTo(TValue[] array, int arrayIndex)
+            {
+                throw new NotImplementedException("Implement as needed");
+            }
+
+            public int Count
+            {
+                get { return _internalDict.Count + 1; }
+            }
+
+            public bool IsReadOnly
+            {
+                get { return true; }
+            }
+
+            #region Explicit Interface Methods
+
+            void ICollection<TValue>.Add(TValue item)
+            {
+                throw new NotSupportedException();
+            }
+
+            void ICollection<TValue>.Clear()
+            {
+                throw new NotSupportedException();
+            }
+
+            bool ICollection<TValue>.Contains(TValue item)
+            {
+                throw new NotSupportedException();
+            }
+
+            bool ICollection<TValue>.Remove(TValue item)
+            {
+                throw new NotSupportedException("Collection is read only!");
+            }
+            #endregion
+
+            #endregion
+        }
+
+        #endregion
+
+        #region NullKeyCollection
+        /// <summary>
+        /// Wraps a dictionary's collection, adding in a
+        /// null key.
+        /// </summary>
+        class NullKeyCollection : ICollection<TKey>
+        {
+            private readonly IDictionary<TKey, TValue> _internalDict;
+
+            public NullKeyCollection(IDictionary<TKey, TValue> dict)
+            {
+                _internalDict = dict;
+            }
+
+            public IEnumerator<TKey> GetEnumerator()
+            {
+                yield return default(TKey);
+                foreach (var key in _internalDict.Keys)
+                {
+                    yield return key;
+                }
+            }
+
+            IEnumerator IEnumerable.GetEnumerator()
+            {
+                return GetEnumerator();
+            }
+
+            public void CopyTo(TKey[] array, int arrayIndex)
+            {
+                throw new NotImplementedException("Implement this as needed");
+            }
+
+            public int Count
+            {
+                get { return _internalDict.Count + 1; }
+            }
+
+            public bool IsReadOnly
+            {
+                get { return true; }
+            }
+
+            #region Explicit Interface Definitions
+            bool ICollection<TKey>.Contains(TKey item)
+            {
+                throw new NotSupportedException();
+            }
+
+            void ICollection<TKey>.Add(TKey item)
+            {
+                throw new NotSupportedException();
+            }
+
+            void ICollection<TKey>.Clear()
+            {
+                throw new NotSupportedException();
+            }
+
+            bool ICollection<TKey>.Remove(TKey item)
+            {
+                throw new NotSupportedException();
+            }
+            #endregion
+        }
+        #endregion
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/lucenenet/blob/612b6d00/src/Lucene.Net.Core/Util/Constants.cs
----------------------------------------------------------------------
diff --git a/src/Lucene.Net.Core/Util/Constants.cs b/src/Lucene.Net.Core/Util/Constants.cs
new file mode 100644
index 0000000..f8c48d9
--- /dev/null
+++ b/src/Lucene.Net.Core/Util/Constants.cs
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+namespace Lucene.Net.Util
+{
+    using System;
+    using System.Reflection;
+
+    /// <summary>
+    /// Global constants that Lucene.Net uses to make decisions based upon the environment
+    /// that Lucene.Net is executing on.
+    /// </summary>
+    public class Constants
+    {
+        static Constants()
+        {
+            string version = null;
+            try
+            {
+                version = typeof(Constants).GetTypeInfo().Assembly.GetName().Version.ToString();
+            }
+            catch (System.Security.SecurityException) //Ignore in medium trust.
+            {
+            }
+
+            if(version == null)
+            {
+                version = EnsureMainVersionWithoutAlphaBeta() + "-SNAPSHOT";
+            }
+
+            LUCENE_VERSION = version;
+        }
+
+        // TODO 5.9 see if the constants for JVM & JAVA are actually needed.
+        // public static readonly String JVM_VENDOR = AppSettings.Get("java.vm.vendor", "");
+        // public static readonly String JVM_VERSION = AppSettings.Get("java.vm.version", "");
+        // public static readonly String JVM_NAME = AppSettings.Get("java.vm.name", "");
+        // public static readonly System.String JAVA_VERSION = AppSettings.Get("java.version", "");
+
+        /// <summary>
+        /// Determines if the KRE is 32 or 64 bit. 
+        /// </summary>
+        /// <remarks><para>JRE_IS_64BIT</para></remarks>
+        public static readonly bool KRE_IS_64BIT = IntPtr.Size == 8;
+
+        /// <summary>
+        /// Returns the runtime version.
+        /// </summary>
+        public static readonly string KRE_VERSION = SystemProps.Get("Version");
+
+        /// <summary>
+        /// Gets the name of the operating system.
+        /// </summary>
+        public static readonly string OS_NAME = SystemProps.Get("OS");
+
+        /// <summary>Returns true, if running on Linux. </summary>
+        public static readonly bool LINUX = OS_NAME.StartsWith("Linux");
+        /// <summary>Returns true, if running on Windows. </summary>
+        public static readonly bool WINDOWS = OS_NAME.StartsWith("Windows");
+        /// <summary>Returns true, if running on SunOS. </summary>
+        public static readonly bool SUN_OS = OS_NAME.StartsWith("SunOS");
+        /// <summary>Returns true, if running on Mac OS X. </summary>
+        public static readonly bool MAC_OS_X = OS_NAME.StartsWith("Mac OS X");
+
+        /// <summary>
+        /// Gets the proccess architechture for the current machine.
+        /// </summary>
+        public static string OS_ARCH = SystemProps.Get("PROCESSOR_ARCHITECTURE");
+
+
+        /// <summary>
+        /// Gets the version of the operating system for the current machine.
+        /// </summary>
+        public static string OS_VERSION = SystemProps.Get("OS_VERSION", "?");
+
+
+        /// <summary>
+        /// This is the internal Lucene version, recorded into each segment.
+        /// </summary>
+        /// <remarks>
+        ///     <para>
+        ///         NOTE: we track per-segment version as a String with the {@code "X.Y"} format
+        ///         (no minor version), e.g. {@code "4.0", "3.1", "3.0"}.
+        ///  </para>
+        ///     <para>
+        ///         Alpha and Beta versions will have numbers like { @code "X.Y.0.Z"},
+        ///         anything else is not allowed.This is done to prevent people from
+        ///         using indexes created with ALPHA/BETA versions with the released version.
+        ///     </para>
+        /// </remarks>
+        public static readonly System.String LUCENE_MAIN_VERSION = Ident("5.0");
+
+        /// <summary>
+        /// This is the Lucene version for display purposes.
+        /// </summary>
+        public static System.String LUCENE_VERSION;
+
+        // this method prevents inlining the final version constant in compiled
+        // classes,
+        // see: http://www.javaworld.com/community/node/3400
+        private static System.String Ident(System.String s)
+        {
+            return s.ToString();
+        }
+
+
+        private static string EnsureMainVersionWithoutAlphaBeta()
+        {
+            var parts = LUCENE_MAIN_VERSION.Split('.');
+            if (parts.Length == 4 && "0".Equals(parts[2]))
+            {
+                return parts[0] + "." + parts[1];
+            }
+
+            return LUCENE_MAIN_VERSION;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/lucenenet/blob/612b6d00/src/Lucene.Net.Core/Util/RamUsageEstimator.cs
----------------------------------------------------------------------
diff --git a/src/Lucene.Net.Core/Util/RamUsageEstimator.cs b/src/Lucene.Net.Core/Util/RamUsageEstimator.cs
new file mode 100644
index 0000000..bf3bf0b
--- /dev/null
+++ b/src/Lucene.Net.Core/Util/RamUsageEstimator.cs
@@ -0,0 +1,537 @@
+/* 
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+
+
+namespace Lucene.Net.Util
+{
+    using Lucene.Net.Support;
+    using System;
+    using System.Collections.Generic;
+    using System.Globalization;
+    using System.Reflection;
+    using System.Linq;
+
+
+    /// <summary> Estimates the size of a given Object using a given MemoryModel for primitive
+    /// size information.
+    /// 
+    /// Resource Usage: 
+    /// 
+    /// Internally uses a Map to temporally hold a reference to every
+    /// object seen. 
+    /// 
+    /// If checkIntered, all Strings checked will be interned, but those
+    /// that were not already interned will be released for GC when the
+    /// estimate is complete.
+    /// </summary>
+    public sealed class RamUsageEstimator
+    {
+        public static readonly string JVM_INFO_STRING;
+
+        public const long ONE_KB = 1024L;
+
+        public const long ONE_MB = ONE_KB * ONE_KB;
+
+        public const long ONE_GB = ONE_KB * ONE_MB;
+
+        /// <summary>
+        /// No instantiation
+        /// </summary>
+        private RamUsageEstimator()
+        {
+        }
+
+        public const int NUM_BYTES_BOOLEAN = 1;
+        public const int NUM_BYTES_BYTE = 1;
+        public const int NUM_BYTES_CHAR = 2;
+        public const int NUM_BYTES_SHORT = 2;
+        public const int NUM_BYTES_INT = 4;
+        public const int NUM_BYTES_FLOAT = 4;
+        public const int NUM_BYTES_LONG = 8;
+        public const int NUM_BYTES_DOUBLE = 8;
+
+        public static readonly int NUM_BYTES_OBJECT_REF;
+
+        public static readonly int NUM_BYTES_OBJECT_HEADER;
+
+        public static readonly int NUM_BYTES_ARRAY_HEADER;
+
+        public static readonly int NUM_BYTES_OBJECT_ALIGNMENT;
+
+        private static readonly IDictionary<Type, int> primitiveSizes;
+
+        static RamUsageEstimator()
+        {
+
+
+            var x = new HashMap<Type, int>();
+           
+            primitiveSizes = new HashMap<Type, int>();
+            primitiveSizes[typeof(bool)] = NUM_BYTES_BOOLEAN;
+            primitiveSizes[typeof(byte)] = NUM_BYTES_BYTE;
+            primitiveSizes[typeof(sbyte)] = NUM_BYTES_BYTE;
+            primitiveSizes[typeof(char)] = NUM_BYTES_CHAR;
+            primitiveSizes[typeof(short)] = NUM_BYTES_SHORT;
+            primitiveSizes[typeof(int)] = NUM_BYTES_INT;
+            primitiveSizes[typeof(float)] = NUM_BYTES_FLOAT;
+            primitiveSizes[typeof(double)] = NUM_BYTES_DOUBLE;
+            primitiveSizes[typeof(long)] = NUM_BYTES_LONG;
+
+            // These were copied from the Java version of lucene and may not be correct.
+            // The referenceSize and objectHeader seem to be correct according to 
+            // https://www.simple-talk.com/dotnet/.net-framework/object-overhead-the-hidden-.net-memory--allocation-cost/
+            int referenceSize = Constants.KRE_IS_64BIT ? 8 : 4;
+            int objectHeader = Constants.KRE_IS_64BIT ? 16 : 8;
+            int arrayHeader = Constants.KRE_IS_64BIT ? 24 : 12;
+            int objectAlignment = Constants.KRE_IS_64BIT ? 8 : 4;
+
+            NUM_BYTES_OBJECT_REF = referenceSize;
+            NUM_BYTES_OBJECT_HEADER = objectHeader;
+            NUM_BYTES_ARRAY_HEADER = arrayHeader;
+            NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment;
+
+
+            /*
+            JVM_INFO_STRING = "[JVM: " +
+                Constants.JVM_NAME + ", " + Constants.JVM_VERSION + ", " + Constants.JVM_VENDOR + ", " +
+                Constants.JAVA_VENDOR + ", " + Constants.JAVA_VERSION + "]"; */
+        }
+
+        private sealed class ClassCache
+        {
+            public readonly long alignedShallowInstanceSize;
+            public readonly FieldInfo[] referenceFields;
+
+            public ClassCache(long alignedShallowInstanceSize, FieldInfo[] referenceFields)
+            {
+                this.alignedShallowInstanceSize = alignedShallowInstanceSize;
+                this.referenceFields = referenceFields;
+            }
+        }
+
+        public static long AlignObjectSize(long size)
+        {
+            size += (long)NUM_BYTES_OBJECT_ALIGNMENT - 1L;
+            return size - (size % NUM_BYTES_OBJECT_ALIGNMENT);
+        }
+
+
+        public static long SizeOf<T>(T[] array) where T : struct
+        {
+            int? size = primitiveSizes[typeof(T)];
+
+            if (size.HasValue)
+                return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)size * array.Length);
+
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + array.Length);
+        }
+
+        /*
+        public static long SizeOf(byte[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + arr.Length);
+        }
+
+        public static long SizeOf(sbyte[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + arr.Length);
+        }
+
+        public static long SizeOf(bool[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + arr.Length);
+        }
+
+        public static long SizeOf(char[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)NUM_BYTES_CHAR * arr.Length);
+        }
+
+        public static long SizeOf(short[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)NUM_BYTES_SHORT * arr.Length);
+        }
+
+        public static long SizeOf(int[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)NUM_BYTES_INT * arr.Length);
+        }
+
+        public static long SizeOf(float[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)NUM_BYTES_FLOAT * arr.Length);
+        }
+
+        public static long SizeOf(long[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)NUM_BYTES_LONG * arr.Length);
+        }
+
+        public static long SizeOf(double[] arr)
+        {
+            return AlignObjectSize((long)NUM_BYTES_ARRAY_HEADER + (long)NUM_BYTES_DOUBLE * arr.Length);
+        }*/
+
+        public static long SizeOf(Object obj)
+        {
+            return MeasureObjectSize(obj);
+        }
+
+        public static long ShallowSizeOf(Object obj)
+        {
+            if (obj == null) return 0;
+            Type clz = obj.GetType();
+            if (clz.IsArray)
+            {
+                return ShallowSizeOfArray((Array)obj);
+            }
+            else
+            {
+                return ShallowSizeOfInstance(clz);
+            }
+        }
+
+        public static long ShallowSizeOfInstance(Type clazz)
+        {
+            // typeInfo = clazz.
+            var type = clazz;
+            var typeInfo = clazz.GetTypeInfo();
+            if (typeInfo.IsArray)
+                throw new ArgumentException("This method does not work with array classes.");
+            if (typeInfo.IsPrimitive)
+                return primitiveSizes[typeInfo.AsType()];
+
+            long size = NUM_BYTES_OBJECT_HEADER;
+
+            // Walk type hierarchy
+            for (; type != null; type = type.GetTypeInfo().BaseType)
+            {
+                var fields = type.GetRuntimeFields().Where(o => o.IsPublic && !o.IsStatic);
+                foreach (FieldInfo f in fields)
+                {
+                    if (!f.IsStatic)
+                    {
+                        size = AdjustForField(size, f);
+                    }
+                }
+            }
+
+            return AlignObjectSize(size);
+        }
+
+        private static long ShallowSizeOfArray(Array array)
+        {
+            long size = NUM_BYTES_ARRAY_HEADER;
+            int len = array.Length;
+            if (len > 0)
+            {
+                Type arrayElementType = array.GetType().GetElementType();
+                var arrayElementTypeInfo = arrayElementType.GetTypeInfo();
+               
+                if (arrayElementTypeInfo.IsPrimitive)
+                {
+                    size += (long)len * primitiveSizes[arrayElementType];
+                }
+                else
+                {
+                    size += (long)NUM_BYTES_OBJECT_REF * len;
+                }
+            }
+            return AlignObjectSize(size);
+        }
+
+        private static long MeasureObjectSize(Object root)
+        {
+            // Objects seen so far.
+            HashSet<Object> seen = new HashSet<Object>();
+            // Class cache with reference Field and precalculated shallow size. 
+            HashMap<Type, ClassCache> classCache = new HashMap<Type, ClassCache>();
+            // Stack of objects pending traversal. Recursion caused stack overflows. 
+            Stack<Object> stack = new Stack<Object>();
+            stack.Push(root);
+
+            long totalSize = 0;
+            while (stack.Count > 0)
+            {
+                Object ob = stack.Pop();
+
+                if (ob == null || seen.Contains(ob))
+                {
+                    continue;
+                }
+                seen.Add(ob);
+
+                Type obClazz = ob.GetType();
+                if (obClazz.IsArray)
+                {
+                    /*
+                     * Consider an array, possibly of primitive types. Push any of its references to
+                     * the processing stack and accumulate this array's shallow size. 
+                     */
+                    long size = NUM_BYTES_ARRAY_HEADER;
+                    Array array = (Array)ob;
+                    int len = array.Length;
+                    if (len > 0)
+                    {
+                        var componentType = obClazz.GetElementType();
+                        var componentTypeInfo = componentType.GetTypeInfo();
+                        if (componentTypeInfo.IsPrimitive)
+                        {
+                            size += (long)len * primitiveSizes[componentType];
+                        }
+                        else
+                        {
+                            size += (long)NUM_BYTES_OBJECT_REF * len;
+
+                            // Push refs for traversal later.
+                            for (int i = len; --i >= 0;)
+                            {
+                                Object o = array.GetValue(i);
+                                if (o != null && !seen.Contains(o))
+                                {
+                                    stack.Push(o);
+                                }
+                            }
+                        }
+                    }
+                    totalSize += AlignObjectSize(size);
+                }
+                else
+                {
+                    /*
+                     * Consider an object. Push any references it has to the processing stack
+                     * and accumulate this object's shallow size. 
+                     */
+                    ClassCache cachedInfo = classCache[obClazz];
+                    if (cachedInfo == null)
+                    {
+                        classCache[obClazz] = cachedInfo = CreateCacheEntry(obClazz);
+                    }
+
+                    foreach (FieldInfo f in cachedInfo.referenceFields)
+                    {
+                        // Fast path to eliminate redundancies.
+                        Object o = f.GetValue(ob);
+                        if (o != null && !seen.Contains(o))
+                        {
+                            stack.Push(o);
+                        }
+                    }
+
+                    totalSize += cachedInfo.alignedShallowInstanceSize;
+
+                }
+            }
+
+            // Help the GC (?).
+            seen.Clear();
+            stack.Clear();
+            classCache.Clear();
+
+            return totalSize;
+        }
+
+        private static ClassCache CreateCacheEntry(Type type)
+        {
+          
+            ClassCache cachedInfo;
+            long shallowInstanceSize = NUM_BYTES_OBJECT_HEADER;
+            List<FieldInfo> referenceFields = new List<FieldInfo>(32);
+            for (var c = type; c != null; c = c.GetTypeInfo().BaseType)
+            {
+                
+                var fields = c.GetRuntimeFields().Where(o => o.IsPublic && !o.IsStatic);
+                foreach (FieldInfo f in fields)
+                {
+                    shallowInstanceSize = AdjustForField(shallowInstanceSize, f);
+
+                    if (!f.FieldType.GetTypeInfo().IsPrimitive)
+                    {
+                        referenceFields.Add(f);
+                    }
+                }
+            }
+
+            cachedInfo = new ClassCache(
+                AlignObjectSize(shallowInstanceSize),
+                referenceFields.ToArray());
+            return cachedInfo;
+        }
+
+        private static long AdjustForField(long sizeSoFar, FieldInfo f)
+        {
+            var typeInfo = f.FieldType.GetTypeInfo();
+            int fsize = typeInfo.IsPrimitive ? primitiveSizes[f.FieldType] : NUM_BYTES_OBJECT_REF;
+
+            // TODO: there was a lot of other stuff here, not sure if needed
+            return sizeSoFar + fsize;
+        }
+
+        public static string HumanReadableUnits(long bytes)
+        {
+            return HumanReadableUnits(bytes, new NumberFormatInfo() { NumberDecimalDigits = 1 });
+        }
+
+        /// <summary> Return good default units based on byte size.</summary>
+        public static string HumanReadableUnits(long bytes, IFormatProvider df)
+        {
+            string newSizeAndUnits;
+
+            if (bytes / ONE_GB > 0)
+            {
+                newSizeAndUnits = System.Convert.ToString(((float)bytes / ONE_GB), df) + " GB";
+            }
+            else if (bytes / ONE_MB > 0)
+            {
+                newSizeAndUnits = System.Convert.ToString((float)bytes / ONE_MB, df) + " MB";
+            }
+            else if (bytes / ONE_KB > 0)
+            {
+                newSizeAndUnits = System.Convert.ToString((float)bytes / ONE_KB, df) + " KB";
+            }
+            else
+            {
+                newSizeAndUnits = System.Convert.ToString(bytes) + " bytes";
+            }
+
+            return newSizeAndUnits;
+        }
+
+        public class JvmFeature
+        {
+            public string Description { get; private set; }
+
+
+        }
+
+        public static IEnumerable<string> UnsupportedFeatures
+        {
+
+            get { return new string[0];  }
+        }
+
+        public static IEnumerable<string> SupportedFeatures
+        {
+            get { return new string[0]; }
+        }
+
+        //public long EstimateRamUsage(System.Object obj)
+        //{
+        //    long size = Size(obj);
+        //    seen.Clear();
+        //    return size;
+        //}
+
+        //private long Size(System.Object obj)
+        //{
+        //    if (obj == null)
+        //    {
+        //        return 0;
+        //    }
+        //    // interned not part of this object
+        //    if (checkInterned && obj is System.String && obj == (System.Object) String.Intern(((System.String) obj)))
+        //    {
+        //        // interned string will be eligible
+        //        // for GC on
+        //        // estimateRamUsage(Object) return
+        //        return 0;
+        //    }
+
+        //    // skip if we have seen before
+        //    if (seen.ContainsKey(obj))
+        //    {
+        //        return 0;
+        //    }
+
+        //    // add to seen
+        //    seen[obj] = null;
+
+        //    System.Type clazz = obj.GetType();
+        //    if (clazz.IsArray)
+        //    {
+        //        return SizeOfArray(obj);
+        //    }
+
+        //    long size = 0;
+
+        //    // walk type hierarchy
+        //    while (clazz != null)
+        //    {
+        //        System.Reflection.FieldInfo[] fields = clazz.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Static);
+        //        for (int i = 0; i < fields.Length; i++)
+        //        {
+        //            if (fields[i].IsStatic)
+        //            {
+        //                continue;
+        //            }
+
+        //            if (fields[i].FieldType.IsPrimitive)
+        //            {
+        //                size += memoryModel.GetPrimitiveSize(fields[i].FieldType);
+        //            }
+        //            else
+        //            {
+        //                size += refSize;
+        //                fields[i].GetType(); 
+        //                try
+        //                {
+        //                    System.Object value_Renamed = fields[i].GetValue(obj);
+        //                    if (value_Renamed != null)
+        //                    {
+        //                        size += Size(value_Renamed);
+        //                    }
+        //                }
+        //                catch (System.UnauthorizedAccessException)
+        //                {
+        //                    // ignore for now?
+        //                }
+        //            }
+        //        }
+        //        clazz = clazz.BaseType;
+        //    }
+        //    size += classSize;
+        //    return size;
+        //}
+
+        //private long SizeOfArray(System.Object obj)
+        //{
+        //    int len = ((System.Array) obj).Length;
+        //    if (len == 0)
+        //    {
+        //        return 0;
+        //    }
+        //    long size = arraySize;
+        //    System.Type arrayElementClazz = obj.GetType().GetElementType();
+        //    if (arrayElementClazz.IsPrimitive)
+        //    {
+        //        size += len * memoryModel.GetPrimitiveSize(arrayElementClazz);
+        //    }
+        //    else
+        //    {
+        //        for (int i = 0; i < len; i++)
+        //        {
+        //            size += refSize + Size(((System.Array) obj).GetValue(i));
+        //        }
+        //    }
+
+        //    return size;
+        //}
+
+
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/lucenenet/blob/612b6d00/src/Lucene.Net.Core/Util/SystemProp.cs
----------------------------------------------------------------------
diff --git a/src/Lucene.Net.Core/Util/SystemProp.cs b/src/Lucene.Net.Core/Util/SystemProp.cs
new file mode 100644
index 0000000..16902f8
--- /dev/null
+++ b/src/Lucene.Net.Core/Util/SystemProp.cs
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+namespace Lucene.Net.Util
+{
+    using Microsoft.Framework.ConfigurationModel;
+    using System;
+
+    /// <summary>
+    /// SystemProps gets configuration properties for Lucene.Net. By default, it loads 
+    /// <see cref="EnvironmentVariablesConfigurationSource"/> for the <see cref="Constants"/> class.
+    /// Other configuration sources may be added at runtime. 
+    /// </summary>
+    public static class SystemProps
+    {
+        private static Configuration s_config = new Configuration();
+
+        static SystemProps()
+        {
+            s_config.Add(new EnvironmentVariablesConfigurationSource());
+        }
+
+#pragma warning disable "CS3001"
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="configurationSource"></param>
+        public static void Add(IConfigurationSource configurationSource)
+#pragma warning restore "CS3001"
+        {
+           
+            s_config.Add(configurationSource);
+        }
+
+        public static string Get(string key)
+        {
+            return s_config.Get(key);
+        }
+
+        public static T Get<T>(string key)
+        {
+            return Get<T>(key, default(T));
+        }
+
+        public static T Get<T>(string key, T defaultValue)
+        {
+            var value = s_config.Get(key);
+            if (value == null)
+                return defaultValue;
+
+            return (T)Convert.ChangeType(value, typeof(T));
+        }
+
+#pragma warning disable "CS3001"
+        // TODO: <Insert justification for suppressing CS3001>
+        public static void UseConfiguration(Configuration configuration)
+#pragma warning restore "CS3001"
+        {
+            s_config = configuration;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/lucenenet/blob/612b6d00/src/Lucene.Net.Core/packages.config
----------------------------------------------------------------------
diff --git a/src/Lucene.Net.Core/packages.config b/src/Lucene.Net.Core/packages.config
new file mode 100644
index 0000000..80dad80
--- /dev/null
+++ b/src/Lucene.Net.Core/packages.config
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Microsoft.Framework.ConfigurationModel" version="1.0.0-alpha3-10137" targetFramework="portable-net451+win81+wpa81" />
+</packages>
\ No newline at end of file


Mime
View raw message