Skip to main content

proka_exec/
utils.rs

1//! Utilities to parse proka exec headers.
2use crate::Error;
3
4/// Convert a `&str` to a specified-length array.
5#[inline]
6pub fn str_to_array<const N: usize>(s: &str) -> [u8; N] {
7    let mut arr: [u8; N] = [0u8; N];
8    let bytes = s.as_bytes();
9    let copy_len = bytes.len().min(N);
10
11    // Copy to slice and return
12    arr[..copy_len].copy_from_slice(&bytes[..copy_len]);
13    arr
14}
15
16/// Convert the slice to a UTF-8 string.
17#[inline]
18pub fn slice_to_str(arr: &[u8]) -> Result<&str, Error> {
19    str::from_utf8(arr).map_err(|_| Error::UnknownCharacter)
20}
21
22// Tests...
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    const TEXT: &str = "Hello world";
28    const RAW: &[u8] = &*b"Hello world";
29
30    #[test]
31    fn test_str_to_array() {
32        let result: [u8; 11] = str_to_array(TEXT);
33        assert_eq!(&result, RAW);
34    }
35
36    #[test]
37    fn test_slice_to_str() {
38        let result = slice_to_str(RAW).unwrap();
39        assert_eq!(result, TEXT);
40    }
41}