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