Skip to main content

generic_array/ext_impls/
impl_const_default.rs

1//! Const default implementation
2
3use crate::{ArrayLength, GenericArray, GenericArrayImplEven, GenericArrayImplOdd};
4use const_default::ConstDefault;
5
6impl<T, U: ConstDefault> ConstDefault for GenericArrayImplEven<T, U> {
7    const DEFAULT: Self = Self {
8        parents: [U::DEFAULT; 2],
9        _marker: core::marker::PhantomData,
10    };
11}
12
13impl<T: ConstDefault, U: ConstDefault> ConstDefault for GenericArrayImplOdd<T, U> {
14    const DEFAULT: Self = Self {
15        parents: [U::DEFAULT; 2],
16        data: T::DEFAULT,
17    };
18}
19
20impl<T, U: ArrayLength> ConstDefault for GenericArray<T, U>
21where
22    U::ArrayType<T>: ConstDefault,
23{
24    const DEFAULT: Self = Self {
25        data: ConstDefault::DEFAULT,
26    };
27}
28
29// `T: ConstDefault` is intentionally redundant to provide better hints in the docs
30impl<T: ConstDefault, U: ArrayLength> GenericArray<T, U>
31where
32    Self: ConstDefault,
33{
34    /// Returns the constant "default value" for an array using [ConstDefault]
35    #[inline(always)]
36    pub const fn const_default() -> Self {
37        Self::DEFAULT
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use crate::{arr, typenum::U4, GenericArray};
44    use const_default::ConstDefault;
45
46    #[test]
47    fn const_default_works() {
48        // Use runtime (non-`const`) bindings: a `const` context is evaluated at
49        // compile time and so is invisible to runtime coverage instrumentation.
50
51        // exercises the recursive `GenericArrayImplEven`/`Odd` and `GenericArray` DEFAULT consts
52        let a: GenericArray<i32, U4> = <GenericArray<i32, U4> as ConstDefault>::DEFAULT;
53        assert_eq!(a, arr![0, 0, 0, 0]);
54
55        // and the `const_default()` convenience accessor
56        let b: GenericArray<i32, U4> = GenericArray::const_default();
57        assert_eq!(b, arr![0, 0, 0, 0]);
58    }
59}