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;
77 public override bool contains (G item) {
78 weak Node<G>? cur = root;
80 int res = compare_func (item, cur.key);
92 private inline void rotate_right (ref Node<G> root) {
93 Node<G> pivot = (owned) root.left;
94 pivot.color = root.color;
95 root.color = Node.Color.RED;
96 root.left = (owned) pivot.right;
97 pivot.right = (owned) root;
100 stdout.printf (dump ("after rotate right on %s".printf ((string)root.right.key)));
104 private inline void rotate_left (ref Node<G> root) {
105 Node<G> pivot = (owned) root.right;
106 pivot.color = root.color;
107 root.color = Node.Color.RED;
108 root.right = (owned) pivot.left;
109 pivot.left = (owned) root;
110 root = (owned) pivot;
112 stdout.printf (dump ("after rotate left on %s".printf ((string)root.left.key)));
116 private inline bool is_red (Node<G>? n) {
117 return n != null && n.color == Node.Color.RED;
120 private inline bool is_black (Node<G>? n) {
121 return n == null || n.color == Node.Color.BLACK;
124 private inline void fix_up (ref Node<G> node) {
126 var n = (string)node.key;
128 if (is_black (node.left) && is_red (node.right)) {
129 rotate_left (ref node);
131 if (is_red (node.left) && is_red (node.left.left)) {
132 rotate_right (ref node);
134 if (is_red (node.left) && is_red (node.right)) {
138 stdout.printf (dump ("after fix up on %s".printf (n)));
142 private bool add_to_node (ref Node<G>? node, owned G item, Node<G>? prev, Node<G>? next) {
145 stdout.printf ("Adding %s to %s\n".printf ((string) item, (string) node.key));
148 node = new Node<G> ((owned) item, prev, next);
159 int cmp = compare_func (item, node.key);
163 } else if (cmp < 0) {
164 bool r = add_to_node (ref node.left, item, node.prev, node);
168 bool r = add_to_node (ref node.right, item, node, node.next);
177 * If the element already exists in the set it will not be added twice.
179 public override bool add (G item) {
180 #if CONSISTENCY_CHECKS
183 bool r = add_to_node (ref root, item, null, null);
184 root.color = Node.Color.BLACK;
185 #if CONSISTENCY_CHECKS
192 private inline void move_red_left (ref Node<G> root) {
194 var n = (string)root.key;
197 if (is_red (root.right.left)) {
198 rotate_right (ref root.right);
199 rotate_left (ref root);
203 stdout.printf (dump ("after red left on %s".printf (n)));
207 private inline void move_red_right (ref Node<G> root) {
209 var n = (string)root.key;
212 if (is_red (root.left.left)) {
213 rotate_right (ref root);
217 stdout.printf (dump ("after red right on %s".printf (n)));
221 private inline void fix_removal (ref Node<G> node, out G? key = null) {
222 Node<G> n = (owned)node;
224 if (n.prev != null) {
225 n.prev.next = n.next;
229 if (n.next != null) {
230 n.next.prev = n.prev;
238 private void remove_minimal (ref Node<G> node, out G key) {
239 if (node.left == null) {
240 fix_removal (ref node, out key);
244 if (is_black (node.left) && is_black (node.left.left)) {
245 move_red_left (ref node);
248 remove_minimal (ref node.left, out key);
253 private bool remove_from_node (ref Node<G>? node, G item, out unowned Node<G>? prev = null, out unowned Node<G>? next = null) {
255 stdout.printf ("Removing %s from %s\n", (string)item, node != null ? (string)node.key : null);
261 } else if (compare_func (item, node.key) < 0) {
262 weak Node<G> left = node.left;
268 if (is_black (left) && is_black (left.left)) {
269 move_red_left (ref node);
271 bool r = remove_from_node (ref node.left, item, out prev, out next);
275 if (is_red (node.left)) {
276 rotate_right (ref node);
279 weak Node<G>? r = node.right;
280 if (compare_func (item, node.key) == 0 && r == null) {
283 fix_removal (ref node, null);
286 if (is_black (r) && r != null && is_black (r.left)) {
287 move_red_right (ref node);
289 if (compare_func (item, node.key) == 0) {
292 remove_minimal (ref node.right, out node.key);
296 bool re = remove_from_node (ref node.right, item, out prev, out next);
306 public override bool remove (G item) {
307 #if CONSISTENCY_CHECKS
310 bool b = remove_from_node (ref root, item);
312 root.color = Node.Color.BLACK;
314 #if CONSISTENCY_CHECKS
321 private inline void clear_subtree (owned Node<G> node) {
323 if (node.left != null)
324 clear_subtree ((owned) node.left);
325 if (node.right != null)
326 clear_subtree ((owned) node.right);
332 public override void clear () {
334 clear_subtree ((owned) root);
335 _first = _last = null;
344 public override Gee.Iterator<G> iterator () {
345 return new Iterator<G> (this);
351 public override BidirIterator<G> bidir_iterator () {
352 return new Iterator<G> (this);
355 private inline G? lift_null_get (Node<G>? node) {
356 return node != null ? node.key : null;
362 public override G first () {
363 assert (_first != null);
370 public override G last () {
371 assert (_last != null);
378 public override SortedSet<G> head_set (G before) {
379 return new SubSet<G>.head (this, before);
385 public override SortedSet<G> tail_set (G after) {
386 return new SubSet<G>.tail (this, after);
392 public override SortedSet<G> sub_set (G after, G before) {
393 return new SubSet<G> (this, after, before);
396 private inline unowned Node<G>? find_node (G item) {
397 weak Node<G>? cur = root;
398 while (cur != null) {
399 int res = compare_func (item, cur.key);
402 } else if (res < 0) {
414 public override Gee.Iterator<G>? iterator_at (G item) {
415 weak Node<G>? node = find_node (item);
416 return node != null ? new Iterator<G>.pointing (this, node) : null;
419 private inline unowned Node<G>? find_nearest (G item) {
420 weak Node<G>? cur = root;
421 while (cur != null) {
422 int res = compare_func (item, cur.key);
425 } else if (res < 0) {
426 if (cur.left == null)
430 if (cur.right == null)
438 private inline unowned Node<G>? find_lower (G item) {
439 weak Node<G>? node = find_nearest (item);
442 return compare_func (item, node.key) <= 0 ? node.prev : node;
445 private inline unowned Node<G>? find_higher (G item) {
446 weak Node<G>? node = find_nearest (item);
449 return compare_func (item, node.key) >= 0 ? node.next : node;
452 private inline unowned Node<G>? find_floor (G item) {
453 weak Node<G>? node = find_nearest (item);
456 return compare_func (item, node.key) < 0 ? node.prev : node;
459 private inline unowned Node<G>? find_ceil (G item) {
460 weak Node<G>? node = find_nearest (item);
463 return compare_func (item, node.key) > 0 ? node.next : node;
469 public override G? lower (G item) {
470 return lift_null_get (find_lower (item));
476 public override G? higher (G item) {
477 return lift_null_get (find_higher (item));
483 public override G? floor (G item) {
484 return lift_null_get (find_floor (item));
490 public override G? ceil (G item) {
491 return lift_null_get (find_ceil (item));
494 #if CONSISTENCY_CHECKS
495 public inline void check () {
496 check_subtree (root);
497 assert (root == null || root.color == Node.Color.BLACK);
499 stdout.printf ("%s\n", dump ());
503 private inline uint check_subtree (Node<G>? node) {
506 assert (! (is_black (node.left) && is_red (node.right))); // Check left-leaning
507 assert (! (is_red (node) && is_red (node.left))); // Check red property
508 uint l = check_subtree (node.left);
509 uint r = check_subtree (node.right);
511 return l + (node.color == Node.Color.BLACK ? 1 : 0);
515 public string dump (string? when = null) {
516 return "TreeSet dump%s:\n%s".printf (when == null ? "" : (" " + when), dump_node (root));
519 private inline string dump_node (Node<G>? node, uint depth = 0) {
521 return dump_node (node.left, depth + 1) +
522 "%s%s%p(%s)\033[0m\n".printf (string.nfill (depth, ' '),
523 node.color == Node.Color.RED ? "\033[0;31m" : "",
524 node, (string)node.key) +
525 dump_node (node.right, depth + 1);
531 private class Node<G> {
536 public Color flip () {
545 public Node (owned G node, Node<G>? prev, Node<G>? next) {
546 this.key = (owned) node;
547 this.color = Color.RED;
558 public void flip () {
559 color = color.flip ();
561 left.color = left.color.flip ();
564 right.color = right.color.flip ();
570 public Node<G>? left;
571 public Node<G>? right;
572 public weak Node<G>? prev;
573 public weak Node<G>? next;
576 private class Iterator<G> : Object, Traversable<G>, Gee.Iterator<G>, BidirIterator<G> {
577 private TreeSet<G> _set;
579 // concurrent modification protection
582 public Iterator (TreeSet<G> set) {
587 public Iterator.pointing (TreeSet<G> set, Node<G> current) {
589 this.current = current;
590 this.stamp = set.stamp;
594 public bool next () {
595 assert (stamp == _set.stamp);
596 if (current != null) {
597 if (current.next != null) {
598 current = current.next;
603 } else if (!started) {
604 current = _set._first;
606 return current != null;
609 if (current != null) {
613 return current != null;
617 public bool has_next () {
618 assert (stamp == _set.stamp);
619 return (!started && _set._first != null) ||
620 (current == null && _next != null) ||
621 (current != null && current.next != null);
624 public bool first () {
625 assert (stamp == _set.stamp);
626 current = _set._first;
630 return current != null; // on false it is null anyway
633 public bool previous () {
634 assert (stamp == _set.stamp);
635 if (current != null) {
636 if (current.prev != null) {
637 current = current.prev;
654 public bool has_previous () {
655 assert (stamp == _set.stamp);
656 return (current == null && _prev != null) ||
657 (current != null && current.prev != null);
660 public bool last () {
661 assert (stamp == _set.stamp);
662 current = _set._last;
666 return current != null; // on false it is null anyway
669 public new G get () {
670 assert (stamp == _set.stamp);
671 assert (current != null);
675 public void remove () {
676 assert (stamp == _set.stamp);
677 assert (current != null);
678 bool success = _set.remove_from_node (ref _set.root, current.key, out _prev, out _next);
680 if (_set.root != null)
681 _set.root.color = Node.Color.BLACK;
683 assert (stamp++ == _set.stamp++);
686 internal bool safe_next_get (out G val) {
687 if (current != null) {
688 val = _set.lift_null_get (current.next);
689 return current.next != null;
691 val = _set.lift_null_get (_next);
692 return _next != null;
696 internal bool safe_previous_get (out G val) {
697 if (current != null) {
698 val = _set.lift_null_get (current.prev);
699 return current.prev != null;
701 val = _set.lift_null_get (_prev);
702 return _next != null;
708 assert (stamp == _set.stamp);
709 return current != null;
713 public bool read_only {
719 public void foreach (ForallFunc<G> f) {
720 assert (stamp == _set.stamp);
721 if (current != null) {
723 _next = current.next;
724 } else if (!started) {
727 while (_next != null) {
730 _next = current.next;
734 private weak Node<G>? current = null;
735 private weak Node<G>? _next = null;
736 private weak Node<G>? _prev = null;
737 private bool started = false;
740 private inline G min (G a, G b) {
741 return compare_func (a, b) <= 0 ? a : b;
744 private inline G max (G a, G b) {
745 return compare_func (a, b) > 0 ? a : b;
748 private class Range<G> {
749 public Range (TreeSet<G> set, G after, G before) {
751 if (set.compare_func (after, before) < 0) {
753 this.before = before;
754 type = RangeType.BOUNDED;
756 type = RangeType.EMPTY;
760 public Range.head (TreeSet<G> set, G before) {
762 this.before = before;
763 type = RangeType.HEAD;
766 public Range.tail (TreeSet<G> set, G after) {
769 type = RangeType.TAIL;
773 public Range.empty (TreeSet<G> set) {
775 type = RangeType.EMPTY;
779 public Range<G> cut_head (G after) {
782 return new Range<G> (set, after, before);
784 return new Range<G>.tail (set, set.max (after, this.after));
785 case RangeType.EMPTY:
787 case RangeType.BOUNDED:
788 var _after = set.max (after, this.after);
789 return new Range<G> (set, _after, before);
791 assert_not_reached ();
795 public Range<G> cut_tail (G before) {
798 return new Range<G>.head (set, set.min (before, this.before));
800 return new Range<G> (set, after, before);
801 case RangeType.EMPTY:
803 case RangeType.BOUNDED:
804 var _before = set.min (before, this.before);
805 return new Range<G> (set, after, _before);
807 assert_not_reached ();
811 public Range<G> cut (G after, G before) {
812 if (type == RangeType.EMPTY)
814 var _before = type != RangeType.TAIL ? set.min (before, this.before) : before;
815 var _after = type != RangeType.HEAD ? set.max (after, this.after) : after;
816 return new Range<G> (set, _after, _before);
819 public bool in_range (G item) {
820 return type == RangeType.EMPTY ? false : compare_range (item) == 0;
823 public int compare_range (G item) {
826 return set.compare_func (item, before) < 0 ? 0 : 1;
828 return set.compare_func (item, after) >= 0 ? 0 : -1;
829 case RangeType.EMPTY:
830 return 0; // For simplicity - please make sure it does not break anything
831 case RangeType.BOUNDED:
832 return set.compare_func (item, after) >= 0 ?
833 (set.compare_func (item, before) < 0 ? 0 : 1) : -1;
835 assert_not_reached ();
839 public bool empty_subset () {
842 return set._first == null || !in_range (set._first.key);
844 return set._last == null || !in_range (set._last.key);
845 case RangeType.EMPTY:
847 case RangeType.BOUNDED:
848 return first () == null;
850 assert_not_reached ();
854 public unowned Node<G>? first () {
856 case RangeType.EMPTY:
861 return set.find_floor (after);
865 public unowned Node<G>? last () {
867 case RangeType.EMPTY:
872 return set.find_lower (before);
876 private new TreeSet<G> set;
879 private RangeType type;
882 private enum RangeType {
889 private class SubSet<G> : AbstractBidirSortedSet<G> {
890 public SubSet (TreeSet<G> set, G after, G before) {
892 this.range = new Range<G> (set, after, before);
895 public SubSet.head (TreeSet<G> set, G before) {
897 this.range = new Range<G>.head (set, before);
900 public SubSet.tail (TreeSet<G> set, G after) {
902 this.range = new Range<G>.tail (set, after);
905 public SubSet.from_range (TreeSet<G> set, Range<G> range) {
910 public override int size {
913 Gee.Iterator<G> iterator = iterator ();
914 while (iterator.next ())
920 public override bool read_only {
924 public bool is_empty {
926 return range.empty_subset ();
930 public override bool contains (G item) {
931 return range.in_range (item) && set.contains (item);
934 public override bool add (G item) {
935 return range.in_range (item) && set.add (item);
938 public override bool remove (G item) {
939 return range.in_range (item) && set.remove (item);
942 public override void clear () {
943 var iter = iterator ();
944 while (iter.next ()) {
949 public override Gee.Iterator<G> iterator () {
950 return new SubIterator<G> (set, range);
953 public override BidirIterator<G> bidir_iterator () {
954 return new SubIterator<G> (set, range);
957 public override G first () {
958 weak Node<G>? _first = range.first ();
959 assert (_first != null);
963 public override G last () {
964 weak Node<G>? _last = range.last ();
965 assert (_last != null);
969 public override SortedSet<G> head_set (G before) {
970 return new SubSet<G>.from_range (set, range.cut_tail (before));
973 public override SortedSet<G> tail_set (G after) {
974 return new SubSet<G>.from_range (set, range.cut_head (after));
977 public override SortedSet<G> sub_set (G after, G before) {
978 return new SubSet<G>.from_range (set, range.cut (after, before));
981 public override Gee.Iterator<G>? iterator_at (G item) {
982 if (!range.in_range (item))
984 weak Node<G>? n = set.find_node (item);
987 return new SubIterator<G>.pointing (set, range, n);
990 public override G? lower (G item) {
991 var res = range.compare_range (item);
994 var l = set.lower (item);
995 return l != null && range.in_range (l) ? l : null;
998 public override G? higher (G item) {
999 var res = range.compare_range (item);
1002 var h = set.higher (item);
1003 return h != null && range.in_range (h) ? h : null;
1006 public override G? floor (G item) {
1007 var res = range.compare_range (item);
1010 var l = set.floor (item);
1011 return l != null && range.in_range (l) ? l : null;
1014 public override G? ceil (G item) {
1015 var res = range.compare_range (item);
1018 var h = set.ceil (item);
1019 return h != null && range.in_range (h) ? h : null;
1022 private new TreeSet<G> set;
1023 private Range<G> range;
1026 private class SubIterator<G> : Object, Traversable<G>, Gee.Iterator<G>, BidirIterator<G> {
1027 public SubIterator (TreeSet<G> set, Range<G> range) {
1032 public SubIterator.pointing (TreeSet<G> set, Range<G> range, Node<G> node) {
1035 this.iterator = new Iterator<G>.pointing (set, node);
1038 public bool next () {
1039 if (iterator != null) {
1041 if (iterator.safe_next_get (out next) && range.in_range (next)) {
1042 assert (iterator.next ());
1052 public bool has_next () {
1053 if (iterator != null) {
1055 return (iterator.safe_next_get (out next) && range.in_range (next));
1057 return range.first () != null;
1061 public bool first () {
1062 weak Node<G>? node = range.first ();
1065 iterator = new Iterator<G>.pointing (set, node);
1069 public bool previous () {
1070 if (iterator == null)
1073 if (iterator.safe_previous_get (out prev) && range.in_range (prev)) {
1074 assert (iterator.previous ());
1081 public bool has_previous () {
1082 if (iterator == null)
1085 return iterator.safe_previous_get (out prev) && range.in_range (prev);
1088 public bool last () {
1089 weak Node<G>? node = range.last ();
1092 iterator = new Iterator<G>.pointing (set, node);
1096 public new G get () {
1097 assert (iterator != null);
1098 return iterator.get ();
1101 public void remove () {
1102 assert (iterator != null);
1106 public bool read_only {
1114 return iterator.valid;
1118 public void foreach(ForallFunc<G> f) {
1125 private new TreeSet<G> set;
1126 private Range<G> range;
1127 private Iterator<G>? iterator = null;
1130 private Node<G>? root = null;
1131 private weak Node<G>? _first = null;
1132 private weak Node<G>? _last = null;
1133 private int stamp = 0;