This small crate provides macros for sorting arrays and slices of any type in const contexts with introsort.
This implementation is usable on Rust version 1.85.0, before the const_trait_impl feature is stabilized.
The crate also provides const functions for sorting arrays and slices of primitives which are available on earlier Rust versions.
The functions that sort arrays are usable already on Rust version 1.56.0,
except the ones that sort arrays of floats, which need 1.83.0.
The functions that sort slices also need 1.83.0.
These functions do exactly the same thing as the macros, but they have been added as their own separate thing to let the crate sort primitives on even earlier Rust versions,
and they can also sometimes use more optimal sorting algorithms (like how bools, u8s, and i8s are sorted with counting sort).
Sort an array of any type by value:
use compile_time_sort::into_sorted_array_by;
// This derive is used for the assertion at the end of this test,
// it is not needed for the macro to work.
#[derive(PartialOrd, PartialEq)]
struct ExampleStruct(u8);
const UNSORTED: [ExampleStruct; 3] = [ExampleStruct(3), ExampleStruct(1), ExampleStruct(2)];
const SORTED: [ExampleStruct; 3] = into_sorted_array_by!(
UNSORTED,
|a: &ExampleStruct, b| { a.0 <= b.0 }
);
assert!(SORTED.is_sorted());Sort it by reference:
use compile_time_sort::sort_slice_by;
#[derive(PartialOrd, PartialEq)]
struct ExampleStruct(u8);
const SORTED: [ExampleStruct; 3] = {
let mut arr = [ExampleStruct(3), ExampleStruct(1), ExampleStruct(2)];
sort_slice_by!(&mut arr, |a: &ExampleStruct, b| { a.0 <= b.0 });
arr
};
assert!(SORTED.is_sorted());Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.