| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577 |
- #if NET_4_0
- // ConcurrentSkipList.cs
- //
- // Copyright (c) 2009 Jérémie "Garuma" Laval
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- //
- using System;
- using System.Threading;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- namespace System.Collections.Concurrent
- {
- public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
- ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
- IDictionary, ICollection, IEnumerable
- {
- class Pair
- {
- public readonly TKey Key;
- public TValue Value;
-
- public Pair (TKey key, TValue value)
- {
- Key = key;
- Value = value;
- }
-
- public override bool Equals (object obj)
- {
- Pair rhs = obj as Pair;
- return rhs == null ? false : Key.Equals (rhs.Key) && Value.Equals (rhs.Value);
- }
-
- public override int GetHashCode ()
- {
- return Key.GetHashCode ();
- }
- }
-
- class Basket: List<Pair>
- {
- }
-
- // Assumption: a List<T> is never empty
- ConcurrentSkipList<Basket> container
- = new ConcurrentSkipList<Basket> ((value) => value[0].GetHashCode ());
- int count;
- IEqualityComparer<TKey> comparer;
-
- public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
- {
- }
-
- public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values)
- : this (values, EqualityComparer<TKey>.Default)
- {
- foreach (KeyValuePair<TKey, TValue> pair in values)
- Add (pair.Key, pair.Value);
- }
-
- public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
- {
- this.comparer = comparer;
- }
-
- public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values, IEqualityComparer<TKey> comparer)
- : this (comparer)
- {
- foreach (KeyValuePair<TKey, TValue> pair in values)
- Add (pair.Key, pair.Value);
- }
-
- // Parameters unused
- public ConcurrentDictionary (int concurrencyLevel, int capacity)
- : this (EqualityComparer<TKey>.Default)
- {
-
- }
-
- public ConcurrentDictionary (int concurrencyLevel,
- IEnumerable<KeyValuePair<TKey, TValue>> values,
- IEqualityComparer<TKey> comparer)
- : this (values, comparer)
- {
-
- }
-
- // Parameters unused
- public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
- : this (comparer)
- {
-
- }
-
- void Add (TKey key, TValue value)
- {
- while (!TryAdd (key, value));
- }
-
- void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
- {
- Add (key, value);
- }
-
- public bool TryAdd (TKey key, TValue value)
- {
- Basket basket;
- // Add a value to an existing basket
- if (TryGetBasket (key, out basket)) {
- // Find a maybe more sexy locking scheme later
- lock (basket) {
- foreach (var p in basket) {
- if (comparer.Equals (p.Key, key))
- throw new ArgumentException ("An element with the same key already exists");
- }
- basket.Add (new Pair (key, value));
- }
- } else {
- // Add a new basket
- basket = new Basket ();
- basket.Add (new Pair (key, value));
-
- if (container.TryAdd (basket)) {
- Interlocked.Increment (ref count);
- return true;
- } else {
- return false;
- }
- }
-
- Interlocked.Increment (ref count);
-
- return true;
- }
-
- void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
- {
- Add (pair.Key, pair.Value);
- }
-
- public TValue AddOrUpdate (TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
- {
- Basket basket;
- TValue temp;
-
- if (!TryGetBasket (key, out basket)) {
- Add (key, (temp = addValueFactory (key)));
- } else {
- lock (basket) {
- Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
- if (pair == null)
- throw new InvalidOperationException ("pair is null, shouldn't be");
- pair.Value = (temp = updateValueFactory (key, pair.Value));
- }
- }
-
- return temp;
- }
-
- public TValue AddOrUpdate (TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
- {
- return AddOrUpdate (key, (_) => addValue, updateValueFactory);
- }
-
- TValue GetValue (TKey key)
- {
- TValue temp;
- if (!TryGetValue (key, out temp))
- // TODO: find a correct Exception
- throw new ArgumentException ("Not a valid key for this dictionary", "key");
- return temp;
- }
-
- public bool TryGetValue (TKey key, out TValue value)
- {
- Basket basket;
- value = default (TValue);
-
- if (!TryGetBasket (key, out basket))
- return false;
-
- lock (basket) {
- Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
- if (pair == null)
- return false;
- value = pair.Value;
- }
-
- return true;
- }
-
- public bool TryUpdate (TKey key, TValue newValue, TValue comparand)
- {
- Basket basket;
- if (!TryGetBasket (key, out basket))
- return false;
-
- lock (basket) {
- Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
- if (pair.Value.Equals (comparand)) {
- pair.Value = newValue;
-
- return true;
- }
- }
-
- return false;
- }
-
- public TValue this[TKey key] {
- get {
- return GetValue (key);
- }
- set {
- Basket basket;
- if (!TryGetBasket (key, out basket)) {
- Add (key, value);
- return;
- }
- lock (basket) {
- Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
- if (pair == null)
- throw new InvalidOperationException ("pair is null, shouldn't be");
- pair.Value = value;
- }
- }
- }
-
- public TValue GetOrAdd (TKey key, Func<TKey, TValue> valueFactory)
- {
- Basket basket;
- TValue temp = default (TValue);
-
- if (TryGetBasket (key, out basket)) {
- Pair pair = null;
- lock (basket) {
- pair = basket.Find ((p) => comparer.Equals (p.Key, key));
- if (pair != null)
- temp = pair.Value;
- }
-
- if (pair == null)
- Add (key, (temp = valueFactory (key)));
- } else {
- Add (key, (temp = valueFactory (key)));
- }
-
- return temp;
- }
-
- public TValue GetOrAdd (TKey key, TValue value)
- {
- return GetOrAdd (key, (_) => value);
- }
-
- public bool TryRemove(TKey key, out TValue value)
- {
- value = default (TValue);
- Basket b;
-
- if (!TryGetBasket (key, out b))
- return false;
-
- lock (b) {
- TValue temp = default (TValue);
- // Should always be == 1 but who know
- bool result = b.RemoveAll ((p) => {
- bool r = comparer.Equals (p.Key, key);
- if (r) temp = p.Value;
- return r;
- }) >= 1;
- value = temp;
-
- if (result)
- Interlocked.Decrement (ref count);
-
- return result;
- }
- }
-
- bool Remove (TKey key)
- {
- TValue dummy;
-
- return TryRemove (key, out dummy);
- }
-
- bool IDictionary<TKey, TValue>.Remove (TKey key)
- {
- return Remove (key);
- }
-
- bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
- {
- return Remove (pair.Key);
- }
-
- public bool ContainsKey (TKey key)
- {
- return container.ContainsFromHash (key.GetHashCode ());
- }
-
- bool IDictionary.Contains (object key)
- {
- if (!(key is TKey))
- return false;
-
- return ContainsKey ((TKey)key);
- }
-
- void IDictionary.Remove (object key)
- {
- if (!(key is TKey))
- return;
-
- Remove ((TKey)key);
- }
-
- object IDictionary.this [object key]
- {
- get {
- if (!(key is TKey))
- throw new ArgumentException ("key isn't of correct type", "key");
-
- return this[(TKey)key];
- }
- set {
- if (!(key is TKey) || !(value is TValue))
- throw new ArgumentException ("key or value aren't of correct type");
-
- this[(TKey)key] = (TValue)value;
- }
- }
-
- void IDictionary.Add (object key, object value)
- {
- if (!(key is TKey) || !(value is TValue))
- throw new ArgumentException ("key or value aren't of correct type");
-
- Add ((TKey)key, (TValue)value);
- }
-
- bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
- {
- return ContainsKey (pair.Key);
- }
-
- public KeyValuePair<TKey,TValue>[] ToArray ()
- {
- // This is most certainly not optimum but there is
- // not a lot of possibilities
-
- return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
- }
-
- public void Clear()
- {
- // Pronk
- container = new ConcurrentSkipList<Basket> ((value) => value [0].GetHashCode ());
- }
-
- public int Count {
- get {
- return count;
- }
- }
-
- public bool IsEmpty {
- get {
- return count == 0;
- }
- }
-
- bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
- get {
- return false;
- }
- }
-
- bool IDictionary.IsReadOnly {
- get {
- return false;
- }
- }
-
- public ICollection<TKey> Keys {
- get {
- return GetPart<TKey> ((kvp) => kvp.Key);
- }
- }
-
- public ICollection<TValue> Values {
- get {
- return GetPart<TValue> ((kvp) => kvp.Value);
- }
- }
-
- ICollection IDictionary.Keys {
- get {
- return (ICollection)Keys;
- }
- }
-
- ICollection IDictionary.Values {
- get {
- return (ICollection)Values;
- }
- }
-
- ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
- {
- List<T> temp = new List<T> ();
-
- foreach (KeyValuePair<TKey, TValue> kvp in this)
- temp.Add (extractor (kvp));
-
- return temp.AsReadOnly ();
- }
-
- void ICollection.CopyTo (Array array, int startIndex)
- {
- KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
- if (arr == null)
- return;
-
- CopyTo (arr, startIndex, count);
- }
-
- void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
- {
- CopyTo (array, startIndex, count);
- }
-
- void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
- {
- CopyTo (array, startIndex);
- }
-
- void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
- {
- // TODO: This is quite unsafe as the count value will likely change during
- // the copying. Watchout for IndexOutOfRange thingies
- if (array.Length <= count + startIndex)
- throw new InvalidOperationException ("The array isn't big enough");
-
- int i = startIndex;
-
- foreach (Basket b in container) {
- lock (b) {
- foreach (Pair p in b) {
- if (i >= num)
- break;
- array[i++] = new KeyValuePair<TKey, TValue> (p.Key, p.Value);
- }
- }
- }
- }
-
- public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
- {
- return GetEnumeratorInternal ();
- }
-
- IEnumerator IEnumerable.GetEnumerator ()
- {
- return (IEnumerator)GetEnumeratorInternal ();
- }
-
- IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
- {
- foreach (Basket b in container) {
- lock (b) {
- foreach (Pair p in b)
- yield return new KeyValuePair<TKey, TValue> (p.Key, p.Value);
- }
- }
- }
-
- IDictionaryEnumerator IDictionary.GetEnumerator ()
- {
- return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
- }
-
- class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
- {
- IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
-
- public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
- {
- this.internalEnum = internalEnum;
- }
-
- public bool MoveNext ()
- {
- return internalEnum.MoveNext ();
- }
-
- public void Reset ()
- {
- internalEnum.Reset ();
- }
-
- public object Current {
- get {
- return Entry;
- }
- }
-
- public DictionaryEntry Entry {
- get {
- KeyValuePair<TKey, TValue> current = internalEnum.Current;
- return new DictionaryEntry (current.Key, current.Value);
- }
- }
-
- public object Key {
- get {
- return internalEnum.Current.Key;
- }
- }
-
- public object Value {
- get {
- return internalEnum.Current.Value;
- }
- }
- }
-
- object ICollection.SyncRoot {
- get {
- return this;
- }
- }
-
- bool IDictionary.IsFixedSize {
- get {
- return false;
- }
- }
-
- bool ICollection.IsSynchronized {
- get { return true; }
- }
- bool TryGetBasket (TKey key, out Basket basket)
- {
- basket = null;
- if (!container.GetFromHash (key.GetHashCode (), out basket))
- return false;
-
- return true;
- }
- }
- }
- #endif
|