| @@ -2,24 +2,32 @@ |
| 2 | 2 | /// |
| 3 | 3 | /// import qsort |
| 4 | 4 | /// |
| 5 | | −/// qsort.sort([3, 1, 2], fn(a, b) { a - b }) // [1, 2, 3] |
| 5 | +/// qsort.sort([3, 1, 2], fn(a, b) { a - b }) // Ok([1, 2, 3]) |
| 6 | 6 | /// |
| 7 | 7 | /// It wraps `sortkit`, whose bindings are generated from its C header. The |
| 8 | 8 | /// comparator runs inside the C call (ADR 0015): it may perform `<ffi>` at |
| 9 | 9 | /// most, and if it panics, the calling actor stops once the sort returns. |
| 10 | 10 | |
| 11 | 11 | import std/ffi.{type Resource} |
| 12 | | −import std/list |
| 12 | +import std/result |
| 13 | 13 | import sortkit.{type SkVec} |
| 14 | 14 | |
| 15 | 15 | /// `xs` sorted by `compare`, which returns a negative number, zero or a |
| 16 | 16 | /// positive number as `a` goes before, with or after `b`. The sort is |
| 17 | | −/// stable. |
| 18 | | −pub fn sort(xs: List<Int>, compare: fn(Int, Int) -> Int / <ffi>) -> List<Int> / <ffi> { |
| 17 | +/// stable. An `Error` if the C library runs out of memory. |
| 18 | +pub fn sort(xs: List<Int>, compare: fn(Int, Int) -> Int / <ffi>) -> Result<List<Int>, String> / <ffi> { |
| 19 | 19 | let v = sortkit.sk_vec_new() |
| 20 | | − list.each(xs, fn(x) { push(v, x) }) |
| 21 | | − let _ = sortkit.sk_vec_sort(v, compare) |
| 22 | | − to_list(v, sortkit.sk_vec_len(v) - 1, []) |
| 20 | + use _ <- result.try(push_all(v, xs)) |
| 21 | + // `sk_vec_sort` returns how many comparisons it made, and 0 when it |
| 22 | + // cannot allocate its buffer: a merge of two or more elements makes one |
| 23 | + // at least. |
| 24 | + let comparisons = sortkit.sk_vec_sort(v, compare) |
| 25 | + let length = sortkit.sk_vec_len(v) |
| 26 | + if length > 1 && comparisons == 0 { |
| 27 | + Error(out_of_memory()) |
| 28 | + } else { |
| 29 | + Ok(to_list(v, length - 1, [])) |
| 30 | + } |
| 23 | 31 | } |
| 24 | 32 | |
| 25 | 33 | /// The version of the C library. |
| @@ -32,8 +40,13 @@ pub fn count_byte(s: String, byte: Int) -> Int / <ffi> { |
| 32 | 40 | sortkit.sk_count_byte(s, byte) |
| 33 | 41 | } |
| 34 | 42 | |
| 35 | | −fn push(v: Resource<SkVec>, x: Int) -> () / <ffi> { |
| 36 | | − if sortkit.sk_vec_push(v, x) { () } else { panic("sortkit: out of memory") } |
| 43 | +fn out_of_memory() -> String { "sortkit: out of memory" } |
| 44 | + |
| 45 | +fn push_all(v: Resource<SkVec>, xs: List<Int>) -> Result<(), String> / <ffi> { |
| 46 | + match xs { |
| 47 | + [] -> Ok(()), |
| 48 | + [x, ..rest] -> if sortkit.sk_vec_push(v, x) { push_all(v, rest) } else { Error(out_of_memory()) }, |
| 49 | + } |
| 37 | 50 | } |
| 38 | 51 | |
| 39 | 52 | /// The elements at `i` and below, before `acc`. `sk_vec_get` does not |