2 // System.Collections.Generic.SortedList.cs
5 // Sergey Chaban (serge@wildwestsoftware.com)
6 // Duncan Mak (duncan@ximian.com)
7 // Herve Poussineau (hpoussineau@fr.st
8 // Zoltan Varga (vargaz@gmail.com)
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 using System.Collections;
38 using System.Globalization;
39 using System.Runtime.InteropServices;
41 namespace System.Collections.Generic
44 /// Represents a collection of associated keys and values
45 /// that are sorted by the keys and are accessible by key
50 public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>,
53 ICollection<KeyValuePair<TKey, TValue>>,
54 IEnumerable<KeyValuePair<TKey, TValue>>,
57 private readonly static int INITIAL_SIZE = 16;
59 private enum EnumeratorMode : int { KEY_MODE = 0, VALUE_MODE, ENTRY_MODE }
62 private int modificationCount;
63 private KeyValuePair<TKey, TValue>[] table;
64 private IComparer<TKey> comparer;
65 private int defaultCapacity;
71 : this (INITIAL_SIZE, null)
75 public SortedList (int capacity)
76 : this (capacity, null)
80 public SortedList (int capacity, IComparer<TKey> comparer)
83 throw new ArgumentOutOfRangeException ("initialCapacity");
88 defaultCapacity = INITIAL_SIZE;
89 Init (comparer, capacity, true);
92 public SortedList (IComparer<TKey> comparer) : this (INITIAL_SIZE, comparer)
96 public SortedList (IDictionary<TKey, TValue> dictionary) : this (dictionary, null)
100 public SortedList (IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer)
102 if (dictionary == null)
103 throw new ArgumentNullException ("dictionary");
105 Init (comparer, dictionary.Count, true);
107 foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
108 Add (kvp.Key, kvp.Value);
123 bool ICollection.IsSynchronized {
129 Object ICollection.SyncRoot {
137 bool IDictionary.IsFixedSize {
143 bool IDictionary.IsReadOnly {
149 public TValue this [TKey key] {
152 throw new ArgumentNullException("key");
157 return table [i].Value;
159 throw new KeyNotFoundException ();
163 throw new ArgumentNullException("key");
165 PutImpl (key, value, true);
169 object IDictionary.this [object key] {
174 return this [(TKey)key];
178 this [ToKey (key)] = ToValue (value);
182 public int Capacity {
188 int current = this.table.Length;
191 throw new ArgumentOutOfRangeException("capacity too small");
193 else if (value == 0) {
194 // return to default size
195 KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [defaultCapacity];
196 Array.Copy (table, newTable, inUse);
197 this.table = newTable;
200 else if (current > defaultCapacity && value < current) {
201 KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [defaultCapacity];
202 Array.Copy (table, newTable, inUse);
203 this.table = newTable;
206 else if (value > inUse) {
207 KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [value];
208 Array.Copy (table, newTable, inUse);
209 this.table = newTable;
211 else if (value > current) {
212 KeyValuePair<TKey, TValue> [] newTable = new KeyValuePair<TKey, TValue> [value];
213 Array.Copy (table, newTable, current);
214 this.table = newTable;
219 public IList<TKey> Keys {
221 return new ListKeys (this);
225 public IList<TValue> Values {
227 return new ListValues (this);
231 ICollection IDictionary.Keys {
233 return new ListKeys (this);
237 ICollection IDictionary.Values {
239 return new ListValues (this);
243 ICollection<TKey> IDictionary<TKey, TValue>.Keys {
249 ICollection<TValue> IDictionary<TKey, TValue>.Values {
255 public IComparer<TKey> Comparer {
261 bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
268 // Public instance methods.
271 public void Add (TKey key, TValue value)
274 throw new ArgumentNullException ("key");
276 PutImpl (key, value, false);
279 public bool ContainsKey (TKey key)
282 throw new ArgumentNullException ("key");
284 return (Find (key) >= 0);
287 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
289 for (int i = 0; i < inUse; i ++) {
290 KeyValuePair<TKey, TValue> current = this.table [i];
292 yield return new KeyValuePair<TKey, TValue> (current.Key, current.Value);
296 public bool Remove (TKey key)
299 throw new ArgumentNullException ("key");
301 int i = IndexOfKey (key);
310 // ICollection<KeyValuePair<TKey, TValue>>
312 void ICollection<KeyValuePair<TKey, TValue>>.Clear ()
314 defaultCapacity = INITIAL_SIZE;
315 this.table = new KeyValuePair<TKey, TValue> [defaultCapacity];
322 defaultCapacity = INITIAL_SIZE;
323 this.table = new KeyValuePair<TKey, TValue> [defaultCapacity];
328 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)
331 throw new ArgumentNullException();
334 throw new ArgumentOutOfRangeException();
336 if (arrayIndex >= array.Length)
337 throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
338 if (Count > (array.Length - arrayIndex))
339 throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
342 foreach (KeyValuePair<TKey, TValue> pair in this)
346 void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> keyValuePair) {
347 Add (keyValuePair.Key, keyValuePair.Value);
350 bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> keyValuePair) {
351 int i = Find (keyValuePair.Key);
354 return Comparer<KeyValuePair<TKey, TValue>>.Default.Compare (table [i], keyValuePair) == 0;
359 bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> keyValuePair) {
360 int i = Find (keyValuePair.Key);
362 if (i >= 0 && (Comparer<KeyValuePair<TKey, TValue>>.Default.Compare (table [i], keyValuePair) == 0)) {
370 // IEnumerable<KeyValuePair<TKey, TValue>>
372 IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator ()
374 for (int i = 0; i < inUse; i ++) {
375 KeyValuePair<TKey, TValue> current = this.table [i];
377 yield return new KeyValuePair<TKey, TValue> (current.Key, current.Value);
383 IEnumerator IEnumerable.GetEnumerator ()
385 return GetEnumerator ();
390 void IDictionary.Add (object key, object value)
392 PutImpl (ToKey (key), ToValue (value), false);
395 bool IDictionary.Contains (object key)
398 throw new ArgumentNullException();
402 return (Find ((TKey)key) >= 0);
405 IDictionaryEnumerator IDictionary.GetEnumerator ()
407 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
410 void IDictionary.Remove (object key)
413 throw new ArgumentNullException ("key");
416 int i = IndexOfKey ((TKey)key);
417 if (i >= 0) RemoveAt (i);
422 void ICollection.CopyTo (Array array, int arrayIndex)
425 throw new ArgumentNullException();
428 throw new ArgumentOutOfRangeException();
431 throw new ArgumentException("array is multi-dimensional");
432 if (arrayIndex >= array.Length)
433 throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
434 if (Count > (array.Length - arrayIndex))
435 throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
437 IEnumerator<KeyValuePair<TKey,TValue>> it = GetEnumerator ();
440 while (it.MoveNext ()) {
441 array.SetValue (it.Current, i++);
446 // SortedList<TKey, TValue>
449 public void RemoveAt (int index)
451 KeyValuePair<TKey, TValue> [] table = this.table;
453 if (index >= 0 && index < cnt) {
454 if (index != cnt - 1) {
455 Array.Copy (table, index+1, table, index, cnt-1-index);
457 table [index] = default (KeyValuePair <TKey, TValue>);
462 throw new ArgumentOutOfRangeException("index out of range");
466 public int IndexOfKey (TKey key)
469 throw new ArgumentNullException ("key");
474 } catch (Exception) {
475 throw new InvalidOperationException();
478 return (indx | (indx >> 31));
481 public int IndexOfValue (TValue value)
486 for (int i = 0; i < inUse; i ++) {
487 KeyValuePair<TKey, TValue> current = this.table [i];
489 if (Equals (value, current.Value))
496 public bool ContainsValue (TValue value)
498 return IndexOfValue (value) >= 0;
501 public void TrimExcess ()
503 if (inUse < table.Length * 0.9)
507 public bool TryGetValue (TKey key, out TValue value)
510 throw new ArgumentNullException("key");
515 value = table [i].Value;
519 value = default (TValue);
528 private void EnsureCapacity (int n, int free)
530 KeyValuePair<TKey, TValue> [] table = this.table;
531 KeyValuePair<TKey, TValue> [] newTable = null;
533 bool gap = (free >=0 && free < Count);
536 newTable = new KeyValuePair<TKey, TValue> [n << 1];
539 if (newTable != null) {
543 Array.Copy (table, 0, newTable, 0, copyLen);
545 copyLen = Count - free;
547 Array.Copy (table, free, newTable, free+1, copyLen);
550 // Just a resizing, copy the entire table.
551 Array.Copy (table, newTable, Count);
553 this.table = newTable;
555 Array.Copy (table, free, table, free+1, Count - free);
559 private void PutImpl (TKey key, TValue value, bool overwrite)
562 throw new ArgumentNullException ("null key");
564 KeyValuePair<TKey, TValue> [] table = this.table;
569 freeIndx = Find (key);
570 } catch (Exception) {
571 throw new InvalidOperationException();
576 throw new ArgumentException("element already exists");
578 table [freeIndx] = new KeyValuePair <TKey, TValue> (key, value);
583 freeIndx = ~freeIndx;
585 if (freeIndx > Capacity + 1)
586 throw new Exception ("SortedList::internal error ("+key+", "+value+") at ["+freeIndx+"]");
589 EnsureCapacity (Count+1, freeIndx);
592 table [freeIndx] = new KeyValuePair <TKey, TValue> (key, value);
599 private void Init (IComparer<TKey> comparer, int capacity, bool forceSize)
601 if (comparer == null)
602 comparer = Comparer<TKey>.Default;
603 this.comparer = comparer;
604 if (!forceSize && (capacity < defaultCapacity))
605 capacity = defaultCapacity;
606 this.table = new KeyValuePair<TKey, TValue> [capacity];
608 this.modificationCount = 0;
611 private void CopyToArray (Array arr, int i,
615 throw new ArgumentNullException ("arr");
617 if (i < 0 || i + this.Count > arr.Length)
618 throw new ArgumentOutOfRangeException ("i");
620 IEnumerator it = new Enumerator (this, mode);
622 while (it.MoveNext ()) {
623 arr.SetValue (it.Current, i++);
627 private int Find (TKey key)
629 KeyValuePair<TKey, TValue> [] table = this.table;
632 if (len == 0) return ~0;
637 while (left <= right) {
638 int guess = (left + right) >> 1;
640 int cmp = comparer.Compare (key, table[guess].Key);
641 if (cmp == 0) return guess;
643 if (cmp > 0) left = guess+1;
644 else right = guess-1;
650 private TKey ToKey (object key) {
652 throw new ArgumentNullException ("key");
654 throw new ArgumentException ("The value \"" + key + "\" isn't of type \"" + typeof (TKey) + "\" and can't be used in this generic collection.", "key");
658 private TValue ToValue (object value) {
659 if (!(value is TValue))
660 throw new ArgumentException ("The value \"" + value + "\" isn't of type \"" + typeof (TValue) + "\" and can't be used in this generic collection.", "value");
661 return (TValue)value;
664 internal TKey KeyAt (int index) {
665 if (index >= 0 && index < Count)
666 return table [index].Key;
668 throw new ArgumentOutOfRangeException("Index out of range");
671 internal TValue ValueAt (int index) {
672 if (index >= 0 && index < Count)
673 return table [index].Value;
675 throw new ArgumentOutOfRangeException("Index out of range");
683 private sealed class Enumerator : ICloneable, IDictionaryEnumerator, IEnumerator {
685 private SortedList<TKey, TValue>host;
689 private EnumeratorMode mode;
691 private object currentKey;
692 private object currentValue;
694 bool invalid = false;
696 private readonly static string xstr = "SortedList.Enumerator: snapshot out of sync.";
698 public Enumerator (SortedList<TKey, TValue>host, EnumeratorMode mode)
701 stamp = host.modificationCount;
707 public Enumerator (SortedList<TKey, TValue>host)
708 : this (host, EnumeratorMode.ENTRY_MODE)
714 if (host.modificationCount != stamp || invalid)
715 throw new InvalidOperationException (xstr);
722 public bool MoveNext ()
724 if (host.modificationCount != stamp || invalid)
725 throw new InvalidOperationException (xstr);
727 KeyValuePair<TKey, TValue> [] table = host.table;
730 KeyValuePair<TKey, TValue> entry = table [pos];
732 currentKey = entry.Key;
733 currentValue = entry.Value;
742 public DictionaryEntry Entry
745 if (invalid || pos >= size || pos == -1)
746 throw new InvalidOperationException (xstr);
748 return new DictionaryEntry (currentKey,
755 if (invalid || pos >= size || pos == -1)
756 throw new InvalidOperationException (xstr);
761 public Object Value {
763 if (invalid || pos >= size || pos == -1)
764 throw new InvalidOperationException (xstr);
769 public Object Current {
771 if (invalid || pos >= size || pos == -1)
772 throw new InvalidOperationException (xstr);
775 case EnumeratorMode.KEY_MODE:
777 case EnumeratorMode.VALUE_MODE:
779 case EnumeratorMode.ENTRY_MODE:
783 throw new NotSupportedException (mode + " is not a supported mode.");
790 public object Clone ()
792 Enumerator e = new Enumerator (host, mode);
796 e.currentKey = currentKey;
797 e.currentValue = currentValue;
804 private class ListKeys : IList<TKey>, ICollection, IEnumerable {
806 private SortedList<TKey, TValue> host;
808 public ListKeys (SortedList<TKey, TValue> host)
811 throw new ArgumentNullException ();
818 public virtual void Add (TKey item) {
819 throw new NotSupportedException();
822 public virtual bool Remove (TKey key) {
823 throw new NotSupportedException ();
826 public virtual void Clear () {
827 throw new NotSupportedException();
830 public virtual void CopyTo (TKey[] array, int arrayIndex) {
832 throw new ArgumentNullException ("array");
834 throw new ArgumentOutOfRangeException();
835 if (arrayIndex >= array.Length)
836 throw new ArgumentOutOfRangeException ("arrayIndex is greater than or equal to array.Length");
837 if (Count > (array.Length - arrayIndex))
838 throw new ArgumentOutOfRangeException("Not enough space in array from arrayIndex to end of array");
841 for (int i = 0; i < Count; ++i)
842 array [j ++] = host.KeyAt (i);
845 public virtual bool Contains (TKey item) {
846 return host.IndexOfKey (item) > -1;
852 public virtual int IndexOf (TKey item) {
853 return host.IndexOfKey (item);
856 public virtual void Insert (int index, TKey item) {
857 throw new NotSupportedException ();
860 public virtual void RemoveAt (int index) {
861 throw new NotSupportedException ();
864 public virtual TKey this [int index] {
866 return host.KeyAt (index);
869 throw new NotSupportedException("attempt to modify a key");
877 public virtual IEnumerator<TKey> GetEnumerator ()
879 for (int i = 0; i < host.Count; ++i)
880 yield return host.KeyAt (i);
887 public virtual int Count {
893 public virtual bool IsSynchronized {
895 return ((ICollection)host).IsSynchronized;
899 public virtual bool IsReadOnly {
905 public virtual Object SyncRoot {
907 return ((ICollection)host).SyncRoot;
911 public virtual void CopyTo (Array array, int arrayIndex)
913 host.CopyToArray (array, arrayIndex, EnumeratorMode.KEY_MODE);
920 IEnumerator IEnumerable.GetEnumerator ()
922 for (int i = 0; i < host.Count; ++i)
923 yield return host.KeyAt (i);
927 private class ListValues : IList<TValue>, ICollection, IEnumerable {
929 private SortedList<TKey, TValue>host;
931 public ListValues (SortedList<TKey, TValue>host)
934 throw new ArgumentNullException ();
939 // ICollection<TValue>
941 public virtual void Add (TValue item) {
942 throw new NotSupportedException();
945 public virtual bool Remove (TValue value) {
946 throw new NotSupportedException ();
949 public virtual void Clear () {
950 throw new NotSupportedException();
953 public virtual void CopyTo (TValue[] array, int arrayIndex) {
955 throw new ArgumentNullException ("array");
957 throw new ArgumentOutOfRangeException();
958 if (arrayIndex >= array.Length)
959 throw new ArgumentOutOfRangeException ("arrayIndex is greater than or equal to array.Length");
960 if (Count > (array.Length - arrayIndex))
961 throw new ArgumentOutOfRangeException("Not enough space in array from arrayIndex to end of array");
964 for (int i = 0; i < Count; ++i)
965 array [j ++] = host.ValueAt (i);
968 public virtual bool Contains (TValue item) {
969 return host.IndexOfValue (item) > -1;
975 public virtual int IndexOf (TValue item) {
976 return host.IndexOfValue (item);
979 public virtual void Insert (int index, TValue item) {
980 throw new NotSupportedException ();
983 public virtual void RemoveAt (int index) {
984 throw new NotSupportedException ();
987 public virtual TValue this [int index] {
989 return host.ValueAt (index);
992 throw new NotSupportedException("attempt to modify a key");
997 // IEnumerable<TValue>
1000 public virtual IEnumerator<TValue> GetEnumerator ()
1002 for (int i = 0; i < host.Count; ++i)
1003 yield return host.ValueAt (i);
1010 public virtual int Count {
1016 public virtual bool IsSynchronized {
1018 return ((ICollection)host).IsSynchronized;
1022 public virtual bool IsReadOnly {
1028 public virtual Object SyncRoot {
1030 return ((ICollection)host).SyncRoot;
1034 public virtual void CopyTo (Array array, int arrayIndex)
1036 host.CopyToArray (array, arrayIndex, EnumeratorMode.VALUE_MODE);
1043 IEnumerator IEnumerable.GetEnumerator ()
1045 for (int i = 0; i < host.Count; ++i)
1046 yield return host.ValueAt (i);
1052 } // System.Collections.Generic