PageRenderTime 19ms CodeModel.GetById 12ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 1ms

/Microsoft.Scripting/Utils/CacheDict.cs

https://bitbucket.org/stefanrusek/xronos
C# | 117 lines | 66 code | 11 blank | 40 comment | 8 complexity | b895f1da32e439c6c6021cc64893b91a MD5 | raw file
  1/* ****************************************************************************
  2 *
  3 * Copyright (c) Microsoft Corporation. 
  4 *
  5 * This source code is subject to terms and conditions of the Microsoft Public License. A 
  6 * copy of the license can be found in the License.html file at the root of this distribution. If 
  7 * you cannot locate the  Microsoft Public License, please send an email to 
  8 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
  9 * by the terms of the Microsoft Public License.
 10 *
 11 * You must not remove this notice, or any other, from this software.
 12 *
 13 *
 14 * ***************************************************************************/
 15
 16#if CODEPLEX_40
 17using System;
 18#else
 19using System; using Microsoft;
 20#endif
 21using System.Collections.Generic;
 22using System.Text;
 23using System.Diagnostics;
 24
 25namespace Microsoft.Scripting.Utils {
 26    /// <summary>
 27    /// Provides a dictionary-like object used for caches which holds onto a maximum
 28    /// number of elements specified at construction time.
 29    /// 
 30    /// This class is not thread safe.
 31    /// </summary>
 32    public class CacheDict<TKey, TValue> {
 33        private readonly Dictionary<TKey, KeyInfo> _dict = new Dictionary<TKey, KeyInfo>();
 34        private readonly LinkedList<TKey> _list = new LinkedList<TKey>();
 35        private readonly int _maxSize;
 36
 37        /// <summary>
 38        /// Creates a dictionary-like object used for caches.
 39        /// </summary>
 40        /// <param name="maxSize">The maximum number of elements to store.</param>
 41        public CacheDict(int maxSize) {
 42            _maxSize = maxSize;
 43        }
 44
 45        /// <summary>
 46        /// Tries to get the value associated with 'key', returning true if it's found and
 47        /// false if it's not present.
 48        /// </summary>
 49        public bool TryGetValue(TKey key, out TValue value) {
 50            KeyInfo storedValue;
 51            if (_dict.TryGetValue(key, out storedValue)) {
 52                LinkedListNode<TKey> node = storedValue.List;
 53                if (node.Previous != null) {
 54                    // move us to the head of the list...
 55                    _list.Remove(node);
 56                    _list.AddFirst(node);
 57                }
 58
 59                value = storedValue.Value;
 60                return true;
 61            }
 62
 63            value = default(TValue);
 64            return false;
 65        }
 66
 67        /// <summary>
 68        /// Adds a new element to the cache, replacing and moving it to the front if the
 69        /// element is already present.
 70        /// </summary>
 71        public void Add(TKey key, TValue value) {
 72            KeyInfo keyInfo;
 73            if (_dict.TryGetValue(key, out keyInfo)) {
 74                // remove original entry from the linked list
 75                _list.Remove(keyInfo.List);
 76            } else if (_list.Count == _maxSize) {
 77                // we've reached capacity, remove the last used element...
 78                LinkedListNode<TKey> node = _list.Last;
 79                _list.RemoveLast();
 80                bool res = _dict.Remove(node.Value);
 81                Debug.Assert(res);
 82            }
 83            
 84            // add the new entry to the head of the list and into the dictionary
 85            LinkedListNode<TKey> listNode = new LinkedListNode<TKey>(key);
 86            _list.AddFirst(listNode);
 87            _dict[key] = new CacheDict<TKey, TValue>.KeyInfo(value, listNode);
 88        }
 89
 90        /// <summary>
 91        /// Returns the value associated with the given key, or throws KeyNotFoundException
 92        /// if the key is not present.
 93        /// </summary>
 94        public TValue this[TKey key] {
 95            get {
 96                TValue res;
 97                if (TryGetValue(key, out res)) {
 98                    return res;
 99                }
100                throw new KeyNotFoundException();
101            }
102            set {
103                Add(key, value);
104            }
105        }
106
107        private struct KeyInfo {
108            internal readonly TValue Value;
109            internal readonly LinkedListNode<TKey> List;
110
111            internal KeyInfo(TValue value, LinkedListNode<TKey> list) {
112                Value = value;
113                List = list;
114            }
115        }
116    }
117}