pub fn array_to_utf8(array: [u8; X]) -> Result { String::from_utf8(array.to_vec()) .map(|mut s| { if let Some(index) = s.find('\u{0}') { s.truncate(index); } s }) } pub fn array_to_utf16(array: &[u8]) -> String { unsafe { let (_, data, _) = array.align_to(); String::from_utf16_lossy(data).trim_matches(char::from(0)).into() } } pub fn utf8_to_array(s: impl Into) -> [u8; N] { let mut array = [0u8; N]; let s = s.into(); let bytes = s.as_bytes(); array[..bytes.len()].clone_from_slice(bytes); array } pub fn utf8_to_utf16_array(s: impl Into) -> [u16; N] { let mut array = [0u16; N]; let bytes = s.into().encode_utf16().collect::>(); array[..bytes.len()].clone_from_slice(&bytes); array } pub fn vec_to_array(vec: Vec) -> [T; N] { let mut result: [T; N] = [T::default(); N]; for (i, v) in vec.into_iter().enumerate() { result[i] = v } result } #[cfg(test)] mod test { use super::*; #[test] fn test_utf8_to_array() { let s = "asdf".to_owned(); let a = utf8_to_array(s); let mut e = [0u8; 8]; e[..4].clone_from_slice(b"asdf"); assert!(a == e); } #[test] fn test_utf8_to_utf16_array() { let utf16 = utf8_to_utf16_array("asdf"); assert!(utf16 == [97, 115, 100, 102, 0,0,0,0,0,0,0,0,0,0,0,0]) } #[test] fn test_utf8_to_utf16_array_unicode() { let utf16 = utf8_to_utf16_array("あいうえお"); assert!(utf16 == [0x3042 , 0x3044, 0x3046, 0x3048, 0x304A, 0,0,0,0,0,0,0,0,0,0,0]) } }