1#[derive(Debug, thiserror::Error)]
2pub enum FixedStrError {
3 #[error("exceed max length limit")]
5 ExceedMaxLengthLimit,
6 #[error("invalid format")]
8 InvalidFormat,
9 #[error("utf8: {0}")]
11 Utf8(#[from] std::str::Utf8Error),
12}
13
14pub fn fixed_str_to_bytes<const MAX_LEN: usize>(
16 name: &str,
17) -> Result<[u8; MAX_LEN], FixedStrError> {
18 let bytes = name.as_bytes();
19 if bytes.len() > MAX_LEN {
20 return Err(FixedStrError::ExceedMaxLengthLimit);
21 }
22 let mut buffer = [0; MAX_LEN];
23 buffer[..bytes.len()].copy_from_slice(bytes);
24 Ok(buffer)
25}
26
27pub fn bytes_to_fixed_str<const MAX_LEN: usize>(
29 bytes: &[u8; MAX_LEN],
30) -> Result<&str, FixedStrError> {
31 let Some(end) = bytes.iter().position(|&x| x == 0) else {
32 return Err(FixedStrError::InvalidFormat);
33 };
34 let valid_bytes = &bytes[..end];
35 Ok(std::str::from_utf8(valid_bytes)?)
36}