5 // Jb Evain <jbevain@novell.com>
7 // Copyright (C) 2010 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Collections;
31 using System.Collections.Generic;
33 using System.Runtime.Serialization;
34 using System.Runtime.InteropServices;
35 using System.Security;
36 using System.Security.Permissions;
37 using System.Diagnostics;
39 // SortedSet is basically implemented as a reduction of SortedDictionary<K, V>
43 namespace System.Collections.Generic {
46 [DebuggerDisplay ("Count={Count}")]
47 [DebuggerTypeProxy (typeof (CollectionDebuggerView))]
48 public class SortedSet<T> : ISet<T>, ICollection, ISerializable, IDeserializationCallback
50 class Node : RBTree.Node {
59 public override void SwapValue (RBTree.Node other)
68 class NodeHelper : RBTree.INodeHelper<T> {
70 static NodeHelper Default = new NodeHelper (Comparer<T>.Default);
72 public IComparer<T> comparer;
74 public int Compare (T item, RBTree.Node node)
76 return comparer.Compare (item, ((Node) node).item);
79 public RBTree.Node CreateNode (T item)
81 return new Node (item);
84 NodeHelper (IComparer<T> comparer)
86 this.comparer = comparer;
89 public static NodeHelper GetHelper (IComparer<T> comparer)
91 if (comparer == null || comparer == Comparer<T>.Default)
94 return new NodeHelper (comparer);
100 SerializationInfo si;
103 : this (Comparer<T>.Default)
107 public SortedSet (IEnumerable<T> collection)
108 : this (collection, Comparer<T>.Default)
112 public SortedSet (IEnumerable<T> collection, IComparer<T> comparer)
115 if (collection == null)
116 throw new ArgumentNullException ("collection");
118 foreach (var item in collection)
122 public SortedSet (IComparer<T> comparer)
124 this.helper = NodeHelper.GetHelper (comparer);
125 this.tree = new RBTree (this.helper);
128 protected SortedSet (SerializationInfo info, StreamingContext context)
133 public IComparer<T> Comparer {
134 get { return helper.comparer; }
138 get { return GetCount (); }
142 get { return GetMax (); }
146 get { return GetMin (); }
149 internal virtual T GetMax ()
154 return GetItem (tree.Count - 1);
157 internal virtual T GetMin ()
165 internal virtual int GetCount ()
170 T GetItem (int index)
172 return ((Node) tree [index]).item;
175 public bool Add (T item)
177 return TryAdd (item);
180 internal virtual bool TryAdd (T item)
182 var node = new Node (item);
183 return tree.Intern (item, node) == node;
186 public virtual void Clear ()
191 public virtual bool Contains (T item)
193 return tree.Lookup (item) != null;
196 public void CopyTo (T [] array)
198 CopyTo (array, 0, Count);
201 public void CopyTo (T [] array, int index)
203 CopyTo (array, index, Count);
206 public void CopyTo (T [] array, int index, int count)
209 throw new ArgumentNullException ("array");
211 throw new ArgumentOutOfRangeException ("index");
212 if (index > array.Length)
213 throw new ArgumentException ("index larger than largest valid index of array");
214 if (array.Length - index < count)
215 throw new ArgumentException ("destination array cannot hold the requested elements");
217 foreach (Node node in tree) {
221 array [index++] = node.item;
225 public bool Remove (T item)
227 return TryRemove (item);
230 internal virtual bool TryRemove (T item)
232 return tree.Remove (item) != null;
235 public int RemoveWhere (Predicate<T> match)
237 var array = ToArray ();
240 foreach (var item in array) {
251 public IEnumerable<T> Reverse ()
253 for (int i = tree.Count - 1; i >= 0; i--)
254 yield return GetItem (i);
259 var array = new T [this.Count];
264 public Enumerator GetEnumerator ()
266 return new Enumerator (this);
269 IEnumerator<T> IEnumerable<T>.GetEnumerator ()
271 return new Enumerator (this);
274 IEnumerator IEnumerable.GetEnumerator ()
276 return new Enumerator (this);
279 public static IEqualityComparer<SortedSet<T>> CreateSetComparer ()
281 return CreateSetComparer (EqualityComparer<T>.Default);
285 public static IEqualityComparer<SortedSet<T>> CreateSetComparer (IEqualityComparer<T> memberEqualityComparer)
287 throw new NotImplementedException ();
291 protected virtual void GetObjectData (SerializationInfo info, StreamingContext context)
293 throw new NotImplementedException ();
296 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
298 GetObjectData (info, context);
302 protected virtual void OnDeserialization (object sender)
307 throw new NotImplementedException ();
310 void IDeserializationCallback.OnDeserialization (object sender)
312 OnDeserialization (sender);
315 [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
316 public void ExceptWith (IEnumerable<T> other)
318 CheckArgumentNotNull (other, "other");
319 foreach (T item in other)
323 public virtual SortedSet<T> GetViewBetween (T lowerValue, T upperValue)
325 if (Comparer.Compare (lowerValue, upperValue) > 0)
326 throw new ArgumentException ("The lowerValue is bigger than upperValue");
328 return new SortedSubSet (this, lowerValue, upperValue);
331 [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
332 public virtual void IntersectWith (IEnumerable<T> other)
334 CheckArgumentNotNull (other, "other");
336 RBTree newtree = new RBTree (helper);
337 foreach (T item in other) {
338 var node = tree.Remove (item);
340 newtree.Intern (item, node);
345 public bool IsProperSubsetOf (IEnumerable<T> other)
347 CheckArgumentNotNull (other, "other");
350 foreach (T item in other)
351 return true; // this idiom means: if 'other' is non-empty, return true
355 return is_subset_of (other, true);
358 public bool IsProperSupersetOf (IEnumerable<T> other)
360 CheckArgumentNotNull (other, "other");
365 return is_superset_of (other, true);
368 public bool IsSubsetOf (IEnumerable<T> other)
370 CheckArgumentNotNull (other, "other");
375 return is_subset_of (other, false);
378 public bool IsSupersetOf (IEnumerable<T> other)
380 CheckArgumentNotNull (other, "other");
383 foreach (T item in other)
384 return false; // this idiom means: if 'other' is non-empty, return false
388 return is_superset_of (other, false);
391 // Precondition: Count != 0, other != null
392 bool is_subset_of (IEnumerable<T> other, bool proper)
394 SortedSet<T> that = nodups (other);
396 if (Count > that.Count)
398 // Count != 0 && Count <= that.Count => that.Count != 0
399 if (proper && Count == that.Count)
401 return that.covers (this);
404 // Precondition: Count != 0, other != null
405 bool is_superset_of (IEnumerable<T> other, bool proper)
407 SortedSet<T> that = nodups (other);
411 if (Count < that.Count)
413 if (proper && Count == that.Count)
415 return this.covers (that);
418 public bool Overlaps (IEnumerable<T> other)
420 CheckArgumentNotNull (other, "other");
425 // Don't use 'nodups' here. Only optimize the SortedSet<T> case
426 SortedSet<T> that = other as SortedSet<T>;
427 if (that != null && that.Comparer != Comparer)
431 return that.Count != 0 && overlaps (that);
433 foreach (T item in other)
439 public bool SetEquals (IEnumerable<T> other)
441 CheckArgumentNotNull (other, "other");
444 foreach (T item in other)
449 SortedSet<T> that = nodups (other);
451 if (Count != that.Count)
454 using (var t = that.GetEnumerator ()) {
455 foreach (T item in this) {
457 throw new SystemException ("count wrong somewhere: this longer than that");
458 if (Comparer.Compare (item, t.Current) != 0)
462 throw new SystemException ("count wrong somewhere: this shorter than that");
467 SortedSet<T> nodups (IEnumerable<T> other)
469 SortedSet<T> that = other as SortedSet<T>;
470 if (that != null && that.Comparer == Comparer)
472 return new SortedSet<T> (other, Comparer);
475 bool covers (SortedSet<T> that)
477 using (var t = that.GetEnumerator ()) {
480 foreach (T item in this) {
481 int cmp = Comparer.Compare (item, t.Current);
484 if (cmp == 0 && !t.MoveNext ())
491 bool overlaps (SortedSet<T> that)
493 using (var t = that.GetEnumerator ()) {
496 foreach (T item in this) {
498 while ((cmp = Comparer.Compare (item, t.Current)) > 0) {
509 [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
510 public void SymmetricExceptWith (IEnumerable<T> other)
512 SortedSet<T> that_minus_this = new SortedSet<T> (Comparer);
514 // compute this - that and that - this in parallel
515 foreach (T item in nodups (other))
517 that_minus_this.Add (item);
519 UnionWith (that_minus_this);
522 [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
523 public void UnionWith (IEnumerable<T> other)
525 CheckArgumentNotNull (other, "other");
527 foreach (T item in other)
531 static void CheckArgumentNotNull (object arg, string name)
534 throw new ArgumentNullException (name);
537 void ICollection<T>.Add (T item)
542 void ICollection<T>.CopyTo (T [] array, int index)
544 CopyTo (array, index, Count);
547 bool ICollection<T>.IsReadOnly {
548 get { return false; }
551 void ICollection.CopyTo (Array array, int index)
556 throw new ArgumentNullException ("array");
557 if (index < 0 || array.Length <= index)
558 throw new ArgumentOutOfRangeException ("index");
559 if (array.Length - index < Count)
560 throw new ArgumentException ();
562 foreach (Node node in tree)
563 array.SetValue (node.item, index++);
566 bool ICollection.IsSynchronized {
567 get { return false; }
570 // TODO:Is this correct? If this is wrong,please fix.
571 object ICollection.SyncRoot {
576 public struct Enumerator : IEnumerator<T>, IDisposable {
578 RBTree.NodeEnumerator host;
582 internal Enumerator (SortedSet<T> set)
584 host = set.tree.GetEnumerator ();
585 current = default (T);
589 get { return current; }
592 object IEnumerator.Current {
594 host.check_current ();
595 return ((Node) host.Current).item;
599 public bool MoveNext ()
601 if (!host.MoveNext ())
604 current = ((Node) host.Current).item;
608 public void Dispose ()
613 void IEnumerator.Reset ()
620 sealed class SortedSubSet : SortedSet<T>, IEnumerable<T>, IEnumerable {
626 public SortedSubSet (SortedSet<T> set, T lower, T upper)
627 : base (set.Comparer)
634 internal override T GetMin ()
636 for (int i = 0; i < set.tree.Count; i++) {
637 var item = set.GetItem (i);
645 internal override T GetMax ()
647 for (int i = set.tree.Count - 1; i >= 0; i--) {
648 var item = set.GetItem (i);
656 internal override int GetCount ()
659 for (int i = 0; i < set.tree.Count; i++) {
660 var item = set.GetItem (i);
670 internal override bool TryAdd (T item)
673 throw new ArgumentOutOfRangeException ("item");
675 return set.TryAdd (item);
678 internal override bool TryRemove (T item)
683 return set.TryRemove (item);
686 public override bool Contains (T item)
691 return set.Contains (item);
694 public override void Clear ()
696 set.RemoveWhere (InRange);
699 bool InRange (T item)
701 return Comparer.Compare (item, lower) >= 0
702 && Comparer.Compare (item, upper) <= 0;
705 public override SortedSet<T> GetViewBetween (T lowerValue, T upperValue)
707 if (Comparer.Compare (lowerValue, upperValue) > 0)
708 throw new ArgumentException ("The lowerValue is bigger than upperValue");
709 if (!InRange (lowerValue))
710 throw new ArgumentOutOfRangeException ("lowerValue");
711 if (!InRange (upperValue))
712 throw new ArgumentOutOfRangeException ("upperValue");
714 return new SortedSubSet (set, lowerValue, upperValue);
717 public IEnumerator<T> GetEnumerator ()
719 var yielding = false;
721 foreach (Node node in set.tree) {
722 var item = node.item;
724 if (InRange (item)) {
732 IEnumerator<T> IEnumerable<T>.GetEnumerator ()
734 return GetEnumerator ();
737 IEnumerator IEnumerable.GetEnumerator ()
739 return GetEnumerator ();
742 public override void IntersectWith (IEnumerable<T> other)
744 CheckArgumentNotNull (other, "other");
746 var slice = new SortedSet<T> (this);
747 slice.IntersectWith (other);
750 set.UnionWith (slice);