]> git.ozlabs.org Git - ccan/blob - ccan/asort/asort.c
alloc: avoid arithmetic on void pointers.
[ccan] / ccan / asort / asort.c
1 #include <ccan/asort/asort.h>
2 #include <stdlib.h>
3
4 #if HAVE_NESTED_FUNCTIONS
5 void _asort(void *base, size_t nmemb, size_t size,
6             int(*compar)(const void *, const void *, void *ctx),
7             void *ctx)
8 {
9         /* This gives bogus "warning: no previous prototype for ‘cmp’"
10          * with gcc 4 with -Wmissing-prototypes.  Hence the auto crap. */
11         auto int cmp(const void *a, const void *b);
12         int cmp(const void *a, const void *b)
13         {
14                 return compar(a, b, ctx);
15         }
16         qsort(base, nmemb, size, cmp);
17 }
18 #else
19 /* Steal glibc's code. */
20
21 /* Copyright (C) 1991,1992,1996,1997,1999,2004 Free Software Foundation, Inc.
22    This file is part of the GNU C Library.
23    Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
24
25    The GNU C Library is free software; you can redistribute it and/or
26    modify it under the terms of the GNU Lesser General Public
27    License as published by the Free Software Foundation; either
28    version 2.1 of the License, or (at your option) any later version.
29
30    The GNU C Library is distributed in the hope that it will be useful,
31    but WITHOUT ANY WARRANTY; without even the implied warranty of
32    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
33    Lesser General Public License for more details.
34
35    You should have received a copy of the GNU Lesser General Public
36    License along with the GNU C Library; if not, write to the Free
37    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
38    02111-1307 USA.  */
39
40 /* If you consider tuning this algorithm, you should consult first:
41    Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
42    Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993.  */
43
44 #include <limits.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 /* Byte-wise swap two items of size SIZE. */
49 #define SWAP(a, b, size)                                                      \
50   do                                                                          \
51     {                                                                         \
52       register size_t __size = (size);                                        \
53       register char *__a = (a), *__b = (b);                                   \
54       do                                                                      \
55         {                                                                     \
56           char __tmp = *__a;                                                  \
57           *__a++ = *__b;                                                      \
58           *__b++ = __tmp;                                                     \
59         } while (--__size > 0);                                               \
60     } while (0)
61
62 /* Discontinue quicksort algorithm when partition gets below this size.
63    This particular magic number was chosen to work best on a Sun 4/260. */
64 #define MAX_THRESH 4
65
66 /* Stack node declarations used to store unfulfilled partition obligations. */
67 typedef struct
68   {
69     char *lo;
70     char *hi;
71   } stack_node;
72
73 /* The next 4 #defines implement a very fast in-line stack abstraction. */
74 /* The stack needs log (total_elements) entries (we could even subtract
75    log(MAX_THRESH)).  Since total_elements has type size_t, we get as
76    upper bound for log (total_elements):
77    bits per byte (CHAR_BIT) * sizeof(size_t).  */
78 #define STACK_SIZE      (CHAR_BIT * sizeof(size_t))
79 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
80 #define POP(low, high)  ((void) (--top, (low = top->lo), (high = top->hi)))
81 #define STACK_NOT_EMPTY (stack < top)
82
83
84 /* Order size using quicksort.  This implementation incorporates
85    four optimizations discussed in Sedgewick:
86
87    1. Non-recursive, using an explicit stack of pointer that store the
88       next array partition to sort.  To save time, this maximum amount
89       of space required to store an array of SIZE_MAX is allocated on the
90       stack.  Assuming a 32-bit (64 bit) integer for size_t, this needs
91       only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
92       Pretty cheap, actually.
93
94    2. Chose the pivot element using a median-of-three decision tree.
95       This reduces the probability of selecting a bad pivot value and
96       eliminates certain extraneous comparisons.
97
98    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
99       insertion sort to order the MAX_THRESH items within each partition.
100       This is a big win, since insertion sort is faster for small, mostly
101       sorted array segments.
102
103    4. The larger of the two sub-partitions is always pushed onto the
104       stack first, with the algorithm then concentrating on the
105       smaller partition.  This *guarantees* no more than log (total_elems)
106       stack size is needed (actually O(1) in this case)!  */
107
108 void
109 _asort (void *const pbase, size_t total_elems, size_t size,
110         int(*cmp)(const void *, const void *, void *arg),
111         void *arg)
112 {
113   register char *base_ptr = (char *) pbase;
114
115   const size_t max_thresh = MAX_THRESH * size;
116
117   if (total_elems == 0)
118     /* Avoid lossage with unsigned arithmetic below.  */
119     return;
120
121   if (total_elems > MAX_THRESH)
122     {
123       char *lo = base_ptr;
124       char *hi = &lo[size * (total_elems - 1)];
125       stack_node stack[STACK_SIZE];
126       stack_node *top = stack;
127
128       PUSH (NULL, NULL);
129
130       while (STACK_NOT_EMPTY)
131         {
132           char *left_ptr;
133           char *right_ptr;
134
135           /* Select median value from among LO, MID, and HI. Rearrange
136              LO and HI so the three values are sorted. This lowers the
137              probability of picking a pathological pivot value and
138              skips a comparison for both the LEFT_PTR and RIGHT_PTR in
139              the while loops. */
140
141           char *mid = lo + size * ((hi - lo) / size >> 1);
142
143           if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
144             SWAP (mid, lo, size);
145           if ((*cmp) ((void *) hi, (void *) mid, arg) < 0)
146             SWAP (mid, hi, size);
147           else
148             goto jump_over;
149           if ((*cmp) ((void *) mid, (void *) lo, arg) < 0)
150             SWAP (mid, lo, size);
151         jump_over:;
152
153           left_ptr  = lo + size;
154           right_ptr = hi - size;
155
156           /* Here's the famous ``collapse the walls'' section of quicksort.
157              Gotta like those tight inner loops!  They are the main reason
158              that this algorithm runs much faster than others. */
159           do
160             {
161               while ((*cmp) ((void *) left_ptr, (void *) mid, arg) < 0)
162                 left_ptr += size;
163
164               while ((*cmp) ((void *) mid, (void *) right_ptr, arg) < 0)
165                 right_ptr -= size;
166
167               if (left_ptr < right_ptr)
168                 {
169                   SWAP (left_ptr, right_ptr, size);
170                   if (mid == left_ptr)
171                     mid = right_ptr;
172                   else if (mid == right_ptr)
173                     mid = left_ptr;
174                   left_ptr += size;
175                   right_ptr -= size;
176                 }
177               else if (left_ptr == right_ptr)
178                 {
179                   left_ptr += size;
180                   right_ptr -= size;
181                   break;
182                 }
183             }
184           while (left_ptr <= right_ptr);
185
186           /* Set up pointers for next iteration.  First determine whether
187              left and right partitions are below the threshold size.  If so,
188              ignore one or both.  Otherwise, push the larger partition's
189              bounds on the stack and continue sorting the smaller one. */
190
191           if ((size_t) (right_ptr - lo) <= max_thresh)
192             {
193               if ((size_t) (hi - left_ptr) <= max_thresh)
194                 /* Ignore both small partitions. */
195                 POP (lo, hi);
196               else
197                 /* Ignore small left partition. */
198                 lo = left_ptr;
199             }
200           else if ((size_t) (hi - left_ptr) <= max_thresh)
201             /* Ignore small right partition. */
202             hi = right_ptr;
203           else if ((right_ptr - lo) > (hi - left_ptr))
204             {
205               /* Push larger left partition indices. */
206               PUSH (lo, right_ptr);
207               lo = left_ptr;
208             }
209           else
210             {
211               /* Push larger right partition indices. */
212               PUSH (left_ptr, hi);
213               hi = right_ptr;
214             }
215         }
216     }
217
218   /* Once the BASE_PTR array is partially sorted by quicksort the rest
219      is completely sorted using insertion sort, since this is efficient
220      for partitions below MAX_THRESH size. BASE_PTR points to the beginning
221      of the array to sort, and END_PTR points at the very last element in
222      the array (*not* one beyond it!). */
223
224 #define min(x, y) ((x) < (y) ? (x) : (y))
225
226   {
227     char *const end_ptr = &base_ptr[size * (total_elems - 1)];
228     char *tmp_ptr = base_ptr;
229     char *thresh = min(end_ptr, base_ptr + max_thresh);
230     register char *run_ptr;
231
232     /* Find smallest element in first threshold and place it at the
233        array's beginning.  This is the smallest array element,
234        and the operation speeds up insertion sort's inner loop. */
235
236     for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
237       if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
238         tmp_ptr = run_ptr;
239
240     if (tmp_ptr != base_ptr)
241       SWAP (tmp_ptr, base_ptr, size);
242
243     /* Insertion sort, running from left-hand-side up to right-hand-side.  */
244
245     run_ptr = base_ptr + size;
246     while ((run_ptr += size) <= end_ptr)
247       {
248         tmp_ptr = run_ptr - size;
249         while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, arg) < 0)
250           tmp_ptr -= size;
251
252         tmp_ptr += size;
253         if (tmp_ptr != run_ptr)
254           {
255             char *trav;
256
257             trav = run_ptr + size;
258             while (--trav >= run_ptr)
259               {
260                 char c = *trav;
261                 char *hi, *lo;
262
263                 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
264                   *hi = *lo;
265                 *hi = c;
266               }
267           }
268       }
269   }
270 }
271 #endif /* !HAVE_NESTED_FUNCTIONS */