You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.8 KiB

  1. pub fn array_to_utf8<const X: usize>(array: [u8; X]) -> Result<String, std::string::FromUtf8Error> {
  2. String::from_utf8(array.to_vec())
  3. .map(|mut s| {
  4. if let Some(index) = s.find('\u{0}') {
  5. s.truncate(index);
  6. }
  7. s
  8. })
  9. }
  10. pub fn array_to_utf16(array: &[u8]) -> String {
  11. unsafe {
  12. let (_, data, _) = array.align_to();
  13. String::from_utf16_lossy(data).trim_matches(char::from(0)).into()
  14. }
  15. }
  16. pub fn utf8_to_array<const N: usize>(s: impl Into<String>) -> [u8; N] {
  17. let mut array = [0u8; N];
  18. let s = s.into();
  19. let bytes = s.as_bytes();
  20. array[..bytes.len()].clone_from_slice(bytes);
  21. array
  22. }
  23. pub fn utf8_to_utf16_array<const N: usize>(s: impl Into<String>) -> [u16; N] {
  24. let mut array = [0u16; N];
  25. let bytes = s.into().encode_utf16().collect::<Vec<_>>();
  26. array[..bytes.len()].clone_from_slice(&bytes);
  27. array
  28. }
  29. pub fn vec_to_array<T: Default + Copy, const N: usize>(vec: Vec<T>) -> [T; N] {
  30. let mut result: [T; N] = [T::default(); N];
  31. for (i, v) in vec.into_iter().enumerate() {
  32. result[i] = v
  33. }
  34. result
  35. }
  36. #[cfg(test)]
  37. mod test {
  38. use super::*;
  39. #[test]
  40. fn test_utf8_to_array() {
  41. let s = "asdf".to_owned();
  42. let a = utf8_to_array(s);
  43. let mut e = [0u8; 8];
  44. e[..4].clone_from_slice(b"asdf");
  45. assert!(a == e);
  46. }
  47. #[test]
  48. fn test_utf8_to_utf16_array() {
  49. let utf16 = utf8_to_utf16_array("asdf");
  50. assert!(utf16 == [97, 115, 100, 102, 0,0,0,0,0,0,0,0,0,0,0,0])
  51. }
  52. #[test]
  53. fn test_utf8_to_utf16_array_unicode() {
  54. let utf16 = utf8_to_utf16_array("あいうえお");
  55. assert!(utf16 == [0x3042 , 0x3044, 0x3046, 0x3048, 0x304A, 0,0,0,0,0,0,0,0,0,0,0])
  56. }
  57. }