diff --git a/vlib/builtin/cfns_wrapper.c.v b/vlib/builtin/cfns_wrapper.c.v index 32aff567ba..f3f9c93eec 100644 --- a/vlib/builtin/cfns_wrapper.c.v +++ b/vlib/builtin/cfns_wrapper.c.v @@ -79,7 +79,13 @@ mut: real_sort_cb FnSortContextCB } + +// GLIBC: +// void qsort_r(void *base, size_t nmemb, size_t size, +// int (*compar)(const void *, const void *, void *), +// void *arg); fn vqsort_context_pure_v(base voidptr, nmemb usize, size usize, sort_cb FnSortContextCB, context voidptr) { + C.qsort_r(base, nmemb, size, voidptr(sort_cb), context) } [inline; unsafe] diff --git a/vlib/builtin/sort_with_compare_context_test.v b/vlib/builtin/sort_with_compare_context_test.v index 3cce17c886..a8ab6efb68 100644 --- a/vlib/builtin/sort_with_compare_context_test.v +++ b/vlib/builtin/sort_with_compare_context_test.v @@ -3,27 +3,49 @@ mut: comparisons []string } +fn (c Context) str() string { + mut res := []string{} + for x in c.comparisons { + res << x + } + return '\n' + res.join('\n') +} + +fn sort_cb(a &string, b &string, mut context Context) int { + context.comparisons << 'a: "${*a}" | b: "${*b}"' + if a < b { + return -1 + } + if a > b { + return 1 + } + return 0 +} + fn test_sort_with_compare() { mut a := ['hi', '1', '5', '3'] mut context := Context{} - a.sort_with_compare_context(fn (a &string, b &string, mut context Context) int { - context.comparisons << 'a: ${*a} | b: ${*b}' - if a < b { - return -1 - } - if a > b { - return 1 - } - return 0 - }, context) + a.sort_with_compare_context(sort_cb, context) dump(a) dump(context) assert a == ['1', '3', '5', 'hi'] assert context.comparisons == [ - 'a: hi | b: 1', - 'a: 5 | b: 3', - 'a: 1 | b: 3', - 'a: hi | b: 3', - 'a: hi | b: 5', + 'a: "hi" | b: "1"', + 'a: "5" | b: "3"', + 'a: "1" | b: "3"', + 'a: "hi" | b: "3"', + 'a: "hi" | b: "5"', + ] + // + mut already_sorted_context := Context{} + a.sort_with_compare_context(sort_cb, already_sorted_context) + dump(a) + dump(already_sorted_context) + assert context != already_sorted_context + assert already_sorted_context.comparisons == [ + 'a: "1" | b: "3"', + 'a: "5" | b: "hi"', + 'a: "1" | b: "5"', + 'a: "3" | b: "5"', ] }