const_panic/utils/
non_basic_utils.rs

1use crate::{FmtArg, PanicVal};
2
3/// For coercing a `&[PanicVal<'_>; LEN]` into a `&[PanicVal<'_>]`.
4pub const fn panicvals_id<'a, 'b, const LEN: usize>(
5    array: &'b [PanicVal<'a>; LEN],
6) -> &'b [PanicVal<'a>] {
7    array
8}
9
10/// Flattens a `&[&[PanicVal<'a>]]` into a `[PanicVal<'a>; LEN]`.
11///
12/// If `LEN` is greater than the amount of `PanicVal`s in the slices,
13/// this fills the remaining array with [`PanicVal::EMPTY`].
14///
15/// # Panics
16///
17/// Panics if the amount of `PanicVal`s in the slices is greater than `LEN`.
18///
19pub const fn flatten_panicvals<'a, const LEN: usize>(
20    mut input: &[&[PanicVal<'a>]],
21) -> [PanicVal<'a>; LEN] {
22    let mut out = [PanicVal::EMPTY; LEN];
23    let mut len = 0usize;
24
25    while let [mut outer, ref rinput @ ..] = *input {
26        while let [arg, ref router @ ..] = *outer {
27            out[len] = arg;
28            len += 1;
29            outer = router;
30        }
31        input = rinput
32    }
33
34    out
35}
36
37/// Gets the maximum value between `l` and `r`
38///
39/// # Example
40///
41/// ```rust
42/// use const_panic::utils::max_usize;
43///
44/// assert_eq!(max_usize(5, 3), 5);
45/// assert_eq!(max_usize(5, 8), 8);
46///
47/// ```
48pub const fn max_usize(l: usize, r: usize) -> usize {
49    if l > r {
50        l
51    } else {
52        r
53    }
54}
55
56/// Gets the maximum value in `slice`, returns `0` if the slice is empty.
57///
58/// # Example
59///
60/// ```rust
61/// use const_panic::utils::slice_max_usize;
62///
63/// assert_eq!(slice_max_usize(&[]), 0);
64/// assert_eq!(slice_max_usize(&[3]), 3);
65/// assert_eq!(slice_max_usize(&[5, 3]), 5);
66/// assert_eq!(slice_max_usize(&[5, 8, 3]), 8);
67/// assert_eq!(slice_max_usize(&[5, 13, 8, 3]), 13);
68///
69/// ```
70pub const fn slice_max_usize(mut slice: &[usize]) -> usize {
71    let mut max = 0;
72
73    while let [x, ref rem @ ..] = *slice {
74        max = max_usize(max, x);
75        slice = rem;
76    }
77
78    max
79}
80
81#[doc(hidden)]
82#[track_caller]
83pub const fn assert_flatten_panicvals_length(expected_larger: usize, actual_value: usize) {
84    if actual_value > expected_larger {
85        crate::concat_panic(&[&[
86            PanicVal::write_str("length passed to flatten_panicvals macro ("),
87            PanicVal::from_usize(expected_larger, FmtArg::DISPLAY),
88            PanicVal::write_str(") is smaller than the computed length ("),
89            PanicVal::from_usize(actual_value, FmtArg::DISPLAY),
90            PanicVal::write_str(")"),
91        ]]);
92    }
93}