| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections; |
| | | 5 | | |
| | | 6 | | namespace CoreWCF.Dispatcher |
| | | 7 | | { |
| | | 8 | | internal class NameValueCache<T> |
| | | 9 | | { |
| | | 10 | | // The NameValueCache implements a structure that uses a dictionary to map objects to |
| | | 11 | | // indices of an array of cache entries. This allows us to store the cache entries in |
| | | 12 | | // the order in which they were added to the cache, and yet still lookup any cache entry. |
| | | 13 | | // The eviction policy of the cache is to evict the least-recently-added cache entry. |
| | | 14 | | // Using a pointer to the next available cache entry in the array, we can always be sure |
| | | 15 | | // that the given entry is the oldest entry. |
| | | 16 | | private readonly Hashtable _cache; |
| | | 17 | | private readonly string[] _currentKeys; |
| | | 18 | | private int _nextAvailableCacheIndex; |
| | | 19 | | internal const int MaxNumberofEntriesInCache = 16; |
| | | 20 | | |
| | | 21 | | public NameValueCache() |
| | 0 | 22 | | : this(MaxNumberofEntriesInCache) |
| | | 23 | | { |
| | 0 | 24 | | } |
| | | 25 | | |
| | 0 | 26 | | public NameValueCache(int maxCacheEntries) |
| | | 27 | | { |
| | 0 | 28 | | _cache = new Hashtable(); |
| | 0 | 29 | | _currentKeys = new string[maxCacheEntries]; |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 32 | | public T Lookup(string key) |
| | | 33 | | { |
| | 0 | 34 | | return (T)_cache[key]; |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | public void AddOrUpdate(string key, T value) |
| | | 38 | | { |
| | 0 | 39 | | lock (_cache) |
| | | 40 | | { |
| | 0 | 41 | | if (!_cache.ContainsKey(key)) |
| | | 42 | | { |
| | 0 | 43 | | if (!string.IsNullOrEmpty(_currentKeys[_nextAvailableCacheIndex])) |
| | | 44 | | { |
| | 0 | 45 | | _cache.Remove(_currentKeys[_nextAvailableCacheIndex]); |
| | | 46 | | } |
| | | 47 | | |
| | 0 | 48 | | _currentKeys[_nextAvailableCacheIndex] = key; |
| | 0 | 49 | | _nextAvailableCacheIndex = ++_nextAvailableCacheIndex % _currentKeys.Length; |
| | | 50 | | } |
| | | 51 | | |
| | 0 | 52 | | _cache[key] = value; |
| | 0 | 53 | | } |
| | 0 | 54 | | } |
| | | 55 | | } |
| | | 56 | | } |