Ejemplo n.º 1
0
        public static void TestRemove3()
        {
            LurchTable <int, int> dict = new LurchTable <int, int>();

            dict[99] = -99;

            ICollection <KeyValuePair <int, int> > col = dict;

            // Make sure we cannot "remove" a key/value pair which is not in the dictionary
            for (int i = 0; i < 200; i++)
            {
                if (i != 99)
                {
                    Assert.False(col.Remove(new KeyValuePair <int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)");
                    Assert.False(col.Remove(new KeyValuePair <int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)");
                }
            }

            // Can we remove a key/value pair successfully?
            Assert.True(col.Remove(new KeyValuePair <int, int>(99, -99)), "Failed to remove existing key/value pair");

            // Make sure the key/value pair is gone
            Assert.False(col.Remove(new KeyValuePair <int, int>(99, -99)), "Should not remove the key/value pair which has been removed");

            // And that the dictionary is empty. We will check the count in a few different ways:
            Assert.Equal(0, dict.Count);
            Assert.Equal(0, dict.ToArray().Length);
        }
Ejemplo n.º 2
0
 public LocaleObjectCache(int initialCapacity)
 {
     // ICU4N: Since .NET doesn't have a memory-sensitive cache, we are using an LRU cache with a fixed size.
     // This ensures that the culture(s) that the application uses most stay near the top of the cache and
     // less used cultures get popped off of the bottom of the cache.
     _map = new LurchTable <TKey, Lazy <TValue> >(initialCapacity, LurchTableOrder.Access, limit: 64, comparer: null);
 }
Ejemplo n.º 3
0
        public static void TestAddNullValue_ConcurrentDictionaryOfString_null()
        {
            // using ConcurrentDictionary<TKey, TValue> class
            LurchTable <string, string> dict1 = new LurchTable <string, string>();

            dict1["key"] = null;
        }
Ejemplo n.º 4
0
        public static void TestBugFix669376()
        {
            var cd = new LurchTable <string, int>(new OrdinalStringComparer());

            cd["test"] = 10;
            Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work");
        }
Ejemplo n.º 5
0
        public Task AddDiagnostics(string category, string type, string step, DiagnosticsData data)
        {
            var loweredCategory = (category ?? "").ToSlug().ToLower();
            var loweredType     = (type ?? "").ToSlug().ToLower();
            var loweredStep     = (step ?? "").ToSlug().ToLower();

            if (!Data.ContainsKey(loweredCategory))
            {
                Data[loweredCategory] = new ConcurrentDictionary <string, LurchTable <string, ConcurrentBag <DiagnosticsData> > >();
            }

            if (!Data[loweredCategory].ContainsKey(loweredType))
            {
                Data[loweredCategory][loweredType] = new LurchTable <string, ConcurrentBag <DiagnosticsData> >(50);
            }

            if (!Data[loweredCategory][loweredType].ContainsKey(loweredStep))
            {
                Data[loweredCategory][loweredType][loweredStep] = new ConcurrentBag <DiagnosticsData>();
            }

            Data[loweredCategory][loweredType][loweredStep].Add(data);

            return(Task.CompletedTask);
        }
Ejemplo n.º 6
0
        public static void TestICollection()
        {
            ICollection dictionary = new LurchTable <int, int>();

            Assert.False(dictionary.IsSynchronized, "TestICollection:  FAILED.  IsSynchronized returned true!");

            int key   = -1;
            int value = +1;

            //add one item to the dictionary
            ((LurchTable <int, int>)dictionary).TryAdd(key, value);

            var objectArray = new object[1];

            dictionary.CopyTo(objectArray, 0);

            Assert.Equal(key, ((KeyValuePair <int, int>)objectArray[0]).Key);
            Assert.Equal(value, ((KeyValuePair <int, int>)objectArray[0]).Value);

            var keyValueArray = new KeyValuePair <int, int> [1];

            dictionary.CopyTo(keyValueArray, 0);
            Assert.Equal(key, keyValueArray[0].Key);
            Assert.Equal(value, keyValueArray[0].Value);

            var entryArray = new DictionaryEntry[1];

            dictionary.CopyTo(entryArray, 0);
            Assert.Equal(key, (int)entryArray[0].Key);
            Assert.Equal(value, (int)entryArray[0].Value);
        }
 public void IDictionary_NonGeneric_Contains_KeyOfWrongType()
 {
     if (!IsReadOnly)
     {
         IDictionary dictionary = new LurchTable <string, int>();
         Assert.False(dictionary.Contains(1));
     }
 }
Ejemplo n.º 8
0
 public EntityCache(string entityPluralSchemaName, int capacity, Func <string, string, string> recordValidator, params string[] attributesToCache)
 {
     _entityPluralSchemaName = entityPluralSchemaName;
     _recordValidator        = recordValidator;
     CachedRecords           = new LurchTable <Guid, TRecord>(capacity);
     CachedAttributeNames    = new List <string>(attributesToCache);
     _selectAttributes       = string.Join(",", attributesToCache);
 }
Ejemplo n.º 9
0
        public static void TryRemove_KeyValuePair_MatchesKeyWithDefaultComparer()
        {
            var dict = new LurchTable <string, string>(StringComparer.OrdinalIgnoreCase);

            dict.TryAdd("key", "value");
            Assert.False(dict.TryRemove(new KeyValuePair <string, string>("key", "VALUE")));
            Assert.True(dict.TryRemove(new KeyValuePair <string, string>("KEY", "value")));
        }
Ejemplo n.º 10
0
        public void Dictionary_Generic_Constructor_int_IEqualityComparer(int count)
        {
            SCG.IEqualityComparer <TKey> comparer   = GetKeyIEqualityComparer();
            LurchTable <TKey, TValue>    dictionary = new LurchTable <TKey, TValue>(count, LurchTableOrder.None, comparer);

            Assert.Equal(0, dictionary.Count);
            Assert.Equal(comparer, dictionary.EqualityComparer);
        }
Ejemplo n.º 11
0
        public static void TestConstructor()
        {
            var dictionary = new LurchTable <int, int>(new[] { new KeyValuePair <int, int>(1, 1) });

            Assert.False(dictionary.IsEmpty);
            Assert.Equal(1, dictionary.Keys.Count);
            Assert.Equal(1, dictionary.Values.Count);
        }
Ejemplo n.º 12
0
        public static void TestAddNullValue_IDictionaryOfString_null()
        {
            // using IDictionary<TKey, TValue> interface
            IDictionary <string, string> dict2 = new LurchTable <string, string>();

            dict2["key"] = null;
            dict2.Add("key2", null);
        }
Ejemplo n.º 13
0
        public static void TestAddNullValue_IDictionary_ReferenceType_null()
        {
            // using IDictionary interface
            IDictionary dict3 = new LurchTable <string, string>();

            dict3["key"] = null;
            dict3.Add("key2", null);
        }
Ejemplo n.º 14
0
        public void LurchTableDemo()
        {
            var counts = new Counts();

            //Queue where producer helps when queue is full
            using (var queue = new LurchTable <string, int>(LurchTableOrder.Insertion, 10))
            {
                var stop = new ManualResetEvent(false);
                queue.ItemRemoved += kv =>
                {
                    Interlocked.Increment(ref counts.Dequeued);
                    Console.WriteLine("[{0}] - {1}", Thread.CurrentThread.ManagedThreadId, kv.Key);
                };
                //start some threads eating queue:
                var thread = new Thread(() =>
                {
                    while (!stop.WaitOne(0))
                    {
                        KeyValuePair <string, int> kv;
                        while (queue.TryDequeue(out kv))
                        {
                            continue;
                        }
                    }
                })
                {
                    Name = "worker", IsBackground = true
                };
                thread.Start();

                var names = Directory.GetFiles(Path.GetTempPath(), "*", SearchOption.AllDirectories);
                if (names.Length < 1)
                {
                    throw new Exception("Not enough trash in your temp dir.");
                }
                var loops = Math.Max(1, 100 / names.Length);
                for (int i = 0; i < loops; i++)
                {
                    foreach (var name in names)
                    {
                        Interlocked.Increment(ref counts.Queued);
                        queue[name] = i;
                    }
                }

                //help empty the queue
                KeyValuePair <string, int> tmp;
                while (queue.TryDequeue(out tmp))
                {
                    continue;
                }
                //shutdown
                stop.Set();
                thread.Join();
            }

            Assert.AreEqual(counts.Queued, counts.Dequeued);
        }
 public void IDictionary_NonGeneric_ItemSet_KeyOfWrongType()
 {
     if (!IsReadOnly)
     {
         IDictionary dictionary = new LurchTable <string, string>();
         AssertExtensions.Throws <ArgumentException>("key", () => dictionary[23] = CreateTValue(12345));
         Assert.Empty(dictionary);
     }
 }
Ejemplo n.º 16
0
        public void Dictionary_Generic_Constructor_IEqualityComparer(int count)
        {
            SCG.IEqualityComparer <TKey>   comparer = GetKeyIEqualityComparer();
            SCG.IDictionary <TKey, TValue> source   = GenericIDictionaryFactory(count);
            LurchTable <TKey, TValue>      copied   = new LurchTable <TKey, TValue>(source, comparer);

            Assert.Equal(source, copied);
            Assert.Equal(comparer, copied.EqualityComparer);
        }
Ejemplo n.º 17
0
        public static void TestIDictionary()
        {
            IDictionary dictionary = new LurchTable <string, int>();

            Assert.False(dictionary.IsReadOnly);

            // Empty dictionary should not enumerate
            Assert.Empty(dictionary);

            const int SIZE = 10;

            for (int i = 0; i < SIZE; i++)
            {
                dictionary.Add(i.ToString(), i);
            }

            Assert.Equal(SIZE, dictionary.Count);

            //test contains
            Assert.False(dictionary.Contains(1), "TestIDictionary:  FAILED.  Contain returned true for incorrect key type");
            Assert.False(dictionary.Contains("100"), "TestIDictionary:  FAILED.  Contain returned true for incorrect key");
            Assert.True(dictionary.Contains("1"), "TestIDictionary:  FAILED.  Contain returned false for correct key");

            //test GetEnumerator
            int count = 0;

            foreach (var obj in dictionary)
            {
                DictionaryEntry entry         = (DictionaryEntry)obj;
                string          key           = (string)entry.Key;
                int             value         = (int)entry.Value;
                int             expectedValue = int.Parse(key);
                Assert.True(value == expectedValue,
                            string.Format("TestIDictionary:  FAILED.  Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue));
                count++;
            }

            Assert.Equal(SIZE, count);
            Assert.Equal(SIZE, dictionary.Keys.Count);
            Assert.Equal(SIZE, dictionary.Values.Count);

            //Test Remove
            dictionary.Remove("9");
            Assert.Equal(SIZE - 1, dictionary.Count);

            //Test this[]
            for (int i = 0; i < dictionary.Count; i++)
            {
                Assert.Equal(i, (int)dictionary[i.ToString()]);
            }

            dictionary["1"] = 100; // try a valid setter
            Assert.Equal(100, (int)dictionary["1"]);

            //non-existing key
            Assert.Null(dictionary["NotAKey"]);
        }
        private static SCG.IDictionary <T, T> CreateDictionary <T>(int size, Func <int, T> keyValueSelector, SCG.IEqualityComparer <T> comparer = null)
        {
            SCG.Dictionary <T, T> temp = Enumerable.Range(0, size + 1).ToDictionary(keyValueSelector, keyValueSelector, comparer);
            LurchTable <T, T>     dict = new LurchTable <T, T>(temp, comparer);

            // Remove first item to reduce Count to size and alter the contiguity of the dictionary
            dict.Remove(keyValueSelector(0));
            return(dict);
        }
        /// <summary>
        /// 构造函数中使用config文件初始化token缓存大小
        /// </summary>
        private SingleUserTokenMutability()
        {
            //int _limit = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LurchTableCache"]);
            //存放的数据应该是devicetype长度的
            int _limit = System.Enum.GetNames(typeof(DeviceType)).Length;

            //构造函数中处理缓存大小,从xml中配置
            _tokenDictionary_s = new LurchTable<string, UserDeviceMutability>(_limit,LurchTableOrder.Access);
        }
Ejemplo n.º 20
0
        private static void TestRemove2(int removesPerThread)
        {
            LurchTable <int, int> dict = new LurchTable <int, int>();

            for (int i = 0; i < removesPerThread; i++)
            {
                dict[i] = -i;
            }

            // The dictionary contains keys [0..N), each key mapped to a value equal to the key.
            // Threads will cooperatively remove all even keys.
            const int SIZE    = 2;
            int       running = SIZE;

            bool[][] seen = new bool[SIZE][];
            for (int i = 0; i < SIZE; i++)
            {
                seen[i] = new bool[removesPerThread];
            }

            using (ManualResetEvent mre = new ManualResetEvent(false))
            {
                for (int t = 0; t < SIZE; t++)
                {
                    int thread = t;
                    Task.Run(
                        () =>
                    {
                        for (int key = 0; key < removesPerThread; key++)
                        {
                            int value;
                            if (dict.TryRemove(key, out value))
                            {
                                seen[thread][key] = true;

                                Assert.Equal(-key, value);
                            }
                        }
                        if (Interlocked.Decrement(ref running) == 0)
                        {
                            mre.Set();
                        }
                    });
                }
                mre.WaitOne();
            }

            Assert.Equal(0, dict.Count);

            for (int i = 0; i < removesPerThread; i++)
            {
                Assert.False(seen[0][i] == seen[1][i],
                             string.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread)
                             );
            }
        }
Ejemplo n.º 21
0
        public static void TestAddNullValue_IDictionary_ValueType_null_add()
        {
            Action action = () =>
            {
                IDictionary dict5 = new LurchTable <string, int>();
                dict5.Add("key", null);
            };

            Assert.Throws <ArgumentNullException>(action);
        }
 public void IDictionary_NonGeneric_Add_NullValueWhenDefaultTValueIsNonNull()
 {
     if (!IsReadOnly)
     {
         IDictionary dictionary = new LurchTable <string, int>();
         object      missingKey = GetNewKey(dictionary);
         Assert.Throws <ArgumentNullException>(() => dictionary.Add(missingKey, null));
         Assert.Empty(dictionary);
     }
 }
Ejemplo n.º 23
0
        public void Dictionary_Generic_RemoveKey_ValidKeyNotContainedInDictionary(int count)
        {
            LurchTable <TKey, TValue> dictionary = (LurchTable <TKey, TValue>)GenericIDictionaryFactory(count);
            TValue value;
            TKey   missingKey = GetNewKey(dictionary);

            Assert.False(dictionary.Remove(missingKey, out value));
            Assert.Equal(count, dictionary.Count);
            Assert.Equal(default(TValue), value);
        }
 public void IDictionary_NonGeneric_ItemSet_ValueOfWrongType()
 {
     if (!IsReadOnly)
     {
         IDictionary dictionary = new LurchTable <string, string>();
         object      missingKey = GetNewKey(dictionary);
         AssertExtensions.Throws <ArgumentException>("value", () => dictionary[missingKey] = 324);
         Assert.Empty(dictionary);
     }
 }
 public void IDictionary_NonGeneric_Add_KeyOfWrongType()
 {
     if (!IsReadOnly)
     {
         IDictionary dictionary = new LurchTable <string, string>();
         object      missingKey = 23;
         AssertExtensions.Throws <ArgumentException>("key", () => dictionary.Add(missingKey, CreateTValue(12345)));
         Assert.Empty(dictionary);
     }
 }
 /// <summary>
 /// 构造函数中使用config文件初始化token缓存大小
 /// </summary>
 public SingleUserToken()
 {
     int _limit = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LurchTableCache"]);
     //防止出现意外没有找到配置的问题
     if (_limit<1) {
         _limit = 5;
     }
     //构造函数中处理缓存大小,从xml中配置
     _tokenLurchtables = new LurchTable<string, UserToken>(LurchTableOrder.Access,_limit);
 }
 protected UserDeviceMutability()
 {
     //配置文件中获取内存大小,用于存放的记录数量上限
     int _limit = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LurchTableCache"]);
     //防止出现意外没有找到配置的问题
     if (_limit < 1)
     {
         _limit = 5;
     }
     _userTokenMutability_s = new LurchTable<string, UserTokenMutability>(LurchTableOrder.Access, _limit);
 }
Ejemplo n.º 28
0
        public static void TestAddNullValue_IDictionary_ValueType_null_indexer()
        {
            // using IDictionary interface and value type values
            Action action = () =>
            {
                IDictionary dict4 = new LurchTable <string, int>();
                dict4["key"] = null;
            };

            Assert.Throws <ArgumentNullException>(action);
        }
        public void LurchTable_Generic_ValueCollection_GetEnumerator(int count)
        {
            LurchTable <string, string> dictionary = new LurchTable <string, string>();
            int seed = 13453;

            while (dictionary.Count < count)
            {
                dictionary.Add(CreateT(seed++), CreateT(seed++));
            }
            dictionary.Values.GetEnumerator();
        }
        protected override ICollection NonGenericICollectionFactory(int count)
        {
            LurchTable <string, string> list = new LurchTable <string, string>();
            int seed = 13453;

            for (int i = 0; i < count; i++)
            {
                list.Add(CreateT(seed++), CreateT(seed++));
            }
            return(list.Values);
        }
Ejemplo n.º 31
0
 public void Dictionary_Generic_RemoveKey_DefaultKeyContainedInDictionary(int count)
 {
     if (DefaultValueAllowed)
     {
         LurchTable <TKey, TValue> dictionary = (LurchTable <TKey, TValue>)(GenericIDictionaryFactory(count));
         TKey   missingKey = default(TKey);
         TValue value;
         dictionary.TryAdd(missingKey, default(TValue));
         Assert.True(dictionary.Remove(missingKey, out value));
     }
 }
Ejemplo n.º 32
0
            public StorageCache(INodeStorage store, int sizeLimit)
            {
                _asyncThreshold   = 50;
                _writeBehindFunc  = Flush;
                _asyncWriteBehind = null;

                _store              = store;
                _cache              = new LurchTable <IStorageHandle, object>(LurchTableOrder.Access, sizeLimit, 1000000, sizeLimit >> 4, 1000, EqualityComparer <IStorageHandle> .Default);
                _dirty              = new LurchTable <IStorageHandle, object>(LurchTableOrder.Modified, sizeLimit, 1000000, sizeLimit >> 4, 1000, EqualityComparer <IStorageHandle> .Default);
                _dirty.ItemRemoved += OnItemRemoved;
            }
        public void CompareTest()
        {
            const int size = 1000000;
            int       reps = 3;
            Stopwatch timer;

            IDictionary <Guid, TestValue> dict = new ConcurrentDictionary <Guid, TestValue>(new Dictionary <Guid, TestValue>(size));
            IDictionary <Guid, TestValue> test = new LurchTable <Guid, TestValue>(size);

            for (int rep = 0; rep < reps; rep++)
            {
                var sample = CreateSample(Guid.NewGuid(), size, 1);

                timer = Stopwatch.StartNew();
                Parallel(1, sample, item => dict.Add(item, new TestValue {
                    Id = item, Count = rep
                }));
                Trace.TraceInformation("Dict Add: {0}", timer.Elapsed);

                timer = Stopwatch.StartNew();
                Parallel(1, sample, item => test.Add(item, new TestValue {
                    Id = item, Count = rep
                }));
                Trace.TraceInformation("Test Add: {0}", timer.Elapsed);

                timer = Stopwatch.StartNew();
                Parallel(1, sample, item => dict[item] = new TestValue {
                    Id = item, Count = rep
                });
                Trace.TraceInformation("Dict Update: {0}", timer.Elapsed);

                timer = Stopwatch.StartNew();
                Parallel(1, sample, item => test[item] = new TestValue {
                    Id = item, Count = rep
                });
                Trace.TraceInformation("Test Update: {0}", timer.Elapsed);

                timer = Stopwatch.StartNew();
                Parallel(1, sample, item => dict.Remove(item));
                Trace.TraceInformation("Dict Rem: {0}", timer.Elapsed);
                Assert.AreEqual(0, dict.Count);

                timer = Stopwatch.StartNew();
                Parallel(1, sample, item => test.Remove(item));
                Trace.TraceInformation("Test Rem: {0}", timer.Elapsed);

                test.Clear();
                dict.Clear();

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        public void LurchTableDemo()
        {
            var counts = new Counts();
            //Queue where producer helps when queue is full
            using (var queue = new LurchTable<string, int>(LurchTableOrder.Insertion, 10))
            {
                var stop = new ManualResetEvent(false);
                queue.ItemRemoved += kv =>
                    {
                        Interlocked.Increment(ref counts.Dequeued);
                        Console.WriteLine("[{0}] - {1}", Thread.CurrentThread.ManagedThreadId, kv.Key);
                    };
                //start some threads eating queue:
                var thread = new Thread(() => 
                {
                    while (!stop.WaitOne(0))
                    {
                        KeyValuePair<string, int> kv;
                        while (queue.TryDequeue(out kv))
                            continue;
                    }
                })
                    { Name = "worker", IsBackground = true };
                thread.Start();

                var names = Directory.GetFiles(Path.GetTempPath(), "*", SearchOption.AllDirectories);
                if (names.Length < 1) throw new Exception("Not enough trash in your temp dir.");
                var loops = Math.Max(1, 100/names.Length);
                for(int i=0; i < loops; i++)
                    foreach (var name in names)
                    {
                        Interlocked.Increment(ref counts.Queued);
                        queue[name] = i;
                    }

                //help empty the queue
                KeyValuePair<string, int> tmp;
                while (queue.TryDequeue(out tmp))
                    continue;
                //shutdown
                stop.Set();
                thread.Join();
            }

            Assert.AreEqual(counts.Queued, counts.Dequeued);
        }