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.

77 lines
1.9 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. // TODO: const fn version of this! (helpful with tests)
  17. #[macro_export]
  18. macro_rules! utf8_to_array {
  19. ($s: expr, $size: expr) => {
  20. {
  21. let mut array = [0u8; $size];
  22. let bytes = $s.as_bytes();
  23. array[..bytes.len()].clone_from_slice(&bytes);
  24. array
  25. }
  26. }
  27. }
  28. #[macro_export]
  29. macro_rules! utf8_to_utf16_array {
  30. ($s: expr, $size: expr) => {
  31. {
  32. let mut array = [0u16; $size];
  33. //let bytes = $s.as_bytes();
  34. let bytes = $s.encode_utf16().collect::<Vec<_>>();
  35. array[..bytes.len()].clone_from_slice(&bytes);
  36. array
  37. }
  38. }
  39. }
  40. pub fn vec_to_array<T: Default + Copy, const N: usize>(vec: Vec<T>) -> [T; N] {
  41. let mut result: [T; N] = [T::default(); N];
  42. for (i, v) in vec.into_iter().enumerate() {
  43. result[i] = v
  44. }
  45. result
  46. }
  47. #[cfg(test)]
  48. mod test {
  49. #[test]
  50. fn test_utf8_to_array() {
  51. let s = "asdf".to_owned();
  52. let a = utf8_to_array!(s, 8);
  53. let mut e = [0u8; 8];
  54. e[..4].clone_from_slice(b"asdf");
  55. assert!(a == e);
  56. }
  57. #[test]
  58. fn utf8_to_utf16_array() {
  59. let utf16 = utf8_to_utf16_array!("asdf", 16);
  60. assert!(utf16 == [97, 115, 100, 102, 0,0,0,0,0,0,0,0,0,0,0,0])
  61. }
  62. #[test]
  63. fn utf8_to_utf16_array_unicode() {
  64. let utf16 = utf8_to_utf16_array!("あいうえお", 16);
  65. assert!(utf16 == [0x3042 , 0x3044, 0x3046, 0x3048, 0x304A, 0,0,0,0,0,0,0,0,0,0,0])
  66. }
  67. }