Spelling fixes
[platform/upstream/glib.git] / glib / gsequence.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007
3  * Soeren Sandmann (sandmann@daimi.au.dk)
4  *
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 of the License, or (at your option) any later version.
9  *
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.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gsequence.h"
24
25 #include "gmem.h"
26 #include "gtestutils.h"
27 /**
28  * SECTION:sequence
29  * @title: Sequences
30  * @short_description: scalable lists
31  *
32  * The #GSequence data structure has the API of a list, but is
33  * implemented internally with a balanced binary tree. This means that
34  * it is possible to maintain a sorted list of n elements in time O(n
35  * log n). The data contained in each element can be either integer
36  * values, by using of the <link
37  * linkend="glib-Type-Conversion-Macros">Type Conversion Macros</link>,
38  * or simply pointers to any type of data.
39  *
40  * A #GSequence is accessed through <firstterm>iterators</firstterm>,
41  * represented by a #GSequenceIter. An iterator represents a position
42  * between two elements of the sequence. For example, the
43  * <firstterm>begin</firstterm> iterator represents the gap immediately
44  * before the first element of the sequence, and the
45  * <firstterm>end</firstterm> iterator represents the gap immediately
46  * after the last element. In an empty sequence, the begin and end
47  * iterators are the same.
48  *
49  * Some methods on #GSequence operate on ranges of items. For example
50  * g_sequence_foreach_range() will call a user-specified function on
51  * each element with the given range. The range is delimited by the
52  * gaps represented by the passed-in iterators, so if you pass in the
53  * begin and end iterators, the range in question is the entire
54  * sequence.
55  *
56  * The function g_sequence_get() is used with an iterator to access the
57  * element immediately following the gap that the iterator represents.
58  * The iterator is said to <firstterm>point</firstterm> to that element.
59  *
60  * Iterators are stable across most operations on a #GSequence. For
61  * example an iterator pointing to some element of a sequence will
62  * continue to point to that element even after the sequence is sorted.
63  * Even moving an element to another sequence using for example
64  * g_sequence_move_range() will not invalidate the iterators pointing
65  * to it. The only operation that will invalidate an iterator is when
66  * the element it points to is removed from any sequence.
67  **/
68
69 /**
70  * GSequenceIter:
71  *
72  * The #GSequenceIter struct is an opaque data type representing an
73  * iterator pointing into a #GSequence.
74  **/
75
76 /**
77  * GSequenceIterCompareFunc:
78  * @a: a #GSequenceIter
79  * @b: a #GSequenceIter
80  * @data: user data
81  * @Returns: zero if the iterators are equal, a negative value if @a
82  *           comes before @b, and a positive value if @b comes before
83  *           @a.
84  *
85  * A #GSequenceIterCompareFunc is a function used to compare iterators.
86  * It must return zero if the iterators compare equal, a negative value
87  * if @a comes before @b, and a positive value if @b comes before @a.
88  **/
89
90 typedef struct _GSequenceNode GSequenceNode;
91
92 /**
93  * GSequence:
94  *
95  * The #GSequence struct is an opaque data type representing a
96  * <link linkend="glib-Sequences">Sequence</link> data type.
97  **/
98 struct _GSequence
99 {
100   GSequenceNode *       end_node;
101   GDestroyNotify        data_destroy_notify;
102   gboolean              access_prohibited;
103
104   /* The 'real_sequence' is used when temporary sequences are created
105    * to hold nodes that are being rearranged. The 'real_sequence' of such
106    * a temporary sequence points to the sequence that is actually being
107    * manipulated. The only reason we need this is so that when the
108    * sort/sort_changed/search_iter() functions call out to the application
109    * g_sequence_iter_get_sequence() will return the correct sequence.
110    */
111   GSequence *           real_sequence;
112 };
113
114 struct _GSequenceNode
115 {
116   gint                  n_nodes;
117   GSequenceNode *       parent;
118   GSequenceNode *       left;
119   GSequenceNode *       right;
120   gpointer              data;   /* For the end node, this field points
121                                  * to the sequence
122                                  */
123 };
124
125 /*
126  * Declaration of GSequenceNode methods
127  */
128 static GSequenceNode *node_new           (gpointer                  data);
129 static GSequenceNode *node_get_first     (GSequenceNode            *node);
130 static GSequenceNode *node_get_last      (GSequenceNode            *node);
131 static GSequenceNode *node_get_prev      (GSequenceNode            *node);
132 static GSequenceNode *node_get_next      (GSequenceNode            *node);
133 static gint           node_get_pos       (GSequenceNode            *node);
134 static GSequenceNode *node_get_by_pos    (GSequenceNode            *node,
135                                           gint                      pos);
136 static GSequenceNode *node_find          (GSequenceNode            *haystack,
137                                           GSequenceNode            *needle,
138                                           GSequenceNode            *end,
139                                           GSequenceIterCompareFunc  cmp,
140                                           gpointer                  user_data);
141 static GSequenceNode *node_find_closest  (GSequenceNode            *haystack,
142                                           GSequenceNode            *needle,
143                                           GSequenceNode            *end,
144                                           GSequenceIterCompareFunc  cmp,
145                                           gpointer                  user_data);
146 static gint           node_get_length    (GSequenceNode            *node);
147 static void           node_free          (GSequenceNode            *node,
148                                           GSequence                *seq);
149 static void           node_cut           (GSequenceNode            *split);
150 static void           node_insert_before (GSequenceNode            *node,
151                                           GSequenceNode            *new);
152 static void           node_unlink        (GSequenceNode            *node);
153 static void           node_join          (GSequenceNode            *left,
154                                           GSequenceNode            *right);
155 static void           node_insert_sorted (GSequenceNode            *node,
156                                           GSequenceNode            *new,
157                                           GSequenceNode            *end,
158                                           GSequenceIterCompareFunc  cmp_func,
159                                           gpointer                  cmp_data);
160
161
162 /*
163  * Various helper functions
164  */
165 static void
166 check_seq_access (GSequence *seq)
167 {
168   if (G_UNLIKELY (seq->access_prohibited))
169     {
170       g_warning ("Accessing a sequence while it is "
171                  "being sorted or searched is not allowed");
172     }
173 }
174
175 static GSequence *
176 get_sequence (GSequenceNode *node)
177 {
178   return (GSequence *)node_get_last (node)->data;
179 }
180
181 static void
182 check_iter_access (GSequenceIter *iter)
183 {
184   check_seq_access (get_sequence (iter));
185 }
186
187 static gboolean
188 is_end (GSequenceIter *iter)
189 {
190   GSequence *seq;
191
192   if (iter->right)
193     return FALSE;
194
195   if (!iter->parent)
196     return TRUE;
197
198   if (iter->parent->right != iter)
199     return FALSE;
200
201   seq = get_sequence (iter);
202
203   return seq->end_node == iter;
204 }
205
206 typedef struct
207 {
208   GCompareDataFunc  cmp_func;
209   gpointer          cmp_data;
210   GSequenceNode    *end_node;
211 } SortInfo;
212
213 /* This function compares two iters using a normal compare
214  * function and user_data passed in in a SortInfo struct
215  */
216 static gint
217 iter_compare (GSequenceIter *node1,
218               GSequenceIter *node2,
219               gpointer       data)
220 {
221   const SortInfo *info = data;
222   gint retval;
223
224   if (node1 == info->end_node)
225     return 1;
226
227   if (node2 == info->end_node)
228     return -1;
229
230   retval = info->cmp_func (node1->data, node2->data, info->cmp_data);
231
232   return retval;
233 }
234
235 /*
236  * Public API
237  */
238
239 /**
240  * g_sequence_new:
241  * @data_destroy: a #GDestroyNotify function, or %NULL
242  *
243  * Creates a new GSequence. The @data_destroy function, if non-%NULL will
244  * be called on all items when the sequence is destroyed and on items that
245  * are removed from the sequence.
246  *
247  * Return value: a new #GSequence
248  *
249  * Since: 2.14
250  **/
251 GSequence *
252 g_sequence_new (GDestroyNotify data_destroy)
253 {
254   GSequence *seq = g_new (GSequence, 1);
255   seq->data_destroy_notify = data_destroy;
256
257   seq->end_node = node_new (seq);
258
259   seq->access_prohibited = FALSE;
260
261   seq->real_sequence = seq;
262
263   return seq;
264 }
265
266 /**
267  * g_sequence_free:
268  * @seq: a #GSequence
269  *
270  * Frees the memory allocated for @seq. If @seq has a data destroy
271  * function associated with it, that function is called on all items in
272  * @seq.
273  *
274  * Since: 2.14
275  **/
276 void
277 g_sequence_free (GSequence *seq)
278 {
279   g_return_if_fail (seq != NULL);
280
281   check_seq_access (seq);
282
283   node_free (seq->end_node, seq);
284
285   g_free (seq);
286 }
287
288 /**
289  * g_sequence_foreach_range:
290  * @begin: a #GSequenceIter
291  * @end: a #GSequenceIter
292  * @func: a #GFunc
293  * @user_data: user data passed to @func
294  *
295  * Calls @func for each item in the range (@begin, @end) passing
296  * @user_data to the function.
297  *
298  * Since: 2.14
299  **/
300 void
301 g_sequence_foreach_range (GSequenceIter *begin,
302                           GSequenceIter *end,
303                           GFunc          func,
304                           gpointer       user_data)
305 {
306   GSequence *seq;
307   GSequenceIter *iter;
308
309   g_return_if_fail (func != NULL);
310   g_return_if_fail (begin != NULL);
311   g_return_if_fail (end != NULL);
312
313   seq = get_sequence (begin);
314
315   seq->access_prohibited = TRUE;
316
317   iter = begin;
318   while (iter != end)
319     {
320       GSequenceIter *next = node_get_next (iter);
321
322       func (iter->data, user_data);
323
324       iter = next;
325     }
326
327   seq->access_prohibited = FALSE;
328 }
329
330 /**
331  * g_sequence_foreach:
332  * @seq: a #GSequence
333  * @func: the function to call for each item in @seq
334  * @user_data: user data passed to @func
335  *
336  * Calls @func for each item in the sequence passing @user_data
337  * to the function.
338  *
339  * Since: 2.14
340  **/
341 void
342 g_sequence_foreach (GSequence *seq,
343                     GFunc      func,
344                     gpointer   user_data)
345 {
346   GSequenceIter *begin, *end;
347
348   check_seq_access (seq);
349
350   begin = g_sequence_get_begin_iter (seq);
351   end   = g_sequence_get_end_iter (seq);
352
353   g_sequence_foreach_range (begin, end, func, user_data);
354 }
355
356 /**
357  * g_sequence_range_get_midpoint:
358  * @begin: a #GSequenceIter
359  * @end: a #GSequenceIter
360  *
361  * Finds an iterator somewhere in the range (@begin, @end). This
362  * iterator will be close to the middle of the range, but is not
363  * guaranteed to be <emphasis>exactly</emphasis> in the middle.
364  *
365  * The @begin and @end iterators must both point to the same sequence and
366  * @begin must come before or be equal to @end in the sequence.
367  *
368  * Return value: A #GSequenceIter pointing somewhere in the
369  * (@begin, @end) range.
370  *
371  * Since: 2.14
372  **/
373 GSequenceIter *
374 g_sequence_range_get_midpoint (GSequenceIter *begin,
375                                GSequenceIter *end)
376 {
377   int begin_pos, end_pos, mid_pos;
378
379   g_return_val_if_fail (begin != NULL, NULL);
380   g_return_val_if_fail (end != NULL, NULL);
381   g_return_val_if_fail (get_sequence (begin) == get_sequence (end), NULL);
382
383   begin_pos = node_get_pos (begin);
384   end_pos = node_get_pos (end);
385
386   g_return_val_if_fail (end_pos >= begin_pos, NULL);
387
388   mid_pos = begin_pos + (end_pos - begin_pos) / 2;
389
390   return node_get_by_pos (begin, mid_pos);
391 }
392
393 /**
394  * g_sequence_iter_compare:
395  * @a: a #GSequenceIter
396  * @b: a #GSequenceIter
397  *
398  * Returns a negative number if @a comes before @b, 0 if they are equal,
399  * and a positive number if @a comes after @b.
400  *
401  * The @a and @b iterators must point into the same sequence.
402  *
403  * Return value: A negative number if @a comes before @b, 0 if they are
404  * equal, and a positive number if @a comes after @b.
405  *
406  * Since: 2.14
407  **/
408 gint
409 g_sequence_iter_compare (GSequenceIter *a,
410                          GSequenceIter *b)
411 {
412   gint a_pos, b_pos;
413
414   g_return_val_if_fail (a != NULL, 0);
415   g_return_val_if_fail (b != NULL, 0);
416   g_return_val_if_fail (get_sequence (a) == get_sequence (b), 0);
417
418   check_iter_access (a);
419   check_iter_access (b);
420
421   a_pos = node_get_pos (a);
422   b_pos = node_get_pos (b);
423
424   if (a_pos == b_pos)
425     return 0;
426   else if (a_pos > b_pos)
427     return 1;
428   else
429     return -1;
430 }
431
432 /**
433  * g_sequence_append:
434  * @seq: a #GSequence
435  * @data: the data for the new item
436  *
437  * Adds a new item to the end of @seq.
438  *
439  * Return value: an iterator pointing to the new item
440  *
441  * Since: 2.14
442  **/
443 GSequenceIter *
444 g_sequence_append (GSequence *seq,
445                    gpointer   data)
446 {
447   GSequenceNode *node;
448
449   g_return_val_if_fail (seq != NULL, NULL);
450
451   check_seq_access (seq);
452
453   node = node_new (data);
454   node_insert_before (seq->end_node, node);
455
456   return node;
457 }
458
459 /**
460  * g_sequence_prepend:
461  * @seq: a #GSequence
462  * @data: the data for the new item
463  *
464  * Adds a new item to the front of @seq
465  *
466  * Return value: an iterator pointing to the new item
467  *
468  * Since: 2.14
469  **/
470 GSequenceIter *
471 g_sequence_prepend (GSequence *seq,
472                     gpointer   data)
473 {
474   GSequenceNode *node, *first;
475
476   g_return_val_if_fail (seq != NULL, NULL);
477
478   check_seq_access (seq);
479
480   node = node_new (data);
481   first = node_get_first (seq->end_node);
482
483   node_insert_before (first, node);
484
485   return node;
486 }
487
488 /**
489  * g_sequence_insert_before:
490  * @iter: a #GSequenceIter
491  * @data: the data for the new item
492  *
493  * Inserts a new item just before the item pointed to by @iter.
494  *
495  * Return value: an iterator pointing to the new item
496  *
497  * Since: 2.14
498  **/
499 GSequenceIter *
500 g_sequence_insert_before (GSequenceIter *iter,
501                           gpointer       data)
502 {
503   GSequenceNode *node;
504
505   g_return_val_if_fail (iter != NULL, NULL);
506
507   check_iter_access (iter);
508
509   node = node_new (data);
510
511   node_insert_before (iter, node);
512
513   return node;
514 }
515
516 /**
517  * g_sequence_remove:
518  * @iter: a #GSequenceIter
519  *
520  * Removes the item pointed to by @iter. It is an error to pass the
521  * end iterator to this function.
522  *
523  * If the sequnce has a data destroy function associated with it, this
524  * function is called on the data for the removed item.
525  *
526  * Since: 2.14
527  **/
528 void
529 g_sequence_remove (GSequenceIter *iter)
530 {
531   GSequence *seq;
532
533   g_return_if_fail (iter != NULL);
534   g_return_if_fail (!is_end (iter));
535
536   check_iter_access (iter);
537
538   seq = get_sequence (iter);
539
540   node_unlink (iter);
541   node_free (iter, seq);
542 }
543
544 /**
545  * g_sequence_remove_range:
546  * @begin: a #GSequenceIter
547  * @end: a #GSequenceIter
548  *
549  * Removes all items in the (@begin, @end) range.
550  *
551  * If the sequence has a data destroy function associated with it, this
552  * function is called on the data for the removed items.
553  *
554  * Since: 2.14
555  **/
556 void
557 g_sequence_remove_range (GSequenceIter *begin,
558                          GSequenceIter *end)
559 {
560   g_return_if_fail (get_sequence (begin) == get_sequence (end));
561
562   check_iter_access (begin);
563   check_iter_access (end);
564
565   g_sequence_move_range (NULL, begin, end);
566 }
567
568 /**
569  * g_sequence_move_range:
570  * @dest: a #GSequenceIter
571  * @begin: a #GSequenceIter
572  * @end: a #GSequenceIter
573  *
574  * Inserts the (@begin, @end) range at the destination pointed to by ptr.
575  * The @begin and @end iters must point into the same sequence. It is
576  * allowed for @dest to point to a different sequence than the one pointed
577  * into by @begin and @end.
578  *
579  * If @dest is NULL, the range indicated by @begin and @end is
580  * removed from the sequence. If @dest iter points to a place within
581  * the (@begin, @end) range, the range does not move.
582  *
583  * Since: 2.14
584  **/
585 void
586 g_sequence_move_range (GSequenceIter *dest,
587                        GSequenceIter *begin,
588                        GSequenceIter *end)
589 {
590   GSequence *src_seq;
591   GSequenceNode *first;
592
593   g_return_if_fail (begin != NULL);
594   g_return_if_fail (end != NULL);
595
596   check_iter_access (begin);
597   check_iter_access (end);
598   if (dest)
599     check_iter_access (dest);
600
601   src_seq = get_sequence (begin);
602
603   g_return_if_fail (src_seq == get_sequence (end));
604
605   /* Dest points to begin or end? */
606   if (dest == begin || dest == end)
607     return;
608
609   /* begin comes after end? */
610   if (g_sequence_iter_compare (begin, end) >= 0)
611     return;
612
613   /* dest points somewhere in the (begin, end) range? */
614   if (dest && get_sequence (dest) == src_seq &&
615       g_sequence_iter_compare (dest, begin) > 0 &&
616       g_sequence_iter_compare (dest, end) < 0)
617     {
618       return;
619     }
620
621   src_seq = get_sequence (begin);
622
623   first = node_get_first (begin);
624
625   node_cut (begin);
626
627   node_cut (end);
628
629   if (first != begin)
630     node_join (first, end);
631
632   if (dest)
633     {
634       first = node_get_first (dest);
635
636       node_cut (dest);
637
638       node_join (begin, dest);
639
640       if (dest != first)
641         node_join (first, begin);
642     }
643   else
644     {
645       node_free (begin, src_seq);
646     }
647 }
648
649 /**
650  * g_sequence_sort:
651  * @seq: a #GSequence
652  * @cmp_func: the function used to sort the sequence
653  * @cmp_data: user data passed to @cmp_func
654  *
655  * Sorts @seq using @cmp_func.
656  *
657  * @cmp_func is passed two items of @seq and should
658  * return 0 if they are equal, a negative value if the
659  * first comes before the second, and a positive value
660  * if the second comes before the first.
661  *
662  * Since: 2.14
663  **/
664 void
665 g_sequence_sort (GSequence        *seq,
666                  GCompareDataFunc  cmp_func,
667                  gpointer          cmp_data)
668 {
669   SortInfo info;
670
671   info.cmp_func = cmp_func;
672   info.cmp_data = cmp_data;
673   info.end_node = seq->end_node;
674
675   check_seq_access (seq);
676
677   g_sequence_sort_iter (seq, iter_compare, &info);
678 }
679
680 /**
681  * g_sequence_insert_sorted:
682  * @seq: a #GSequence
683  * @data: the data to insert
684  * @cmp_func: the function used to compare items in the sequence
685  * @cmp_data: user data passed to @cmp_func.
686  *
687  * Inserts @data into @sequence using @func to determine the new
688  * position. The sequence must already be sorted according to @cmp_func;
689  * otherwise the new position of @data is undefined.
690  *
691  * @cmp_func is called with two items of the @seq and @user_data.
692  * It should return 0 if the items are equal, a negative value
693  * if the first item comes before the second, and a positive value
694  * if the second  item comes before the first.
695  *
696  * Return value: a #GSequenceIter pointing to the new item.
697  *
698  * Since: 2.14
699  **/
700 GSequenceIter *
701 g_sequence_insert_sorted (GSequence        *seq,
702                           gpointer          data,
703                           GCompareDataFunc  cmp_func,
704                           gpointer          cmp_data)
705 {
706   SortInfo info;
707
708   g_return_val_if_fail (seq != NULL, NULL);
709   g_return_val_if_fail (cmp_func != NULL, NULL);
710
711   info.cmp_func = cmp_func;
712   info.cmp_data = cmp_data;
713   info.end_node = seq->end_node;
714   check_seq_access (seq);
715
716   return g_sequence_insert_sorted_iter (seq, data, iter_compare, &info);
717 }
718
719 /**
720  * g_sequence_sort_changed:
721  * @iter: A #GSequenceIter
722  * @cmp_func: the function used to compare items in the sequence
723  * @cmp_data: user data passed to @cmp_func.
724  *
725  * Moves the data pointed to a new position as indicated by @cmp_func. This
726  * function should be called for items in a sequence already sorted according
727  * to @cmp_func whenever some aspect of an item changes so that @cmp_func
728  * may return different values for that item.
729  *
730  * @cmp_func is called with two items of the @seq and @user_data.
731  * It should return 0 if the items are equal, a negative value if
732  * the first item comes before the second, and a positive value if
733  * the second item comes before the first.
734  *
735  * Since: 2.14
736  **/
737 void
738 g_sequence_sort_changed (GSequenceIter    *iter,
739                          GCompareDataFunc  cmp_func,
740                          gpointer          cmp_data)
741 {
742   SortInfo info;
743
744   g_return_if_fail (!is_end (iter));
745
746   info.cmp_func = cmp_func;
747   info.cmp_data = cmp_data;
748   info.end_node = get_sequence (iter)->end_node;
749   check_iter_access (iter);
750
751   g_sequence_sort_changed_iter (iter, iter_compare, &info);
752 }
753
754 /**
755  * g_sequence_search:
756  * @seq: a #GSequence
757  * @data: data for the new item
758  * @cmp_func: the function used to compare items in the sequence
759  * @cmp_data: user data passed to @cmp_func.
760  *
761  * Returns an iterator pointing to the position where @data would
762  * be inserted according to @cmp_func and @cmp_data.
763  *
764  * @cmp_func is called with two items of the @seq and @user_data.
765  * It should return 0 if the items are equal, a negative value if
766  * the first item comes before the second, and a positive value if
767  * the second item comes before the first.
768  *
769  * If you are simply searching for an existing element of the sequence,
770  * consider using g_sequence_lookup().
771  *
772  * Return value: an #GSequenceIter pointing to the position where @data
773  * would have been inserted according to @cmp_func and @cmp_data.
774  *
775  * Since: 2.14
776  **/
777 GSequenceIter *
778 g_sequence_search (GSequence        *seq,
779                    gpointer          data,
780                    GCompareDataFunc  cmp_func,
781                    gpointer          cmp_data)
782 {
783   SortInfo info;
784
785   g_return_val_if_fail (seq != NULL, NULL);
786
787   info.cmp_func = cmp_func;
788   info.cmp_data = cmp_data;
789   info.end_node = seq->end_node;
790   check_seq_access (seq);
791
792   return g_sequence_search_iter (seq, data, iter_compare, &info);
793 }
794
795 /**
796  * g_sequence_lookup:
797  * @seq: a #GSequence
798  * @data: data to lookup
799  * @cmp_func: the function used to compare items in the sequence
800  * @cmp_data: user data passed to @cmp_func.
801  *
802  * Returns an iterator pointing to the position of the first item found
803  * equal to @data according to @cmp_func and @cmp_data. If more than one
804  * item is equal, it is not guaranteed that it is the first which is
805  * returned. In that case, you can use g_sequence_iter_next() and
806  * g_sequence_iter_prev() to get others.
807  *
808  * @cmp_func is called with two items of the @seq and @user_data.
809  * It should return 0 if the items are equal, a negative value if
810  * the first item comes before the second, and a positive value if
811  * the second item comes before the first.
812  *
813  * Return value: an #GSequenceIter pointing to the position of the
814  *     first item found equal to @data according to @cmp_func and @cmp_data.
815  *
816  * Since: 2.28
817  **/
818 GSequenceIter *
819 g_sequence_lookup (GSequence *seq,
820                    gpointer data,
821                    GCompareDataFunc cmp_func,
822                    gpointer cmp_data)
823 {
824   SortInfo info;
825
826   g_return_val_if_fail (seq != NULL, NULL);
827
828   info.cmp_func = cmp_func;
829   info.cmp_data = cmp_data;
830   info.end_node = seq->end_node;
831   check_seq_access (seq);
832
833   return g_sequence_lookup_iter (seq, data, iter_compare, &info);
834 }
835
836 /**
837  * g_sequence_sort_iter:
838  * @seq: a #GSequence
839  * @cmp_func: the function used to compare iterators in the sequence
840  * @cmp_data: user data passed to @cmp_func
841  *
842  * Like g_sequence_sort(), but uses a #GSequenceIterCompareFunc instead
843  * of a GCompareDataFunc as the compare function
844  *
845  * @cmp_func is called with two iterators pointing into @seq. It should
846  * return 0 if the iterators are equal, a negative value if the first
847  * iterator comes before the second, and a positive value if the second
848  * iterator comes before the first.
849  *
850  * Since: 2.14
851  **/
852 void
853 g_sequence_sort_iter (GSequence                *seq,
854                       GSequenceIterCompareFunc  cmp_func,
855                       gpointer                  cmp_data)
856 {
857   GSequence *tmp;
858   GSequenceNode *begin, *end;
859
860   g_return_if_fail (seq != NULL);
861   g_return_if_fail (cmp_func != NULL);
862
863   check_seq_access (seq);
864
865   begin = g_sequence_get_begin_iter (seq);
866   end   = g_sequence_get_end_iter (seq);
867
868   tmp = g_sequence_new (NULL);
869   tmp->real_sequence = seq;
870
871   g_sequence_move_range (g_sequence_get_begin_iter (tmp), begin, end);
872
873   seq->access_prohibited = TRUE;
874   tmp->access_prohibited = TRUE;
875
876   while (g_sequence_get_length (tmp) > 0)
877     {
878       GSequenceNode *node = g_sequence_get_begin_iter (tmp);
879
880       node_insert_sorted (seq->end_node, node, seq->end_node,
881                           cmp_func, cmp_data);
882     }
883
884   tmp->access_prohibited = FALSE;
885   seq->access_prohibited = FALSE;
886
887   g_sequence_free (tmp);
888 }
889
890 /**
891  * g_sequence_sort_changed_iter:
892  * @iter: a #GSequenceIter
893  * @iter_cmp: the function used to compare iterators in the sequence
894  * @cmp_data: user data passed to @cmp_func
895  *
896  * Like g_sequence_sort_changed(), but uses
897  * a #GSequenceIterCompareFunc instead of a #GCompareDataFunc as
898  * the compare function.
899  *
900  * @iter_cmp is called with two iterators pointing into @seq. It should
901  * return 0 if the iterators are equal, a negative value if the first
902  * iterator comes before the second, and a positive value if the second
903  * iterator comes before the first.
904  *
905  * Since: 2.14
906  **/
907 void
908 g_sequence_sort_changed_iter (GSequenceIter            *iter,
909                               GSequenceIterCompareFunc  iter_cmp,
910                               gpointer                  cmp_data)
911 {
912   GSequence *seq, *tmp_seq;
913   GSequenceIter *next, *prev;
914
915   g_return_if_fail (iter != NULL);
916   g_return_if_fail (!is_end (iter));
917   g_return_if_fail (iter_cmp != NULL);
918   check_iter_access (iter);
919
920   /* If one of the neighbours is equal to iter, then
921    * don't move it. This ensures that sort_changed() is
922    * a stable operation.
923    */
924
925   next = node_get_next (iter);
926   prev = node_get_prev (iter);
927
928   if (prev != iter && iter_cmp (prev, iter, cmp_data) == 0)
929     return;
930
931   if (!is_end (next) && iter_cmp (next, iter, cmp_data) == 0)
932     return;
933
934   seq = get_sequence (iter);
935
936   seq->access_prohibited = TRUE;
937
938   tmp_seq = g_sequence_new (NULL);
939   tmp_seq->real_sequence = seq;
940
941   node_unlink (iter);
942   node_insert_before (tmp_seq->end_node, iter);
943
944   node_insert_sorted (seq->end_node, iter, seq->end_node,
945                       iter_cmp, cmp_data);
946
947   g_sequence_free (tmp_seq);
948
949   seq->access_prohibited = FALSE;
950 }
951
952 /**
953  * g_sequence_insert_sorted_iter:
954  * @seq: a #GSequence
955  * @data: data for the new item
956  * @iter_cmp: the function used to compare iterators in the sequence
957  * @cmp_data: user data passed to @cmp_func
958  *
959  * Like g_sequence_insert_sorted(), but uses
960  * a #GSequenceIterCompareFunc instead of a #GCompareDataFunc as
961  * the compare function.
962  *
963  * @iter_cmp is called with two iterators pointing into @seq.
964  * It should return 0 if the iterators are equal, a negative
965  * value if the first iterator comes before the second, and a
966  * positive value if the second iterator comes before the first.
967  *
968  * It is called with two iterators pointing into @seq. It should
969  * return 0 if the iterators are equal, a negative value if the
970  * first iterator comes before the second, and a positive value
971  * if the second iterator comes before the first.
972  *
973  * Return value: a #GSequenceIter pointing to the new item
974  *
975  * Since: 2.14
976  **/
977 GSequenceIter *
978 g_sequence_insert_sorted_iter (GSequence                *seq,
979                                gpointer                  data,
980                                GSequenceIterCompareFunc  iter_cmp,
981                                gpointer                  cmp_data)
982 {
983   GSequenceNode *new_node;
984   GSequence *tmp_seq;
985
986   g_return_val_if_fail (seq != NULL, NULL);
987   g_return_val_if_fail (iter_cmp != NULL, NULL);
988
989   check_seq_access (seq);
990
991   seq->access_prohibited = TRUE;
992
993   /* Create a new temporary sequence and put the new node into
994    * that. The reason for this is that the user compare function
995    * will be called with the new node, and if it dereferences,
996    * "is_end" will be called on it. But that will crash if the
997    * node is not actually in a sequence.
998    *
999    * node_insert_sorted() makes sure the node is unlinked before
1000    * it is inserted.
1001    *
1002    * The reason we need the "iter" versions at all is that that
1003    * is the only kind of compare functions GtkTreeView can use.
1004    */
1005   tmp_seq = g_sequence_new (NULL);
1006   tmp_seq->real_sequence = seq;
1007
1008   new_node = g_sequence_append (tmp_seq, data);
1009
1010   node_insert_sorted (seq->end_node, new_node,
1011                       seq->end_node, iter_cmp, cmp_data);
1012
1013   g_sequence_free (tmp_seq);
1014
1015   seq->access_prohibited = FALSE;
1016
1017   return new_node;
1018 }
1019
1020 /**
1021  * g_sequence_search_iter:
1022  * @seq: a #GSequence
1023  * @data: data for the new item
1024  * @iter_cmp: the function used to compare iterators in the sequence
1025  * @cmp_data: user data passed to @iter_cmp
1026  *
1027  * Like g_sequence_search(), but uses a #GSequenceIterCompareFunc
1028  * instead of a #GCompareDataFunc as the compare function.
1029  *
1030  * @iter_cmp is called with two iterators pointing into @seq.
1031  * It should return 0 if the iterators are equal, a negative value
1032  * if the first iterator comes before the second, and a positive
1033  * value if the second iterator comes before the first.
1034  *
1035  * If you are simply searching for an existing element of the sequence,
1036  * consider using g_sequence_lookup_iter().
1037  *
1038  * Return value: a #GSequenceIter pointing to the position in @seq
1039  *     where @data would have been inserted according to @iter_cmp
1040  *     and @cmp_data.
1041  *
1042  * Since: 2.14
1043  **/
1044 GSequenceIter *
1045 g_sequence_search_iter (GSequence                *seq,
1046                         gpointer                  data,
1047                         GSequenceIterCompareFunc  iter_cmp,
1048                         gpointer                  cmp_data)
1049 {
1050   GSequenceNode *node;
1051   GSequenceNode *dummy;
1052   GSequence *tmp_seq;
1053
1054   g_return_val_if_fail (seq != NULL, NULL);
1055
1056   check_seq_access (seq);
1057
1058   seq->access_prohibited = TRUE;
1059
1060   tmp_seq = g_sequence_new (NULL);
1061   tmp_seq->real_sequence = seq;
1062
1063   dummy = g_sequence_append (tmp_seq, data);
1064
1065   node = node_find_closest (seq->end_node, dummy,
1066                             seq->end_node, iter_cmp, cmp_data);
1067
1068   g_sequence_free (tmp_seq);
1069
1070   seq->access_prohibited = FALSE;
1071
1072   return node;
1073 }
1074
1075 /**
1076  * g_sequence_lookup_iter:
1077  * @seq: a #GSequence
1078  * @data: data to lookup
1079  * @iter_cmp: the function used to compare iterators in the sequence
1080  * @cmp_data: user data passed to @iter_cmp
1081  *
1082  * Like g_sequence_lookup(), but uses a #GSequenceIterCompareFunc
1083  * instead of a #GCompareDataFunc as the compare function.
1084  *
1085  * @iter_cmp is called with two iterators pointing into @seq.
1086  * It should return 0 if the iterators are equal, a negative value
1087  * if the first iterator comes before the second, and a positive
1088  * value if the second iterator comes before the first.
1089  *
1090  * Return value: an #GSequenceIter pointing to the position of
1091  *     the first item found equal to @data according to @cmp_func
1092  *     and @cmp_data.
1093  *
1094  * Since: 2.28
1095  **/
1096 GSequenceIter *
1097 g_sequence_lookup_iter (GSequence *seq,
1098                         gpointer data,
1099                         GSequenceIterCompareFunc iter_cmp,
1100                         gpointer cmp_data)
1101 {
1102   GSequenceNode *node;
1103   GSequenceNode *dummy;
1104   GSequence *tmp_seq;
1105
1106   g_return_val_if_fail (seq != NULL, NULL);
1107
1108   check_seq_access (seq);
1109
1110   seq->access_prohibited = TRUE;
1111
1112   tmp_seq = g_sequence_new (NULL);
1113   tmp_seq->real_sequence = seq;
1114
1115   dummy = g_sequence_append (tmp_seq, data);
1116
1117   node = node_find (seq->end_node, dummy,
1118                     seq->end_node, iter_cmp, cmp_data);
1119
1120   g_sequence_free (tmp_seq);
1121
1122   seq->access_prohibited = FALSE;
1123
1124   return node;
1125 }
1126
1127 /**
1128  * g_sequence_iter_get_sequence:
1129  * @iter: a #GSequenceIter
1130  *
1131  * Returns the #GSequence that @iter points into.
1132  *
1133  * Return value: the #GSequence that @iter points into.
1134  *
1135  * Since: 2.14
1136  **/
1137 GSequence *
1138 g_sequence_iter_get_sequence (GSequenceIter *iter)
1139 {
1140   GSequence *seq;
1141
1142   g_return_val_if_fail (iter != NULL, NULL);
1143
1144   seq = get_sequence (iter);
1145
1146   /* For temporary sequences, this points to the sequence that
1147    * is actually being manipulated
1148    */
1149   return seq->real_sequence;
1150 }
1151
1152 /**
1153  * g_sequence_get:
1154  * @iter: a #GSequenceIter
1155  *
1156  * Returns the data that @iter points to.
1157  *
1158  * Return value: the data that @iter points to
1159  *
1160  * Since: 2.14
1161  **/
1162 gpointer
1163 g_sequence_get (GSequenceIter *iter)
1164 {
1165   g_return_val_if_fail (iter != NULL, NULL);
1166   g_return_val_if_fail (!is_end (iter), NULL);
1167
1168   return iter->data;
1169 }
1170
1171 /**
1172  * g_sequence_set:
1173  * @iter: a #GSequenceIter
1174  * @data: new data for the item
1175  *
1176  * Changes the data for the item pointed to by @iter to be @data. If
1177  * the sequence has a data destroy function associated with it, that
1178  * function is called on the existing data that @iter pointed to.
1179  *
1180  * Since: 2.14
1181  **/
1182 void
1183 g_sequence_set (GSequenceIter *iter,
1184                 gpointer       data)
1185 {
1186   GSequence *seq;
1187
1188   g_return_if_fail (iter != NULL);
1189   g_return_if_fail (!is_end (iter));
1190
1191   seq = get_sequence (iter);
1192
1193   /* If @data is identical to iter->data, it is destroyed
1194    * here. This will work right in case of ref-counted objects. Also
1195    * it is similar to what ghashtables do.
1196    *
1197    * For non-refcounted data it's a little less convenient, but
1198    * code relying on self-setting not destroying would be
1199    * pretty dubious anyway ...
1200    */
1201
1202   if (seq->data_destroy_notify)
1203     seq->data_destroy_notify (iter->data);
1204
1205   iter->data = data;
1206 }
1207
1208 /**
1209  * g_sequence_get_length:
1210  * @seq: a #GSequence
1211  *
1212  * Returns the length of @seq
1213  *
1214  * Return value: the length of @seq
1215  *
1216  * Since: 2.14
1217  **/
1218 gint
1219 g_sequence_get_length (GSequence *seq)
1220 {
1221   return node_get_length (seq->end_node) - 1;
1222 }
1223
1224 /**
1225  * g_sequence_get_end_iter:
1226  * @seq: a #GSequence
1227  *
1228  * Returns the end iterator for @seg
1229  *
1230  * Return value: the end iterator for @seq
1231  *
1232  * Since: 2.14
1233  **/
1234 GSequenceIter *
1235 g_sequence_get_end_iter (GSequence *seq)
1236 {
1237   g_return_val_if_fail (seq != NULL, NULL);
1238
1239   return seq->end_node;
1240 }
1241
1242 /**
1243  * g_sequence_get_begin_iter:
1244  * @seq: a #GSequence
1245  *
1246  * Returns the begin iterator for @seq.
1247  *
1248  * Return value: the begin iterator for @seq.
1249  *
1250  * Since: 2.14
1251  **/
1252 GSequenceIter *
1253 g_sequence_get_begin_iter (GSequence *seq)
1254 {
1255   g_return_val_if_fail (seq != NULL, NULL);
1256
1257   return node_get_first (seq->end_node);
1258 }
1259
1260 static int
1261 clamp_position (GSequence *seq,
1262                 int        pos)
1263 {
1264   gint len = g_sequence_get_length (seq);
1265
1266   if (pos > len || pos < 0)
1267     pos = len;
1268
1269   return pos;
1270 }
1271
1272 /*
1273  * if pos > number of items or -1, will return end pointer
1274  */
1275 /**
1276  * g_sequence_get_iter_at_pos:
1277  * @seq: a #GSequence
1278  * @pos: a position in @seq, or -1 for the end.
1279  *
1280  * Returns the iterator at position @pos. If @pos is negative or larger
1281  * than the number of items in @seq, the end iterator is returned.
1282  *
1283  * Return value: The #GSequenceIter at position @pos
1284  *
1285  * Since: 2.14
1286  **/
1287 GSequenceIter *
1288 g_sequence_get_iter_at_pos (GSequence *seq,
1289                             gint       pos)
1290 {
1291   g_return_val_if_fail (seq != NULL, NULL);
1292
1293   pos = clamp_position (seq, pos);
1294
1295   return node_get_by_pos (seq->end_node, pos);
1296 }
1297
1298 /**
1299  * g_sequence_move:
1300  * @src: a #GSequenceIter pointing to the item to move
1301  * @dest: a #GSequenceIter pointing to the position to which
1302  *        the item is moved.
1303  *
1304  * Moves the item pointed to by @src to the position indicated by @dest.
1305  * After calling this function @dest will point to the position immediately
1306  * after @src. It is allowed for @src and @dest to point into different
1307  * sequences.
1308  *
1309  * Since: 2.14
1310  **/
1311 void
1312 g_sequence_move (GSequenceIter *src,
1313                  GSequenceIter *dest)
1314 {
1315   g_return_if_fail (src != NULL);
1316   g_return_if_fail (dest != NULL);
1317   g_return_if_fail (!is_end (src));
1318
1319   if (src == dest)
1320     return;
1321
1322   node_unlink (src);
1323   node_insert_before (dest, src);
1324 }
1325
1326 /* GSequenceIter */
1327
1328 /**
1329  * g_sequence_iter_is_end:
1330  * @iter: a #GSequenceIter
1331  *
1332  * Returns whether @iter is the end iterator
1333  *
1334  * Return value: Whether @iter is the end iterator.
1335  *
1336  * Since: 2.14
1337  **/
1338 gboolean
1339 g_sequence_iter_is_end (GSequenceIter *iter)
1340 {
1341   g_return_val_if_fail (iter != NULL, FALSE);
1342
1343   return is_end (iter);
1344 }
1345
1346 /**
1347  * g_sequence_iter_is_begin:
1348  * @iter: a #GSequenceIter
1349  *
1350  * Returns whether @iter is the begin iterator
1351  *
1352  * Return value: whether @iter is the begin iterator
1353  *
1354  * Since: 2.14
1355  **/
1356 gboolean
1357 g_sequence_iter_is_begin (GSequenceIter *iter)
1358 {
1359   g_return_val_if_fail (iter != NULL, FALSE);
1360
1361   return (node_get_prev (iter) == iter);
1362 }
1363
1364 /**
1365  * g_sequence_iter_get_position:
1366  * @iter: a #GSequenceIter
1367  *
1368  * Returns the position of @iter
1369  *
1370  * Return value: the position of @iter
1371  *
1372  * Since: 2.14
1373  **/
1374 gint
1375 g_sequence_iter_get_position (GSequenceIter *iter)
1376 {
1377   g_return_val_if_fail (iter != NULL, -1);
1378
1379   return node_get_pos (iter);
1380 }
1381
1382 /**
1383  * g_sequence_iter_next:
1384  * @iter: a #GSequenceIter
1385  *
1386  * Returns an iterator pointing to the next position after @iter. If
1387  * @iter is the end iterator, the end iterator is returned.
1388  *
1389  * Return value: a #GSequenceIter pointing to the next position after @iter.
1390  *
1391  * Since: 2.14
1392  **/
1393 GSequenceIter *
1394 g_sequence_iter_next (GSequenceIter *iter)
1395 {
1396   g_return_val_if_fail (iter != NULL, NULL);
1397
1398   return node_get_next (iter);
1399 }
1400
1401 /**
1402  * g_sequence_iter_prev:
1403  * @iter: a #GSequenceIter
1404  *
1405  * Returns an iterator pointing to the previous position before @iter. If
1406  * @iter is the begin iterator, the begin iterator is returned.
1407  *
1408  * Return value: a #GSequenceIter pointing to the previous position before
1409  * @iter.
1410  *
1411  * Since: 2.14
1412  **/
1413 GSequenceIter *
1414 g_sequence_iter_prev (GSequenceIter *iter)
1415 {
1416   g_return_val_if_fail (iter != NULL, NULL);
1417
1418   return node_get_prev (iter);
1419 }
1420
1421 /**
1422  * g_sequence_iter_move:
1423  * @iter: a #GSequenceIter
1424  * @delta: A positive or negative number indicating how many positions away
1425  *    from @iter the returned #GSequenceIter will be.
1426  *
1427  * Returns the #GSequenceIter which is @delta positions away from @iter.
1428  * If @iter is closer than -@delta positions to the beginning of the sequence,
1429  * the begin iterator is returned. If @iter is closer than @delta positions
1430  * to the end of the sequence, the end iterator is returned.
1431  *
1432  * Return value: a #GSequenceIter which is @delta positions away from @iter.
1433  *
1434  * Since: 2.14
1435  **/
1436 GSequenceIter *
1437 g_sequence_iter_move (GSequenceIter *iter,
1438                       gint           delta)
1439 {
1440   gint new_pos;
1441   gint len;
1442
1443   g_return_val_if_fail (iter != NULL, NULL);
1444
1445   len = g_sequence_get_length (get_sequence (iter));
1446
1447   new_pos = node_get_pos (iter) + delta;
1448
1449   if (new_pos < 0)
1450     new_pos = 0;
1451   else if (new_pos > len)
1452     new_pos = len;
1453
1454   return node_get_by_pos (iter, new_pos);
1455 }
1456
1457 /**
1458  * g_sequence_swap:
1459  * @a: a #GSequenceIter
1460  * @b: a #GSequenceIter
1461  *
1462  * Swaps the items pointed to by @a and @b. It is allowed for @a and @b
1463  * to point into difference sequences.
1464  *
1465  * Since: 2.14
1466  **/
1467 void
1468 g_sequence_swap (GSequenceIter *a,
1469                  GSequenceIter *b)
1470 {
1471   GSequenceNode *leftmost, *rightmost, *rightmost_next;
1472   int a_pos, b_pos;
1473
1474   g_return_if_fail (!g_sequence_iter_is_end (a));
1475   g_return_if_fail (!g_sequence_iter_is_end (b));
1476
1477   if (a == b)
1478     return;
1479
1480   a_pos = g_sequence_iter_get_position (a);
1481   b_pos = g_sequence_iter_get_position (b);
1482
1483   if (a_pos > b_pos)
1484     {
1485       leftmost = b;
1486       rightmost = a;
1487     }
1488   else
1489     {
1490       leftmost = a;
1491       rightmost = b;
1492     }
1493
1494   rightmost_next = node_get_next (rightmost);
1495
1496   /* The situation is now like this:
1497    *
1498    *     ..., leftmost, ......., rightmost, rightmost_next, ...
1499    *
1500    */
1501   g_sequence_move (rightmost, leftmost);
1502   g_sequence_move (leftmost, rightmost_next);
1503 }
1504
1505 /*
1506  * Implementation of a treap
1507  *
1508  *
1509  */
1510 static guint
1511 get_priority (GSequenceNode *node)
1512 {
1513   guint key = GPOINTER_TO_UINT (node);
1514
1515   /* This hash function is based on one found on Thomas Wang's
1516    * web page at
1517    *
1518    *    http://www.concentric.net/~Ttwang/tech/inthash.htm
1519    *
1520    */
1521   key = (key << 15) - key - 1;
1522   key = key ^ (key >> 12);
1523   key = key + (key << 2);
1524   key = key ^ (key >> 4);
1525   key = key + (key << 3) + (key << 11);
1526   key = key ^ (key >> 16);
1527
1528   /* We rely on 0 being less than all other priorities */
1529   return key? key : 1;
1530 }
1531
1532 static GSequenceNode *
1533 find_root (GSequenceNode *node)
1534 {
1535   while (node->parent)
1536     node = node->parent;
1537
1538   return node;
1539 }
1540
1541 static GSequenceNode *
1542 node_new (gpointer data)
1543 {
1544   GSequenceNode *node = g_slice_new0 (GSequenceNode);
1545
1546   node->n_nodes = 1;
1547   node->data = data;
1548   node->left = NULL;
1549   node->right = NULL;
1550   node->parent = NULL;
1551
1552   return node;
1553 }
1554
1555 static GSequenceNode *
1556 node_get_first (GSequenceNode *node)
1557 {
1558   node = find_root (node);
1559
1560   while (node->left)
1561     node = node->left;
1562
1563   return node;
1564 }
1565
1566 static GSequenceNode *
1567 node_get_last (GSequenceNode *node)
1568 {
1569   node = find_root (node);
1570
1571   while (node->right)
1572     node = node->right;
1573
1574   return node;
1575 }
1576
1577 #define NODE_LEFT_CHILD(n)  (((n)->parent) && ((n)->parent->left) == (n))
1578 #define NODE_RIGHT_CHILD(n) (((n)->parent) && ((n)->parent->right) == (n))
1579
1580 static GSequenceNode *
1581 node_get_next (GSequenceNode *node)
1582 {
1583   GSequenceNode *n = node;
1584
1585   if (n->right)
1586     {
1587       n = n->right;
1588       while (n->left)
1589         n = n->left;
1590     }
1591   else
1592     {
1593       while (NODE_RIGHT_CHILD (n))
1594         n = n->parent;
1595
1596       if (n->parent)
1597         n = n->parent;
1598       else
1599         n = node;
1600     }
1601
1602   return n;
1603 }
1604
1605 static GSequenceNode *
1606 node_get_prev (GSequenceNode *node)
1607 {
1608   GSequenceNode *n = node;
1609
1610   if (n->left)
1611     {
1612       n = n->left;
1613       while (n->right)
1614         n = n->right;
1615     }
1616   else
1617     {
1618       while (NODE_LEFT_CHILD (n))
1619         n = n->parent;
1620
1621       if (n->parent)
1622         n = n->parent;
1623       else
1624         n = node;
1625     }
1626
1627   return n;
1628 }
1629
1630 #define N_NODES(n) ((n)? (n)->n_nodes : 0)
1631
1632 static gint
1633 node_get_pos (GSequenceNode *node)
1634 {
1635   int n_smaller = 0;
1636
1637   if (node->left)
1638     n_smaller = node->left->n_nodes;
1639
1640   while (node)
1641     {
1642       if (NODE_RIGHT_CHILD (node))
1643         n_smaller += N_NODES (node->parent->left) + 1;
1644
1645       node = node->parent;
1646     }
1647
1648   return n_smaller;
1649 }
1650
1651 static GSequenceNode *
1652 node_get_by_pos (GSequenceNode *node,
1653                  gint           pos)
1654 {
1655   int i;
1656
1657   node = find_root (node);
1658
1659   while ((i = N_NODES (node->left)) != pos)
1660     {
1661       if (i < pos)
1662         {
1663           node = node->right;
1664           pos -= (i + 1);
1665         }
1666       else
1667         {
1668           node = node->left;
1669         }
1670     }
1671
1672   return node;
1673 }
1674
1675 static GSequenceNode *
1676 node_find (GSequenceNode            *haystack,
1677            GSequenceNode            *needle,
1678            GSequenceNode            *end,
1679            GSequenceIterCompareFunc  iter_cmp,
1680            gpointer                  cmp_data)
1681 {
1682   gint c;
1683
1684   haystack = find_root (haystack);
1685
1686   do
1687     {
1688       /* iter_cmp can't be passed the end node, since the function may
1689        * be user-supplied
1690        */
1691       if (haystack == end)
1692         c = 1;
1693       else
1694         c = iter_cmp (haystack, needle, cmp_data);
1695
1696       if (c == 0)
1697         break;
1698
1699       if (c > 0)
1700         haystack = haystack->left;
1701       else
1702         haystack = haystack->right;
1703     }
1704   while (haystack != NULL);
1705
1706   return haystack;
1707 }
1708
1709 static GSequenceNode *
1710 node_find_closest (GSequenceNode            *haystack,
1711                    GSequenceNode            *needle,
1712                    GSequenceNode            *end,
1713                    GSequenceIterCompareFunc  iter_cmp,
1714                    gpointer                  cmp_data)
1715 {
1716   GSequenceNode *best;
1717   gint c;
1718
1719   haystack = find_root (haystack);
1720
1721   do
1722     {
1723       best = haystack;
1724
1725       /* iter_cmp can't be passed the end node, since the function may
1726        * be user-supplied
1727        */
1728       if (haystack == end)
1729         c = 1;
1730       else
1731         c = iter_cmp (haystack, needle, cmp_data);
1732
1733       /* In the following we don't break even if c == 0. Instead we go on
1734        * searching along the 'bigger' nodes, so that we find the last one
1735        * that is equal to the needle.
1736        */
1737       if (c > 0)
1738         haystack = haystack->left;
1739       else
1740         haystack = haystack->right;
1741     }
1742   while (haystack != NULL);
1743
1744   /* If the best node is smaller or equal to the data, then move one step
1745    * to the right to make sure the best one is strictly bigger than the data
1746    */
1747   if (best != end && c <= 0)
1748     best = node_get_next (best);
1749
1750   return best;
1751 }
1752
1753 static gint
1754 node_get_length    (GSequenceNode            *node)
1755 {
1756   node = find_root (node);
1757
1758   return node->n_nodes;
1759 }
1760
1761 static void
1762 real_node_free (GSequenceNode *node,
1763                 GSequence     *seq)
1764 {
1765   if (node)
1766     {
1767       real_node_free (node->left, seq);
1768       real_node_free (node->right, seq);
1769
1770       if (seq && seq->data_destroy_notify && node != seq->end_node)
1771         seq->data_destroy_notify (node->data);
1772
1773       g_slice_free (GSequenceNode, node);
1774     }
1775 }
1776
1777 static void
1778 node_free (GSequenceNode *node,
1779            GSequence *seq)
1780 {
1781   node = find_root (node);
1782
1783   real_node_free (node, seq);
1784 }
1785
1786 static void
1787 node_update_fields (GSequenceNode *node)
1788 {
1789   int n_nodes = 1;
1790
1791   n_nodes += N_NODES (node->left);
1792   n_nodes += N_NODES (node->right);
1793
1794   node->n_nodes = n_nodes;
1795 }
1796
1797 static void
1798 node_rotate (GSequenceNode *node)
1799 {
1800   GSequenceNode *tmp, *old;
1801
1802   g_assert (node->parent);
1803   g_assert (node->parent != node);
1804
1805   if (NODE_LEFT_CHILD (node))
1806     {
1807       /* rotate right */
1808       tmp = node->right;
1809
1810       node->right = node->parent;
1811       node->parent = node->parent->parent;
1812       if (node->parent)
1813         {
1814           if (node->parent->left == node->right)
1815             node->parent->left = node;
1816           else
1817             node->parent->right = node;
1818         }
1819
1820       g_assert (node->right);
1821
1822       node->right->parent = node;
1823       node->right->left = tmp;
1824
1825       if (node->right->left)
1826         node->right->left->parent = node->right;
1827
1828       old = node->right;
1829     }
1830   else
1831     {
1832       /* rotate left */
1833       tmp = node->left;
1834
1835       node->left = node->parent;
1836       node->parent = node->parent->parent;
1837       if (node->parent)
1838         {
1839           if (node->parent->right == node->left)
1840             node->parent->right = node;
1841           else
1842             node->parent->left = node;
1843         }
1844
1845       g_assert (node->left);
1846
1847       node->left->parent = node;
1848       node->left->right = tmp;
1849
1850       if (node->left->right)
1851         node->left->right->parent = node->left;
1852
1853       old = node->left;
1854     }
1855
1856   node_update_fields (old);
1857   node_update_fields (node);
1858 }
1859
1860 static void
1861 node_update_fields_deep (GSequenceNode *node)
1862 {
1863   if (node)
1864     {
1865       node_update_fields (node);
1866
1867       node_update_fields_deep (node->parent);
1868     }
1869 }
1870
1871 static void
1872 rotate_down (GSequenceNode *node,
1873              guint          priority)
1874 {
1875   guint left, right;
1876
1877   left = node->left ? get_priority (node->left)  : 0;
1878   right = node->right ? get_priority (node->right) : 0;
1879
1880   while (priority < left || priority < right)
1881     {
1882       if (left > right)
1883         node_rotate (node->left);
1884       else
1885         node_rotate (node->right);
1886
1887       left = node->left ? get_priority (node->left)  : 0;
1888       right = node->right ? get_priority (node->right) : 0;
1889     }
1890 }
1891
1892 static void
1893 node_cut (GSequenceNode *node)
1894 {
1895   while (node->parent)
1896     node_rotate (node);
1897
1898   if (node->left)
1899     node->left->parent = NULL;
1900
1901   node->left = NULL;
1902   node_update_fields (node);
1903
1904   rotate_down (node, get_priority (node));
1905 }
1906
1907 static void
1908 node_join (GSequenceNode *left,
1909            GSequenceNode *right)
1910 {
1911   GSequenceNode *fake = node_new (NULL);
1912
1913   fake->left = find_root (left);
1914   fake->right = find_root (right);
1915   fake->left->parent = fake;
1916   fake->right->parent = fake;
1917
1918   node_update_fields (fake);
1919
1920   node_unlink (fake);
1921
1922   node_free (fake, NULL);
1923 }
1924
1925 static void
1926 node_insert_before (GSequenceNode *node,
1927                     GSequenceNode *new)
1928 {
1929   new->left = node->left;
1930   if (new->left)
1931     new->left->parent = new;
1932
1933   new->parent = node;
1934   node->left = new;
1935
1936   node_update_fields_deep (new);
1937
1938   while (new->parent && get_priority (new) > get_priority (new->parent))
1939     node_rotate (new);
1940
1941   rotate_down (new, get_priority (new));
1942 }
1943
1944 static void
1945 node_unlink (GSequenceNode *node)
1946 {
1947   rotate_down (node, 0);
1948
1949   if (NODE_RIGHT_CHILD (node))
1950     node->parent->right = NULL;
1951   else if (NODE_LEFT_CHILD (node))
1952     node->parent->left = NULL;
1953
1954   if (node->parent)
1955     node_update_fields_deep (node->parent);
1956
1957   node->parent = NULL;
1958 }
1959
1960 static void
1961 node_insert_sorted (GSequenceNode            *node,
1962                     GSequenceNode            *new,
1963                     GSequenceNode            *end,
1964                     GSequenceIterCompareFunc  iter_cmp,
1965                     gpointer                  cmp_data)
1966 {
1967   GSequenceNode *closest;
1968
1969   closest = node_find_closest (node, new, end, iter_cmp, cmp_data);
1970
1971   node_unlink (new);
1972
1973   node_insert_before (closest, new);
1974 }