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.

63 lines
1.5 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. // TODO: const fn version of this! (helpful with tests)
  11. #[macro_export]
  12. macro_rules! utf8_to_array {
  13. ($s: expr, $size: expr) => {
  14. {
  15. let mut array = [0u8; $size];
  16. let bytes = $s.as_bytes();
  17. array[..bytes.len()].clone_from_slice(&bytes);
  18. array
  19. }
  20. }
  21. }
  22. #[macro_export]
  23. macro_rules! utf8_to_utf16_array {
  24. ($s: expr, $size: expr) => {
  25. {
  26. let mut array = [0u16; $size];
  27. //let bytes = $s.as_bytes();
  28. let bytes = $s.encode_utf16().collect::<Vec<_>>();
  29. array[..bytes.len()].clone_from_slice(&bytes);
  30. array
  31. }
  32. }
  33. }
  34. #[cfg(test)]
  35. mod test {
  36. #[test]
  37. fn test_utf8_to_array() {
  38. let s = "asdf".to_owned();
  39. let a = utf8_to_array!(s, 8);
  40. let mut e = [0u8; 8];
  41. e[..4].clone_from_slice(b"asdf");
  42. assert!(a == e);
  43. }
  44. #[test]
  45. fn utf8_to_utf16_array() {
  46. let utf16 = utf8_to_utf16_array!("asdf", 16);
  47. assert!(utf16 == [97, 115, 100, 102, 0,0,0,0,0,0,0,0,0,0,0,0])
  48. }
  49. #[test]
  50. fn utf8_to_utf16_array_unicode() {
  51. let utf16 = utf8_to_utf16_array!("あいうえお", 16);
  52. assert!(utf16 == [0x3042 , 0x3044, 0x3046, 0x3048, 0x304A, 0,0,0,0,0,0,0,0,0,0,0])
  53. }
  54. }