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);
117 public virtual int Count {
123 bool ICollection.IsSynchronized {
129 Object ICollection.SyncRoot {
137 bool IDictionary.IsFixedSize {
143 bool IDictionary.IsReadOnly {
149 public virtual 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 // IDictionary<TKey, TValue>
273 public virtual void Add (TKey key, TValue value)
276 throw new ArgumentNullException ("key");
278 PutImpl (key, value, false);
281 public bool ContainsKey (TKey key)
284 throw new ArgumentNullException ("key");
286 return (Find (key) >= 0);
289 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
291 for (int i = 0; i < inUse; i ++) {
292 KeyValuePair<TKey, TValue> current = this.table [i];
294 yield return new KeyValuePair<TKey, TValue> (current.Key, current.Value);
298 public virtual bool Remove (TKey key)
301 throw new ArgumentNullException ("key");
303 int i = IndexOfKey (key);
312 // ICollection<KeyValuePair<TKey, TValue>>
314 public virtual void Clear ()
316 defaultCapacity = INITIAL_SIZE;
317 this.table = new KeyValuePair<TKey, TValue> [defaultCapacity];
322 void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)
325 throw new ArgumentNullException();
328 throw new ArgumentOutOfRangeException();
330 if (arrayIndex >= array.Length)
331 throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
332 if (Count > (array.Length - arrayIndex))
333 throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
336 foreach (KeyValuePair<TKey, TValue> pair in this)
340 void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> keyValuePair) {
341 Add (keyValuePair.Key, keyValuePair.Value);
344 bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> keyValuePair) {
345 int i = Find (keyValuePair.Key);
348 return Comparer<KeyValuePair<TKey, TValue>>.Default.Compare (table [i], keyValuePair) == 0;
353 bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> keyValuePair) {
354 int i = Find (keyValuePair.Key);
356 if (i >= 0 && (Comparer<KeyValuePair<TKey, TValue>>.Default.Compare (table [i], keyValuePair) == 0)) {
364 // IEnumerable<KeyValuePair<TKey, TValue>>
366 IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator ()
368 for (int i = 0; i < inUse; i ++) {
369 KeyValuePair<TKey, TValue> current = this.table [i];
371 yield return new KeyValuePair<TKey, TValue> (current.Key, current.Value);
377 IEnumerator IEnumerable.GetEnumerator ()
379 return GetEnumerator ();
384 void IDictionary.Add (object key, object value)
386 PutImpl (ToKey (key), ToValue (value), false);
389 bool IDictionary.Contains (object key)
392 throw new ArgumentNullException();
396 return (Find ((TKey)key) >= 0);
399 IDictionaryEnumerator IDictionary.GetEnumerator ()
401 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
404 void IDictionary.Remove (object key)
407 throw new ArgumentNullException ("key");
410 int i = IndexOfKey ((TKey)key);
411 if (i >= 0) RemoveAt (i);
416 void ICollection.CopyTo (Array array, int arrayIndex)
419 throw new ArgumentNullException();
422 throw new ArgumentOutOfRangeException();
425 throw new ArgumentException("array is multi-dimensional");
426 if (arrayIndex >= array.Length)
427 throw new ArgumentNullException("arrayIndex is greater than or equal to array.Length");
428 if (Count > (array.Length - arrayIndex))
429 throw new ArgumentNullException("Not enough space in array from arrayIndex to end of array");
431 IEnumerator<KeyValuePair<TKey,TValue>> it = GetEnumerator ();
434 while (it.MoveNext ()) {
435 array.SetValue (it.Current, i++);
440 // SortedList<TKey, TValue>
443 public void RemoveAt (int index)
445 KeyValuePair<TKey, TValue> [] table = this.table;
447 if (index >= 0 && index < cnt) {
448 if (index != cnt - 1) {
449 Array.Copy (table, index+1, table, index, cnt-1-index);
451 table [index] = default (KeyValuePair <TKey, TValue>);
456 throw new ArgumentOutOfRangeException("index out of range");
460 public int IndexOfKey (TKey key)
463 throw new ArgumentNullException ("key");
468 } catch (Exception) {
469 throw new InvalidOperationException();
472 return (indx | (indx >> 31));
475 public int IndexOfValue (TValue value)
480 for (int i = 0; i < inUse; i ++) {
481 KeyValuePair<TKey, TValue> current = this.table [i];
483 if (Equals (value, current.Value))
490 public bool ContainsValue (TValue value)
492 return IndexOfValue (value) >= 0;
495 public void TrimExcess ()
497 if (inUse < table.Length * 0.9)
501 public bool TryGetValue (TKey key, out TValue value)
504 throw new ArgumentNullException("key");
509 value = table [i].Value;
513 value = default (TValue);
522 private void EnsureCapacity (int n, int free)
524 KeyValuePair<TKey, TValue> [] table = this.table;
525 KeyValuePair<TKey, TValue> [] newTable = null;
527 bool gap = (free >=0 && free < Count);
530 newTable = new KeyValuePair<TKey, TValue> [n << 1];
533 if (newTable != null) {
537 Array.Copy (table, 0, newTable, 0, copyLen);
539 copyLen = Count - free;
541 Array.Copy (table, free, newTable, free+1, copyLen);
544 // Just a resizing, copy the entire table.
545 Array.Copy (table, newTable, Count);
547 this.table = newTable;
549 Array.Copy (table, free, table, free+1, Count - free);
553 private void PutImpl (TKey key, TValue value, bool overwrite)
556 throw new ArgumentNullException ("null key");
558 KeyValuePair<TKey, TValue> [] table = this.table;
563 freeIndx = Find (key);
564 } catch (Exception) {
565 throw new InvalidOperationException();
570 throw new ArgumentException("element already exists");
572 table [freeIndx] = new KeyValuePair <TKey, TValue> (key, value);
577 freeIndx = ~freeIndx;
579 if (freeIndx > Capacity + 1)
580 throw new Exception ("SortedList::internal error ("+key+", "+value+") at ["+freeIndx+"]");
583 EnsureCapacity (Count+1, freeIndx);
586 table [freeIndx] = new KeyValuePair <TKey, TValue> (key, value);
593 private void Init (IComparer<TKey> comparer, int capacity, bool forceSize)
595 if (comparer == null)
596 comparer = Comparer<TKey>.Default;
597 this.comparer = comparer;
598 if (!forceSize && (capacity < defaultCapacity))
599 capacity = defaultCapacity;
600 this.table = new KeyValuePair<TKey, TValue> [capacity];
602 this.modificationCount = 0;
605 private void CopyToArray (Array arr, int i,
609 throw new ArgumentNullException ("arr");
611 if (i < 0 || i + this.Count > arr.Length)
612 throw new ArgumentOutOfRangeException ("i");
614 IEnumerator it = new Enumerator (this, mode);
616 while (it.MoveNext ()) {
617 arr.SetValue (it.Current, i++);
621 private int Find (TKey key)
623 KeyValuePair<TKey, TValue> [] table = this.table;
626 if (len == 0) return ~0;
631 while (left <= right) {
632 int guess = (left + right) >> 1;
634 int cmp = comparer.Compare (key, table[guess].Key);
635 if (cmp == 0) return guess;
637 if (cmp > 0) left = guess+1;
638 else right = guess-1;
644 private TKey ToKey (object key) {
646 throw new ArgumentNullException ("key");
648 throw new ArgumentException ("The value \"" + key + "\" isn't of type \"" + typeof (TKey) + "\" and can't be used in this generic collection.", "key");
652 private TValue ToValue (object value) {
653 if (!(value is TValue))
654 throw new ArgumentException ("The value \"" + value + "\" isn't of type \"" + typeof (TValue) + "\" and can't be used in this generic collection.", "value");
655 return (TValue)value;
658 internal TKey KeyAt (int index) {
659 if (index >= 0 && index < Count)
660 return table [index].Key;
662 throw new ArgumentOutOfRangeException("Index out of range");
665 internal TValue ValueAt (int index) {
666 if (index >= 0 && index < Count)
667 return table [index].Value;
669 throw new ArgumentOutOfRangeException("Index out of range");
677 private sealed class Enumerator : ICloneable, IDictionaryEnumerator, IEnumerator {
679 private SortedList<TKey, TValue>host;
683 private EnumeratorMode mode;
685 private object currentKey;
686 private object currentValue;
688 bool invalid = false;
690 private readonly static string xstr = "SortedList.Enumerator: snapshot out of sync.";
692 public Enumerator (SortedList<TKey, TValue>host, EnumeratorMode mode)
695 stamp = host.modificationCount;
701 public Enumerator (SortedList<TKey, TValue>host)
702 : this (host, EnumeratorMode.ENTRY_MODE)
708 if (host.modificationCount != stamp || invalid)
709 throw new InvalidOperationException (xstr);
716 public bool MoveNext ()
718 if (host.modificationCount != stamp || invalid)
719 throw new InvalidOperationException (xstr);
721 KeyValuePair<TKey, TValue> [] table = host.table;
724 KeyValuePair<TKey, TValue> entry = table [pos];
726 currentKey = entry.Key;
727 currentValue = entry.Value;
736 public DictionaryEntry Entry
739 if (invalid || pos >= size || pos == -1)
740 throw new InvalidOperationException (xstr);
742 return new DictionaryEntry (currentKey,
749 if (invalid || pos >= size || pos == -1)
750 throw new InvalidOperationException (xstr);
755 public Object Value {
757 if (invalid || pos >= size || pos == -1)
758 throw new InvalidOperationException (xstr);
763 public Object Current {
765 if (invalid || pos >= size || pos == -1)
766 throw new InvalidOperationException (xstr);
769 case EnumeratorMode.KEY_MODE:
771 case EnumeratorMode.VALUE_MODE:
773 case EnumeratorMode.ENTRY_MODE:
777 throw new NotSupportedException (mode + " is not a supported mode.");
784 public object Clone ()
786 Enumerator e = new Enumerator (host, mode);
790 e.currentKey = currentKey;
791 e.currentValue = currentValue;
798 private class ListKeys : IList<TKey>, ICollection, IEnumerable {
800 private SortedList<TKey, TValue> host;
802 public ListKeys (SortedList<TKey, TValue> host)
805 throw new ArgumentNullException ();
812 public virtual void Add (TKey item) {
813 throw new NotSupportedException();
816 public virtual bool Remove (TKey key) {
817 throw new NotSupportedException ();
820 public virtual void Clear () {
821 throw new NotSupportedException();
824 public virtual void CopyTo (TKey[] array, int arrayIndex) {
826 throw new ArgumentNullException ("array");
828 throw new ArgumentOutOfRangeException();
829 if (arrayIndex >= array.Length)
830 throw new ArgumentOutOfRangeException ("arrayIndex is greater than or equal to array.Length");
831 if (Count > (array.Length - arrayIndex))
832 throw new ArgumentOutOfRangeException("Not enough space in array from arrayIndex to end of array");
835 for (int i = 0; i < Count; ++i)
836 array [j ++] = host.KeyAt (i);
839 public virtual bool Contains (TKey item) {
840 return host.IndexOfKey (item) > -1;
846 public virtual int IndexOf (TKey item) {
847 return host.IndexOfKey (item);
850 public virtual void Insert (int index, TKey item) {
851 throw new NotSupportedException ();
854 public virtual void RemoveAt (int index) {
855 throw new NotSupportedException ();
858 public virtual TKey this [int index] {
860 return host.KeyAt (index);
863 throw new NotSupportedException("attempt to modify a key");
871 public virtual IEnumerator<TKey> GetEnumerator ()
873 for (int i = 0; i < host.Count; ++i)
874 yield return host.KeyAt (i);
881 public virtual int Count {
887 public virtual bool IsSynchronized {
889 return ((ICollection)host).IsSynchronized;
893 public virtual bool IsReadOnly {
899 public virtual Object SyncRoot {
901 return ((ICollection)host).SyncRoot;
905 public virtual void CopyTo (Array array, int arrayIndex)
907 host.CopyToArray (array, arrayIndex, EnumeratorMode.KEY_MODE);
914 IEnumerator IEnumerable.GetEnumerator ()
916 for (int i = 0; i < host.Count; ++i)
917 yield return host.KeyAt (i);
921 private class ListValues : IList<TValue>, ICollection, IEnumerable {
923 private SortedList<TKey, TValue>host;
925 public ListValues (SortedList<TKey, TValue>host)
928 throw new ArgumentNullException ();
933 // ICollection<TValue>
935 public virtual void Add (TValue item) {
936 throw new NotSupportedException();
939 public virtual bool Remove (TValue value) {
940 throw new NotSupportedException ();
943 public virtual void Clear () {
944 throw new NotSupportedException();
947 public virtual void CopyTo (TValue[] array, int arrayIndex) {
949 throw new ArgumentNullException ("array");
951 throw new ArgumentOutOfRangeException();
952 if (arrayIndex >= array.Length)
953 throw new ArgumentOutOfRangeException ("arrayIndex is greater than or equal to array.Length");
954 if (Count > (array.Length - arrayIndex))
955 throw new ArgumentOutOfRangeException("Not enough space in array from arrayIndex to end of array");
958 for (int i = 0; i < Count; ++i)
959 array [j ++] = host.ValueAt (i);
962 public virtual bool Contains (TValue item) {
963 return host.IndexOfValue (item) > -1;
969 public virtual int IndexOf (TValue item) {
970 return host.IndexOfValue (item);
973 public virtual void Insert (int index, TValue item) {
974 throw new NotSupportedException ();
977 public virtual void RemoveAt (int index) {
978 throw new NotSupportedException ();
981 public virtual TValue this [int index] {
983 return host.ValueAt (index);
986 throw new NotSupportedException("attempt to modify a key");
991 // IEnumerable<TValue>
994 public virtual IEnumerator<TValue> GetEnumerator ()
996 for (int i = 0; i < host.Count; ++i)
997 yield return host.ValueAt (i);
1004 public virtual int Count {
1010 public virtual bool IsSynchronized {
1012 return ((ICollection)host).IsSynchronized;
1016 public virtual bool IsReadOnly {
1022 public virtual Object SyncRoot {
1024 return ((ICollection)host).SyncRoot;
1028 public virtual void CopyTo (Array array, int arrayIndex)
1030 host.CopyToArray (array, arrayIndex, EnumeratorMode.VALUE_MODE);
1037 IEnumerator IEnumerable.GetEnumerator ()
1039 for (int i = 0; i < host.Count; ++i)
1040 yield return host.ValueAt (i);
1046 } // System.Collections.Generic