1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use core::{
    fmt::{Debug, Display},
    num::{NonZeroU16, NonZeroU32, NonZeroU8},
};

use alloc::boxed::Box;

use crate::inline::get_heap_threshold;

mod sealed {
    use core::num::{NonZeroU16, NonZeroU32, NonZeroU8};

    pub trait LengthSealed {}
    impl LengthSealed for u8 {}
    impl LengthSealed for u16 {}
    #[cfg(any(target_pointer_width = "64", target_pointer_width = "32"))]
    impl LengthSealed for u32 {}

    pub trait NonZeroSealed {}
    impl NonZeroSealed for NonZeroU8 {}
    impl NonZeroSealed for NonZeroU16 {}
    #[cfg(any(target_pointer_width = "64", target_pointer_width = "32"))]
    impl NonZeroSealed for NonZeroU32 {}
}

#[derive(Debug)]
pub struct InvalidLength<T> {
    type_name: &'static str,
    original: Box<[T]>,
}

impl<T> InvalidLength<T> {
    #[cold]
    #[track_caller]
    pub(crate) fn new(type_name: &'static str, original: Box<[T]>) -> Self {
        Self {
            type_name,
            original,
        }
    }

    /// Returns the original Box<[T]> that could not be converted from.
    pub fn get_inner(self) -> Box<[T]> {
        self.original
    }
}

impl<T> core::fmt::Display for InvalidLength<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Cannot fit {} into {}",
            self.original.len(),
            self.type_name,
        )
    }
}

#[derive(Debug)]
pub struct InvalidStrLength {
    type_name: &'static str,
    original: Box<str>,
}

impl InvalidStrLength {
    /// Returns the original [`Box<str>`] that could not be converted from.
    pub fn get_inner(self) -> Box<str> {
        self.original
    }
}

impl core::fmt::Display for InvalidStrLength {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Cannot fit {} into {}",
            self.original.len(),
            self.type_name,
        )
    }
}

impl TryFrom<InvalidLength<u8>> for InvalidStrLength {
    type Error = core::str::Utf8Error;

    fn try_from(value: InvalidLength<u8>) -> Result<Self, Self::Error> {
        let original = if let Err(err) = core::str::from_utf8(&value.original) {
            return Err(err);
        } else {
            unsafe { alloc::str::from_boxed_utf8_unchecked(value.original) }
        };

        Ok(Self {
            original,
            type_name: value.type_name,
        })
    }
}

#[doc(hidden)]
pub trait NonZero<Int: ValidLength>:
    sealed::NonZeroSealed + Into<Int> + Sized + Copy + PartialEq + Debug
{
    fn new(val: Int) -> Option<Self>;
}

impl NonZero<u8> for NonZeroU8 {
    fn new(val: u8) -> Option<Self> {
        NonZeroU8::new(val)
    }
}

impl NonZero<u16> for NonZeroU16 {
    fn new(val: u16) -> Option<Self> {
        NonZeroU16::new(val)
    }
}

impl NonZero<u32> for NonZeroU32 {
    fn new(val: u32) -> Option<Self> {
        NonZeroU32::new(val)
    }
}

/// A sealed trait to represent valid lengths for a [`FixedArray`].
///
/// This is implemented on `u32` for non-16 bit platforms, and `u16` on all platforms.
///
/// [`FixedArray`]: `crate::array::FixedArray`
pub trait ValidLength:
    sealed::LengthSealed + Copy + Display + PartialEq + From<u8> + TryFrom<usize> + Into<u32>
{
    const ZERO: Self;
    const MAX: Self;
    const DANGLING: Self::NonZero;

    type NonZero: NonZero<Self>;
    #[cfg(feature = "typesize")]
    type InlineStrRepr: Copy + AsRef<[u8]> + AsMut<[u8]> + Default + typesize::TypeSize;
    #[cfg(not(feature = "typesize"))]
    type InlineStrRepr: Copy + AsRef<[u8]> + AsMut<[u8]> + Default;

    #[must_use]
    fn to_usize(self) -> usize;

    #[must_use]
    fn from_usize(len: usize) -> Option<Self> {
        len.try_into().ok()
    }
}

impl ValidLength for u8 {
    const ZERO: Self = 0;
    const MAX: Self = Self::MAX;
    const DANGLING: Self::NonZero = Self::NonZero::MAX;

    type NonZero = NonZeroU8;
    type InlineStrRepr = [u8; get_heap_threshold::<Self>()];

    fn to_usize(self) -> usize {
        self.into()
    }
}

impl ValidLength for u16 {
    const ZERO: Self = 0;
    const MAX: Self = Self::MAX;
    const DANGLING: Self::NonZero = Self::NonZero::MAX;

    type NonZero = NonZeroU16;
    type InlineStrRepr = [u8; get_heap_threshold::<Self>()];

    fn to_usize(self) -> usize {
        self.into()
    }
}

#[cfg(any(target_pointer_width = "64", target_pointer_width = "32"))]
impl ValidLength for u32 {
    const ZERO: Self = 0;
    const MAX: Self = Self::MAX;
    const DANGLING: Self::NonZero = Self::NonZero::MAX;

    type NonZero = NonZeroU32;
    type InlineStrRepr = [u8; get_heap_threshold::<Self>()];

    fn to_usize(self) -> usize {
        self.try_into()
            .expect("u32 can fit into usize on platforms with pointer lengths of 32 and 64")
    }
}

#[cfg(target_pointer_width = "16")]
pub type SmallLen = u16;
#[cfg(not(target_pointer_width = "16"))]
pub type SmallLen = u32;