libpso/src/util.rs

68 lines
1.8 KiB
Rust
Raw Normal View History

2019-11-03 10:46:13 -08:00
pub fn array_to_utf8<const X: usize>(array: [u8; X]) -> Result<String, std::string::FromUtf8Error> {
String::from_utf8(array.to_vec())
.map(|mut s| {
if let Some(index) = s.find('\u{0}') {
2019-11-03 10:46:13 -08:00
s.truncate(index);
}
s
})
}
2020-05-20 23:21:43 -06:00
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()
2020-05-20 23:21:43 -06:00
}
}
2023-11-14 21:37:22 -07:00
pub fn utf8_to_array<const N: usize>(s: impl Into<String>) -> [u8; N] {
let mut array = [0u8; N];
let s = s.into();
let bytes = s.as_bytes();
array[..bytes.len()].clone_from_slice(bytes);
2023-11-14 21:37:22 -07:00
array
2019-11-03 10:46:13 -08:00
}
2023-11-14 21:37:22 -07:00
pub fn utf8_to_utf16_array<const N: usize>(s: impl Into<String>) -> [u16; N] {
let mut array = [0u16; N];
let bytes = s.into().encode_utf16().collect::<Vec<_>>();
array[..bytes.len()].clone_from_slice(&bytes);
array
2019-11-03 10:46:13 -08:00
}
2020-10-07 00:04:24 -06:00
pub fn vec_to_array<T: Default + Copy, const N: usize>(vec: Vec<T>) -> [T; N] {
let mut result: [T; N] = [T::default(); N];
for (i, v) in vec.into_iter().enumerate() {
result[i] = v
}
result
}
2019-11-03 10:46:13 -08:00
#[cfg(test)]
mod test {
2023-11-14 21:37:22 -07:00
use super::*;
2019-11-03 10:46:13 -08:00
#[test]
fn test_utf8_to_array() {
let s = "asdf".to_owned();
2023-11-14 21:37:22 -07:00
let a = utf8_to_array(s);
2019-11-03 10:46:13 -08:00
let mut e = [0u8; 8];
e[..4].clone_from_slice(b"asdf");
assert!(a == e);
}
#[test]
2023-11-14 21:37:22 -07:00
fn test_utf8_to_utf16_array() {
let utf16 = utf8_to_utf16_array("asdf");
2019-11-03 10:46:13 -08:00
assert!(utf16 == [97, 115, 100, 102, 0,0,0,0,0,0,0,0,0,0,0,0])
}
#[test]
2023-11-14 21:37:22 -07:00
fn test_utf8_to_utf16_array_unicode() {
let utf16 = utf8_to_utf16_array("あいうえお");
2019-11-03 10:46:13 -08:00
assert!(utf16 == [0x3042 , 0x3044, 0x3046, 0x3048, 0x304A, 0,0,0,0,0,0,0,0,0,0,0])
}
}