core_utils_rs/
four_char_code_unchecked.rs

1use four_char_code::FourCharCode;
2
3const fn from_bytes_unchecked(mut bytes: [u8; 4]) -> FourCharCode {
4    let mut null_streak = true;
5
6    let mut i = 3usize;
7    loop {
8        let mut c = bytes[i];
9        if c == 0 {
10            if null_streak {
11                c = 0x20;
12                bytes[i] = c;
13            } else {
14                panic!("Invalid FourCharCode");
15            }
16        } else {
17            null_streak = false;
18        }
19
20        if c <= b'\x1f' || c >= b'\x7f' {
21            panic!("Invalid FourCharCode");
22        }
23
24        if i == 0 {
25            break;
26        }
27        i -= 1;
28    }
29
30    unsafe { FourCharCode::new_unchecked(u32::from_be_bytes(bytes)) }
31}
32/// Returns a [FourCharCode] if slice is valid, an error describing the problem otherwise.
33pub const fn from_slice_unchecked(value: &[u8]) -> FourCharCode {
34    if value.len() < 4 || value.len() > 4 {
35        panic!("Invalid FourCharCode");
36    }
37
38    from_bytes_unchecked([value[0], value[1], value[2], value[3]])
39}
40
41/// Returns a [FourCharCode] if string is valid, an error describing the problem otherwise.
42#[allow(clippy::should_implement_trait)]
43pub const fn from_str_unchecked(value: &str) -> FourCharCode {
44    from_slice_unchecked(value.as_bytes())
45}