/// Sorting with a C library and a Louise comparator (issue #48). /// /// import qsort /// /// qsort.sort([3, 1, 2], fn(a, b) { a - b }) // Ok([1, 2, 3]) /// /// It wraps `sortkit`, whose bindings are generated from its C header. The /// comparator runs inside the C call (ADR 0015): it may perform `` at /// most, and if it panics, the calling actor stops once the sort returns. import sortkit.{type SkVec} import std/ffi.{type Resource} import std/result import std/test.{assert, assert_equal} /// `xs` sorted by `compare`, which returns a negative number, zero or a /// positive number as `a` goes before, with or after `b`. The sort is /// stable. An `Error` if the C library runs out of memory. pub fn sort :: xs: List compare: fn(Int, Int) -> Int / -> Result, String> / { let v = sortkit.sk_vec_new () use _ <- result.try (push_all v xs) // `sk_vec_sort` returns how many comparisons it made, and 0 when it // cannot allocate its buffer: a merge of two or more elements makes one // at least. let comparisons = sortkit.sk_vec_sort v compare let length = sortkit.sk_vec_len v if length > 1 && comparisons == 0 { Error(out_of_memory ()) } else { Ok(to_list v (length - 1) []) } } /// The version of the C library. pub fn version :: -> String / { sortkit.sk_version () } /// How many of the UTF-8 bytes of `s` equal `byte`. pub fn count_byte :: s: String byte: Int -> Int / { sortkit.sk_count_byte s byte } fn out_of_memory :: -> String { "sortkit: out of memory" } fn push_all :: v: Resource xs: List -> Result<(), String> / { match xs { [] -> Ok(()) , [ x , ..rest ] -> if sortkit.sk_vec_push v x { push_all v rest } else { Error(out_of_memory ()) } } } /// The elements at `i` and below, before `acc`. `sk_vec_get` does not /// check its index: `i` stays below the length. fn to_list :: v: Resource i: Int acc: List -> List / { if i < 0 { acc } else { to_list v (i - 1) Cons(sortkit.sk_vec_get v i, acc) } } @test fn push_all_keeps_the_order :: -> () / { let v = sortkit.sk_vec_new () assert (push_all v [3, 1, 2] |> result.is_ok) "pushed" assert_equal (sortkit.sk_vec_len v) 3 assert_equal (to_list v 2 []) [3, 1, 2] } @test fn to_list_puts_the_elements_before_acc :: -> () / { let v = sortkit.sk_vec_new () let _ = push_all v [3, 1, 2] assert_equal (to_list v 1 [0]) [3, 1, 0] assert_equal (to_list v (-1) [0]) [0] }