3 * Copyright (C) 2009-2011 Maciej Piechotka
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 * Maciej Piechotka <uzytkownik2@gmail.com>
26 * Left-leaning red-black tree implementation of the {@link Set} interface.
28 * This implementation is especially well designed for large quantity of
29 * data. The (balanced) tree implementation insure that the set and get
30 * methods are in logarithmic complexity. For a linear implementation see
35 public class Gee.TreeSet<G> : AbstractBidirSortedSet<G> {
39 public override int size {
46 public override bool read_only {
51 * The elements' comparator function.
53 [CCode (notify = false)]
54 public CompareDataFunc<G> compare_func { private set; get; }
56 private int _size = 0;
59 * Constructs a new, empty tree set sorted according to the specified
60 * comparator function.
62 * If not provided, the function parameter is requested to the
63 * {@link Functions} function factory methods.
65 * @param compare_func an optional element comparator function
67 public TreeSet (owned CompareDataFunc<G>? compare_func = null) {
68 if (compare_func == null) {
69 compare_func = Functions.get_compare_func_for (typeof (G));
71 this.compare_func = compare_func;
81 public override bool contains (G item) {
82 weak Node<G>? cur = root;
84 int res = compare_func (item, cur.key);
96 private inline void rotate_right (ref Node<G> root) {
97 Node<G> pivot = (owned) root.left;
98 pivot.color = root.color;
99 root.color = Node.Color.RED;
100 root.left = (owned) pivot.right;
101 pivot.right = (owned) root;
102 root = (owned) pivot;
104 stdout.printf (dump ("after rotate right on %s".printf ((string)root.right.key)));
108 private inline void rotate_left (ref Node<G> root) {
109 Node<G> pivot = (owned) root.right;
110 pivot.color = root.color;
111 root.color = Node.Color.RED;
112 root.right = (owned) pivot.left;
113 pivot.left = (owned) root;
114 root = (owned) pivot;
116 stdout.printf (dump ("after rotate left on %s".printf ((string)root.left.key)));
120 private inline bool is_red (Node<G>? n) {
121 return n != null && n.color == Node.Color.RED;
124 private inline bool is_black (Node<G>? n) {
125 return n == null || n.color == Node.Color.BLACK;
128 private inline void fix_up (ref Node<G> node) {
130 var n = (string)node.key;
132 if (is_black (node.left) && is_red (node.right)) {
133 rotate_left (ref node);
135 if (is_red (node.left) && is_red (node.left.left)) {
136 rotate_right (ref node);
138 if (is_red (node.left) && is_red (node.right)) {
142 stdout.printf (dump ("after fix up on %s".printf (n)));
146 private bool add_to_node (ref Node<G>? node, owned G item, Node<G>? prev, Node<G>? next) {
149 stdout.printf ("Adding %s to %s\n".printf ((string) item, (string) node.key));
152 node = new Node<G> ((owned) item, prev, next);
163 int cmp = compare_func (item, node.key);
167 } else if (cmp < 0) {
168 bool r = add_to_node (ref node.left, item, node.prev, node);
172 bool r = add_to_node (ref node.right, item, node, node.next);
181 * If the element already exists in the set it will not be added twice.
183 public override bool add (G item) {
184 #if CONSISTENCY_CHECKS
187 bool r = add_to_node (ref root, item, null, null);
188 root.color = Node.Color.BLACK;
189 #if CONSISTENCY_CHECKS
196 private inline void move_red_left (ref Node<G> root) {
198 var n = (string)root.key;
201 if (is_red (root.right.left)) {
202 rotate_right (ref root.right);
203 rotate_left (ref root);
207 stdout.printf (dump ("after red left on %s".printf (n)));
211 private inline void move_red_right (ref Node<G> root) {
213 var n = (string)root.key;
216 if (is_red (root.left.left)) {
217 rotate_right (ref root);
221 stdout.printf (dump ("after red right on %s".printf (n)));
225 private inline void fix_removal (ref Node<G> node, out G? key = null) {
226 Node<G> n = (owned)node;
228 if (n.prev != null) {
229 n.prev.next = n.next;
233 if (n.next != null) {
234 n.next.prev = n.prev;
242 private void remove_minimal (ref Node<G> node, out G key) {
243 if (node.left == null) {
244 fix_removal (ref node, out key);
248 if (is_black (node.left) && is_black (node.left.left)) {
249 move_red_left (ref node);
252 remove_minimal (ref node.left, out key);
257 private bool remove_from_node (ref Node<G>? node, G item, out unowned Node<G>? prev = null, out unowned Node<G>? next = null) {
259 stdout.printf ("Removing %s from %s\n", (string)item, node != null ? (string)node.key : null);
265 } else if (compare_func (item, node.key) < 0) {
266 weak Node<G> left = node.left;
272 if (is_black (left) && is_black (left.left)) {
273 move_red_left (ref node);
275 bool r = remove_from_node (ref node.left, item, out prev, out next);
279 if (is_red (node.left)) {
280 rotate_right (ref node);
283 weak Node<G>? r = node.right;
284 if (compare_func (item, node.key) == 0 && r == null) {
287 fix_removal (ref node, null);
290 if (is_black (r) && r != null && is_black (r.left)) {
291 move_red_right (ref node);
293 if (compare_func (item, node.key) == 0) {
296 remove_minimal (ref node.right, out node.key);
300 bool re = remove_from_node (ref node.right, item, out prev, out next);
310 public override bool remove (G item) {
311 #if CONSISTENCY_CHECKS
314 bool b = remove_from_node (ref root, item);
316 root.color = Node.Color.BLACK;
318 #if CONSISTENCY_CHECKS
325 private inline void clear_subtree (owned Node<G> node) {
327 if (node.left != null)
328 clear_subtree ((owned) node.left);
329 if (node.right != null)
330 clear_subtree ((owned) node.right);
336 public override void clear () {
338 clear_subtree ((owned) root);
339 _first = _last = null;
348 public override Gee.Iterator<G> iterator () {
349 return new Iterator<G> (this);
355 public override BidirIterator<G> bidir_iterator () {
356 return new Iterator<G> (this);
359 private inline G? lift_null_get (Node<G>? node) {
360 return node != null ? node.key : null;
366 public override G first () {
367 assert (_first != null);
374 public override G last () {
375 assert (_last != null);
382 public override SortedSet<G> head_set (G before) {
383 return new SubSet<G>.head (this, before);
389 public override SortedSet<G> tail_set (G after) {
390 return new SubSet<G>.tail (this, after);
396 public override SortedSet<G> sub_set (G after, G before) {
397 return new SubSet<G> (this, after, before);
400 private inline unowned Node<G>? find_node (G item) {
401 weak Node<G>? cur = root;
402 while (cur != null) {
403 int res = compare_func (item, cur.key);
406 } else if (res < 0) {
418 public override Gee.Iterator<G>? iterator_at (G item) {
419 weak Node<G>? node = find_node (item);
420 return node != null ? new Iterator<G>.pointing (this, node) : null;
423 private inline unowned Node<G>? find_nearest (G item) {
424 weak Node<G>? cur = root;
425 while (cur != null) {
426 int res = compare_func (item, cur.key);
429 } else if (res < 0) {
430 if (cur.left == null)
434 if (cur.right == null)
442 private inline unowned Node<G>? find_lower (G item) {
443 weak Node<G>? node = find_nearest (item);
446 return compare_func (item, node.key) <= 0 ? node.prev : node;
449 private inline unowned Node<G>? find_higher (G item) {
450 weak Node<G>? node = find_nearest (item);
453 return compare_func (item, node.key) >= 0 ? node.next : node;
456 private inline unowned Node<G>? find_floor (G item) {
457 weak Node<G>? node = find_nearest (item);
460 return compare_func (item, node.key) < 0 ? node.prev : node;
463 private inline unowned Node<G>? find_ceil (G item) {
464 weak Node<G>? node = find_nearest (item);
467 return compare_func (item, node.key) > 0 ? node.next : node;
473 public override G? lower (G item) {
474 return lift_null_get (find_lower (item));
480 public override G? higher (G item) {
481 return lift_null_get (find_higher (item));
487 public override G? floor (G item) {
488 return lift_null_get (find_floor (item));
494 public override G? ceil (G item) {
495 return lift_null_get (find_ceil (item));
498 #if CONSISTENCY_CHECKS
499 public inline void check () {
500 check_subtree (root);
501 assert (root == null || root.color == Node.Color.BLACK);
503 stdout.printf ("%s\n", dump ());
507 private inline uint check_subtree (Node<G>? node) {
510 assert (! (is_black (node.left) && is_red (node.right))); // Check left-leaning
511 assert (! (is_red (node) && is_red (node.left))); // Check red property
512 uint l = check_subtree (node.left);
513 uint r = check_subtree (node.right);
515 return l + (node.color == Node.Color.BLACK ? 1 : 0);
519 public string dump (string? when = null) {
520 return "TreeSet dump%s:\n%s".printf (when == null ? "" : (" " + when), dump_node (root));
523 private inline string dump_node (Node<G>? node, uint depth = 0) {
525 return dump_node (node.left, depth + 1) +
526 "%s%s%p(%s)\033[0m\n".printf (string.nfill (depth, ' '),
527 node.color == Node.Color.RED ? "\033[0;31m" : "",
528 node, (string)node.key) +
529 dump_node (node.right, depth + 1);
535 private class Node<G> {
540 public Color flip () {
549 public Node (owned G node, Node<G>? prev, Node<G>? next) {
550 this.key = (owned) node;
551 this.color = Color.RED;
562 public void flip () {
563 color = color.flip ();
565 left.color = left.color.flip ();
568 right.color = right.color.flip ();
574 public Node<G>? left;
575 public Node<G>? right;
576 public weak Node<G>? prev;
577 public weak Node<G>? next;
580 private class Iterator<G> : Object, Traversable<G>, Gee.Iterator<G>, BidirIterator<G> {
581 private TreeSet<G> _set;
583 // concurrent modification protection
586 public Iterator (TreeSet<G> set) {
591 public Iterator.pointing (TreeSet<G> set, Node<G> current) {
593 this._current = current;
594 this.stamp = set.stamp;
598 public bool next () {
599 assert (stamp == _set.stamp);
600 if (_current != null) {
601 if (_current.next != null) {
602 _current = _current.next;
607 } else if (!started) {
608 _current = _set._first;
610 return _current != null;
613 if (_current != null) {
617 return _current != null;
621 public bool has_next () {
622 assert (stamp == _set.stamp);
623 return (!started && _set._first != null) ||
624 (_current == null && _next != null) ||
625 (_current != null && _current.next != null);
628 public bool first () {
629 assert (stamp == _set.stamp);
630 _current = _set._first;
634 return _current != null; // on false it is null anyway
637 public bool previous () {
638 assert (stamp == _set.stamp);
639 if (_current != null) {
640 if (_current.prev != null) {
641 _current = _current.prev;
658 public bool has_previous () {
659 assert (stamp == _set.stamp);
660 return (_current == null && _prev != null) ||
661 (_current != null && _current.prev != null);
664 public bool last () {
665 assert (stamp == _set.stamp);
666 _current = _set._last;
670 return _current != null; // on false it is null anyway
673 public new G get () {
674 assert (stamp == _set.stamp);
675 assert (_current != null);
679 public void remove () {
680 assert (stamp == _set.stamp);
681 assert (_current != null);
682 bool success = _set.remove_from_node (ref _set.root, _current.key, out _prev, out _next);
684 if (_set.root != null)
685 _set.root.color = Node.Color.BLACK;
687 assert (stamp++ == _set.stamp++);
690 internal bool safe_next_get (out G val) {
691 if (_current != null) {
692 val = _set.lift_null_get (_current.next);
693 return _current.next != null;
695 val = _set.lift_null_get (_next);
696 return _next != null;
700 internal bool safe_previous_get (out G val) {
701 if (_current != null) {
702 val = _set.lift_null_get (_current.prev);
703 return _current.prev != null;
705 val = _set.lift_null_get (_prev);
706 return _next != null;
712 assert (stamp == _set.stamp);
713 return _current != null;
717 public bool read_only {
723 public bool foreach (ForallFunc<G> f) {
724 assert (stamp == _set.stamp);
725 unowned Node<G>? current = _current, next;
726 if (current != null) {
727 if (!f (current.key)) {
731 } else if (!started) {
743 while (next != null) {
755 private weak Node<G>? _current = null;
756 private weak Node<G>? _next = null;
757 private weak Node<G>? _prev = null;
758 private bool started = false;
761 private inline G min (G a, G b) {
762 return compare_func (a, b) <= 0 ? a : b;
765 private inline G max (G a, G b) {
766 return compare_func (a, b) > 0 ? a : b;
769 private class Range<G> {
770 public Range (TreeSet<G> set, G after, G before) {
772 if (set.compare_func (after, before) < 0) {
774 this.before = before;
775 type = RangeType.BOUNDED;
777 type = RangeType.EMPTY;
781 public Range.head (TreeSet<G> set, G before) {
783 this.before = before;
784 type = RangeType.HEAD;
787 public Range.tail (TreeSet<G> set, G after) {
790 type = RangeType.TAIL;
794 public Range.empty (TreeSet<G> set) {
796 type = RangeType.EMPTY;
800 public Range<G> cut_head (G after) {
803 return new Range<G> (set, after, before);
805 return new Range<G>.tail (set, set.max (after, this.after));
806 case RangeType.EMPTY:
808 case RangeType.BOUNDED:
809 var _after = set.max (after, this.after);
810 return new Range<G> (set, _after, before);
812 assert_not_reached ();
816 public Range<G> cut_tail (G before) {
819 return new Range<G>.head (set, set.min (before, this.before));
821 return new Range<G> (set, after, before);
822 case RangeType.EMPTY:
824 case RangeType.BOUNDED:
825 var _before = set.min (before, this.before);
826 return new Range<G> (set, after, _before);
828 assert_not_reached ();
832 public Range<G> cut (G after, G before) {
833 if (type == RangeType.EMPTY)
835 var _before = type != RangeType.TAIL ? set.min (before, this.before) : before;
836 var _after = type != RangeType.HEAD ? set.max (after, this.after) : after;
837 return new Range<G> (set, _after, _before);
840 public bool in_range (G item) {
841 return type == RangeType.EMPTY ? false : compare_range (item) == 0;
844 public int compare_range (G item) {
847 return set.compare_func (item, before) < 0 ? 0 : 1;
849 return set.compare_func (item, after) >= 0 ? 0 : -1;
850 case RangeType.EMPTY:
851 return 0; // For simplicity - please make sure it does not break anything
852 case RangeType.BOUNDED:
853 return set.compare_func (item, after) >= 0 ?
854 (set.compare_func (item, before) < 0 ? 0 : 1) : -1;
856 assert_not_reached ();
860 public bool empty_subset () {
863 return set._first == null || !in_range (set._first.key);
865 return set._last == null || !in_range (set._last.key);
866 case RangeType.EMPTY:
868 case RangeType.BOUNDED:
869 return first () == null;
871 assert_not_reached ();
875 public unowned Node<G>? first () {
877 case RangeType.EMPTY:
882 return set.find_floor (after);
886 public unowned Node<G>? last () {
888 case RangeType.EMPTY:
893 return set.find_lower (before);
897 private new TreeSet<G> set;
900 private RangeType type;
903 private enum RangeType {
910 private class SubSet<G> : AbstractBidirSortedSet<G> {
911 public SubSet (TreeSet<G> set, G after, G before) {
913 this.range = new Range<G> (set, after, before);
916 public SubSet.head (TreeSet<G> set, G before) {
918 this.range = new Range<G>.head (set, before);
921 public SubSet.tail (TreeSet<G> set, G after) {
923 this.range = new Range<G>.tail (set, after);
926 public SubSet.from_range (TreeSet<G> set, Range<G> range) {
931 public override int size {
934 Gee.Iterator<G> iterator = iterator ();
935 while (iterator.next ())
941 public override bool read_only {
945 public bool is_empty {
947 return range.empty_subset ();
951 public override bool contains (G item) {
952 return range.in_range (item) && set.contains (item);
955 public override bool add (G item) {
956 return range.in_range (item) && set.add (item);
959 public override bool remove (G item) {
960 return range.in_range (item) && set.remove (item);
963 public override void clear () {
964 var iter = iterator ();
965 while (iter.next ()) {
970 public override Gee.Iterator<G> iterator () {
971 return new SubIterator<G> (set, range);
974 public override BidirIterator<G> bidir_iterator () {
975 return new SubIterator<G> (set, range);
978 public override G first () {
979 weak Node<G>? _first = range.first ();
980 assert (_first != null);
984 public override G last () {
985 weak Node<G>? _last = range.last ();
986 assert (_last != null);
990 public override SortedSet<G> head_set (G before) {
991 return new SubSet<G>.from_range (set, range.cut_tail (before));
994 public override SortedSet<G> tail_set (G after) {
995 return new SubSet<G>.from_range (set, range.cut_head (after));
998 public override SortedSet<G> sub_set (G after, G before) {
999 return new SubSet<G>.from_range (set, range.cut (after, before));
1002 public override Gee.Iterator<G>? iterator_at (G item) {
1003 if (!range.in_range (item))
1005 weak Node<G>? n = set.find_node (item);
1008 return new SubIterator<G>.pointing (set, range, n);
1011 public override G? lower (G item) {
1012 var res = range.compare_range (item);
1015 var l = set.lower (item);
1016 return l != null && range.in_range (l) ? l : null;
1019 public override G? higher (G item) {
1020 var res = range.compare_range (item);
1023 var h = set.higher (item);
1024 return h != null && range.in_range (h) ? h : null;
1027 public override G? floor (G item) {
1028 var res = range.compare_range (item);
1031 var l = set.floor (item);
1032 return l != null && range.in_range (l) ? l : null;
1035 public override G? ceil (G item) {
1036 var res = range.compare_range (item);
1039 var h = set.ceil (item);
1040 return h != null && range.in_range (h) ? h : null;
1043 private new TreeSet<G> set;
1044 private Range<G> range;
1047 private class SubIterator<G> : Object, Traversable<G>, Gee.Iterator<G>, BidirIterator<G> {
1048 public SubIterator (TreeSet<G> set, Range<G> range) {
1053 public SubIterator.pointing (TreeSet<G> set, Range<G> range, Node<G> node) {
1056 this.iterator = new Iterator<G>.pointing (set, node);
1059 public bool next () {
1060 if (iterator != null) {
1062 if (iterator.safe_next_get (out next) && range.in_range (next)) {
1063 assert (iterator.next ());
1073 public bool has_next () {
1074 if (iterator != null) {
1076 return (iterator.safe_next_get (out next) && range.in_range (next));
1078 return range.first () != null;
1082 public bool first () {
1083 weak Node<G>? node = range.first ();
1086 iterator = new Iterator<G>.pointing (set, node);
1090 public bool previous () {
1091 if (iterator == null)
1094 if (iterator.safe_previous_get (out prev) && range.in_range (prev)) {
1095 assert (iterator.previous ());
1102 public bool has_previous () {
1103 if (iterator == null)
1106 return iterator.safe_previous_get (out prev) && range.in_range (prev);
1109 public bool last () {
1110 weak Node<G>? node = range.last ();
1113 iterator = new Iterator<G>.pointing (set, node);
1117 public new G get () {
1118 assert (iterator != null);
1119 return iterator.get ();
1122 public void remove () {
1123 assert (iterator != null);
1127 public bool read_only {
1135 return iterator.valid;
1139 public bool foreach(ForallFunc<G> f) {
1153 private new TreeSet<G> set;
1154 private Range<G> range;
1155 private Iterator<G>? iterator = null;
1158 private Node<G>? root = null;
1159 private weak Node<G>? _first = null;
1160 private weak Node<G>? _last = null;
1161 private int stamp = 0;