gmsol_utils/
fixed_str.rs

1#[derive(Debug, thiserror::Error)]
2pub enum FixedStrError {
3    /// Exceed max length limit.
4    #[error("exceed max length limit")]
5    ExceedMaxLengthLimit,
6    /// Invalid format.
7    #[error("invalid format")]
8    InvalidFormat,
9    /// Utf8 Error.
10    #[error("utf8: {0}")]
11    Utf8(#[from] std::str::Utf8Error),
12}
13
14/// Fixed size string to bytes.
15pub 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
27/// Bytes to fixed size string.
28pub 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}