Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #include <csort.h>
26 : #include <internal/csortimpl.h>
27 : #include <internal/test_helpers/csortimpl.h>
28 : #include <math.h>
29 : #include <stdint.h>
30 : #include <stdlib.h>
31 : #include <string.h>
32 :
33 : // Compares two stored string pointers with strcmp(). It's the default
34 : // comparator that csort_get_default_comparison_proc() gives for char *
35 : // elements. first and second are the addresses of the stored pointers. NULL is
36 : // part of the char * element type (argv-style lists, a cvec_find() with a NULL
37 : // needle), so every NULL equals every other NULL and sorts below every string;
38 : // the merge needs a real total order, as the NaN rule below does.
39 123 : int csort__default_string_comparison_proc(const void *first,
40 : const void *second) {
41 123 : const char *s1;
42 123 : const char *s2;
43 123 : memcpy(&s1, first, sizeof(s1));
44 123 : memcpy(&s2, second, sizeof(s2));
45 123 : if (!s1 || !s2) {
46 22 : return (s1 != NULL) - (s2 != NULL);
47 : }
48 101 : return strcmp(s1, s2);
49 : }
50 :
51 : // Defines the default comparator of an integer type. The operands are read with
52 : // memcpy because a getter can hand over an address with neither the alignment
53 : // nor the effective type of the element; a constant-size memcpy is one load. (a
54 : // > b) - (a < b) gives -1, 0 or 1 with no overflow at the edge values.
55 : #define csort__define_default_integral_comparison_proc(type, name) \
56 : int csort__default_cmp(name)(const void *first, const void *second) { \
57 : type v1; \
58 : type v2; \
59 : memcpy(&v1, first, sizeof(v1)); \
60 : memcpy(&v2, second, sizeof(v2)); \
61 : return (v1 > v2) - (v1 < v2); \
62 : }
63 :
64 114282 : csort__define_default_integral_comparison_proc(char, char);
65 19 : csort__define_default_integral_comparison_proc(signed char, signed_char);
66 111587 : csort__define_default_integral_comparison_proc(short, short);
67 124358 : csort__define_default_integral_comparison_proc(int, int);
68 47 : csort__define_default_integral_comparison_proc(long, long);
69 114151 : csort__define_default_integral_comparison_proc(long long, long_long);
70 26 : csort__define_default_integral_comparison_proc(unsigned char, unsigned_char);
71 28 : csort__define_default_integral_comparison_proc(unsigned short, unsigned_short);
72 34 : csort__define_default_integral_comparison_proc(unsigned int, unsigned_int);
73 28 : csort__define_default_integral_comparison_proc(unsigned long, unsigned_long);
74 31 : csort__define_default_integral_comparison_proc(unsigned long long,
75 : unsigned_long_long);
76 : #undef csort__define_default_integral_comparison_proc
77 :
78 : // Compares two bool values, false before true; the default comparator for bool.
79 : // It's written out because before C23 bool is a macro and would expand inside
80 : // the name the macro above builds.
81 22 : int csort__default_bool_comparison_proc(const void *first, const void *second) {
82 22 : _Bool v1;
83 22 : _Bool v2;
84 22 : memcpy(&v1, first, sizeof(v1));
85 22 : memcpy(&v2, second, sizeof(v2));
86 22 : return (v1 > v2) - (v1 < v2);
87 : }
88 :
89 : // Defines the default comparator of a floating type. NaN is greater than every
90 : // other value and equal only to NaN. A plain (a > b) - (a < b) calls NaN equal
91 : // to everything, so a merge step picks a side from that answer and the real
92 : // values around the NaN come out unsorted ({9, NaN, 1, 4, NaN, 2, 7} gives {1,
93 : // 4, 9, NaN, NaN, 2, 7}). isnan() is type-generic, so one macro serves all
94 : // three types.
95 : #define csort__define_default_float_comparison_proc(type, name) \
96 : int csort__default_cmp(name)(const void *first, const void *second) { \
97 : type v1; \
98 : type v2; \
99 : memcpy(&v1, first, sizeof(v1)); \
100 : memcpy(&v2, second, sizeof(v2)); \
101 : bool nan1 = isnan(v1); \
102 : bool nan2 = isnan(v2); \
103 : if (nan1 || nan2) { \
104 : return nan1 == nan2 ? 0 : (nan1 ? 1 : -1); \
105 : } \
106 : return (v1 > v2) - (v1 < v2); \
107 : }
108 :
109 54 : csort__define_default_float_comparison_proc(float, float);
110 111827 : csort__define_default_float_comparison_proc(double, double);
111 109677 : csort__define_default_float_comparison_proc(long double, long_double);
112 : #undef csort__define_default_float_comparison_proc
113 :
114 : // Merges the sorted runs [left, mid] and [mid + 1, right] of col, for the
115 : // getter-based mergesort. Both runs are copied into temp_buffer, then merged
116 : // back through getter_proc. Taking the left element on a tie keeps the sort
117 : // stable. The procs are never NULL here; csort__merge_sort() checks them.
118 36679 : static void csort_merge(void *col, size_t left, size_t mid, size_t right,
119 : size_t elem_size, csort_item_getter_proc getter_proc,
120 : ccol_comparison_proc comparison_proc,
121 : void *temp_buffer) {
122 36679 : size_t i, j, k;
123 36679 : size_t n1 = mid - left + 1;
124 36679 : size_t n2 = right - mid;
125 :
126 276114 : for (i = 0; i < n1; i++) {
127 239435 : void *src = getter_proc(col, left + i);
128 239435 : void *dst = (unsigned char *)temp_buffer + i * elem_size;
129 239435 : memcpy(dst, src, elem_size);
130 : }
131 :
132 246065 : for (j = 0; j < n2; j++) {
133 209386 : void *src = getter_proc(col, mid + 1 + j);
134 209386 : void *dst = (unsigned char *)temp_buffer + (n1 + j) * elem_size;
135 209386 : memcpy(dst, src, elem_size);
136 : }
137 :
138 : i = 0;
139 : j = n1;
140 : k = left;
141 :
142 427014 : while (i < n1 && j < n1 + n2) {
143 390335 : void *elem_i = (unsigned char *)temp_buffer + i * elem_size;
144 390335 : void *elem_j = (unsigned char *)temp_buffer + j * elem_size;
145 390335 : void *dst = getter_proc(col, k);
146 :
147 390335 : if (comparison_proc(elem_i, elem_j) <= 0) {
148 211507 : memcpy(dst, elem_i, elem_size);
149 211507 : i++;
150 : } else {
151 178828 : memcpy(dst, elem_j, elem_size);
152 178828 : j++;
153 : }
154 390335 : k++;
155 : }
156 :
157 64607 : while (i < n1) {
158 27928 : void *src = (unsigned char *)temp_buffer + i * elem_size;
159 27928 : void *dst = getter_proc(col, k);
160 27928 : memcpy(dst, src, elem_size);
161 27928 : i++;
162 27928 : k++;
163 : }
164 :
165 67237 : while (j < n1 + n2) {
166 30558 : void *src = (unsigned char *)temp_buffer + j * elem_size;
167 30558 : void *dst = getter_proc(col, k);
168 30558 : memcpy(dst, src, elem_size);
169 30558 : j++;
170 30558 : k++;
171 : }
172 36679 : }
173 :
174 : // What csort_check_sort_shape() tells a driver: Allocate and sort, return true
175 : // with nothing to do, or return false.
176 : typedef enum {
177 : csort_buffer_ready,
178 : csort_buffer_not_needed,
179 : csort_buffer_refused
180 : } csort_buffer_outcome;
181 :
182 : // Decides whether a sort of length elements of elem_size bytes may allocate its
183 : // buffer and run. Both drivers call it, so they apply the same limits. A length
184 : // above ccol_max_elem_count is refused, because the doubling run size would
185 : // overflow to 0 and the passes would never end (the overflow guard can't catch
186 : // that when elem_size is 1). An elem_size of 0 needs no buffer and is a
187 : // success, since malloc(0) may give NULL and read as "out of memory". length *
188 : // elem_size must not overflow, or the passes write past a short buffer. An
189 : // incomplete mprocs is refused here, right before the only allocation, so it
190 : // can't change the result of a call that never allocates.
191 : static inline __attribute__((always_inline)) csort_buffer_outcome
192 194 : csort_check_sort_shape(size_t length, size_t elem_size,
193 : ccol_memmgmt_procs *mprocs) {
194 194 : if (length > ccol_max_elem_count) {
195 : return csort_buffer_refused;
196 : }
197 :
198 192 : if (elem_size == 0) {
199 : return csort_buffer_not_needed;
200 : }
201 :
202 190 : if (length > SIZE_MAX / elem_size) {
203 : return csort_buffer_refused;
204 : }
205 :
206 189 : if (!ccol__verify_memmgmt_procs(mprocs, (char **)NULL)) {
207 : return csort_buffer_refused;
208 : }
209 :
210 : return csort_buffer_ready;
211 : }
212 :
213 : // Sorts the range [low, high] of col with the bottom-up mergesort; it's the
214 : // body of csort__merge_sort(). Runs of size 1, 2, 4 and so on are merged in
215 : // pairs through one buffer of length * elem_size. Gives false when the shape is
216 : // refused or the allocation fails, before any merge, so the collection is
217 : // unchanged.
218 71 : static bool csort_mergesort_iterative(void *col, size_t low, size_t high,
219 : size_t elem_size,
220 : csort_item_getter_proc getter_proc,
221 : ccol_comparison_proc comparison_proc,
222 : ccol_memmgmt_procs *mprocs) {
223 71 : if (low >= high) {
224 : return true;
225 : }
226 :
227 71 : size_t length = high - low + 1;
228 :
229 71 : csort_buffer_outcome outcome =
230 71 : csort_check_sort_shape(length, elem_size, mprocs);
231 : if (outcome != csort_buffer_ready) {
232 9 : return outcome == csort_buffer_not_needed;
233 : }
234 :
235 62 : void *temp_buffer = ccol__mem_alloc(mprocs, length * elem_size);
236 62 : if (!temp_buffer) {
237 : return false;
238 : }
239 :
240 394 : for (size_t curr_size = 1; curr_size < length; curr_size *= 2) {
241 37012 : for (size_t left_start = low; left_start <= high;
242 36679 : left_start += 2 * curr_size) {
243 36849 : size_t mid = left_start + curr_size - 1;
244 :
245 36849 : if (mid >= high) {
246 : break;
247 : }
248 :
249 36679 : size_t right_end = left_start + 2 * curr_size - 1;
250 36679 : if (right_end > high) {
251 : right_end = high;
252 : }
253 :
254 36679 : csort_merge(col, left_start, mid, right_end, elem_size, getter_proc,
255 : comparison_proc, temp_buffer);
256 : }
257 : }
258 :
259 61 : ccol__mem_free(mprocs, temp_buffer);
260 : return true;
261 : }
262 :
263 : #ifdef RUNNING_UNIT_TESTS
264 : // Counts the contiguous sorts that allocated a buffer, for the tests.
265 : static _Atomic unsigned long long g_csort_contiguous_sorts_for_tests = 0;
266 : // Gives the counter above, so the vector tests can prove that cvec_sort takes
267 : // the contiguous path.
268 142 : unsigned long long csort__contiguous_sorts_for_tests(void) {
269 142 : return g_csort_contiguous_sorts_for_tests;
270 : }
271 : #endif
272 :
273 : // Merges the runs [left, mid] and [mid + 1, right] of a contiguous array, for
274 : // the contiguous sort. Only the left run is copied out. The write position
275 : // trails the read position of the right run by the number of left elements not
276 : // merged yet, so it never overtakes it, and when the left run is used up the
277 : // rest of the right run is already in place. Ties take the left element, so the
278 : // sort is stable.
279 40221 : static inline __attribute__((always_inline)) void csort_merge_contiguous(
280 : unsigned char *base, size_t left, size_t mid, size_t right,
281 : size_t elem_size, ccol_comparison_proc comparison_proc,
282 : unsigned char *temp_buffer) {
283 40221 : size_t left_bytes = (mid - left + 1) * elem_size;
284 40221 : unsigned char *out = base + left * elem_size;
285 40221 : memcpy(temp_buffer, out, left_bytes);
286 40221 : unsigned char *l = temp_buffer;
287 40221 : unsigned char *l_end = temp_buffer + left_bytes;
288 40221 : unsigned char *r = base + (mid + 1) * elem_size;
289 40221 : unsigned char *r_end = base + (right + 1) * elem_size;
290 459184 : while (l < l_end && r < r_end) {
291 418963 : if (comparison_proc(l, r) <= 0) {
292 226512 : memcpy(out, l, elem_size);
293 226512 : l += elem_size;
294 : } else {
295 192451 : memcpy(out, r, elem_size);
296 192451 : r += elem_size;
297 : }
298 418963 : out += elem_size;
299 : }
300 40221 : if (l < l_end) {
301 18709 : memcpy(out, l, (size_t)(l_end - l));
302 : }
303 : }
304 :
305 : // Runs every bottom-up merge pass over [0, length) of a contiguous array, in
306 : // the same order as csort_mergesort_iterative(), so both drivers give the same
307 : // result. It's inlined once per element width.
308 122 : static inline __attribute__((always_inline)) void csort_contiguous_passes(
309 : unsigned char *base, size_t length, size_t elem_size,
310 : ccol_comparison_proc comparison_proc, unsigned char *temp_buffer) {
311 122 : size_t high = length - 1;
312 644 : for (size_t curr_size = 1; curr_size < length; curr_size *= 2) {
313 40743 : for (size_t left_start = 0; left_start <= high;
314 : left_start += 2 * curr_size) {
315 40454 : size_t mid = left_start + curr_size - 1;
316 40454 : if (mid >= high) {
317 : break;
318 : }
319 40221 : size_t right_end = left_start + 2 * curr_size - 1;
320 40221 : if (right_end > high) {
321 : right_end = high;
322 : }
323 80964 : csort_merge_contiguous(base, left_start, mid, right_end, elem_size,
324 : comparison_proc, temp_buffer);
325 : }
326 : }
327 : }
328 :
329 : // Sorts the length elements at base in place, stably; it's the sort behind
330 : // cvec_sort() and cvec_sort_with(), which avoids a getter
331 : // call per element access. The buffer comes from mprocs. Gives true on success
332 : // or when there's nothing to do, false when csort_check_sort_shape() refuses or
333 : // the allocation fails. The widths 1, 2, 4, 8 and 16 get their own copy of the
334 : // passes with a constant elem_size, so every element move is one load and one
335 : // store. Bumps the test counter when it allocates.
336 141 : bool csort__merge_sort_contiguous(void *base, size_t length, size_t elem_size,
337 : ccol_comparison_proc comparison_proc,
338 : ccol_memmgmt_procs *mprocs) {
339 141 : if (!base || length < 2) {
340 : return true;
341 : }
342 123 : if (!comparison_proc) {
343 0 : ccol__assert(false);
344 : return false;
345 : }
346 :
347 123 : csort_buffer_outcome outcome =
348 123 : csort_check_sort_shape(length, elem_size, mprocs);
349 : if (outcome != csort_buffer_ready) {
350 0 : return outcome == csort_buffer_not_needed;
351 : }
352 :
353 123 : unsigned char *temp_buffer = ccol__mem_alloc(mprocs, length * elem_size);
354 123 : if (!temp_buffer) {
355 : return false;
356 : }
357 : #ifdef RUNNING_UNIT_TESTS
358 122 : g_csort_contiguous_sorts_for_tests++;
359 : #endif
360 :
361 122 : unsigned char *b = base;
362 122 : switch (elem_size) {
363 : case 1:
364 16 : csort_contiguous_passes(b, length, 1, comparison_proc, temp_buffer);
365 : break;
366 : case 2:
367 13 : csort_contiguous_passes(b, length, 2, comparison_proc, temp_buffer);
368 : break;
369 : case 4:
370 30 : csort_contiguous_passes(b, length, 4, comparison_proc, temp_buffer);
371 : break;
372 : case 8:
373 43 : csort_contiguous_passes(b, length, 8, comparison_proc, temp_buffer);
374 : break;
375 : case 16:
376 11 : csort_contiguous_passes(b, length, 16, comparison_proc, temp_buffer);
377 : break;
378 : default:
379 9 : csort_contiguous_passes(b, length, elem_size, comparison_proc,
380 : temp_buffer);
381 : break;
382 : }
383 :
384 122 : ccol__mem_free(mprocs, temp_buffer);
385 : return true;
386 : }
387 :
388 : // Sorts col in place through getter_proc and comparison_proc; it's the body of
389 : // csort_sort(), for collections that aren't one contiguous array. A NULL col or
390 : // a length of 0 or 1 gives true without looking at the procs; otherwise a NULL
391 : // proc asserts. Gives the result of csort_mergesort_iterative().
392 96 : bool csort__merge_sort(void *col, size_t length, size_t elem_size,
393 : csort_item_getter_proc getter_proc,
394 : ccol_comparison_proc comparison_proc,
395 : ccol_memmgmt_procs *mprocs) {
396 96 : if (!col) {
397 : return true;
398 : }
399 :
400 94 : if (length == 0 || length == 1) {
401 : return true;
402 : }
403 :
404 74 : if (!getter_proc || !comparison_proc) {
405 3 : ccol__assert(false);
406 : return false;
407 : }
408 :
409 71 : return csort_mergesort_iterative(col, 0, length - 1, elem_size, getter_proc,
410 : comparison_proc, mprocs);
411 : }
|