From 7aa0f907d559721964e2c8e9ec27f67d7308419b Mon Sep 17 00:00:00 2001 From: Jake Probst Date: Fri, 30 Aug 2019 00:57:25 -0700 Subject: [PATCH] utf8_to_utf16_array --- src/common/util.rs | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/common/util.rs b/src/common/util.rs index c88e214..0c85032 100644 --- a/src/common/util.rs +++ b/src/common/util.rs @@ -9,14 +9,6 @@ pub fn array_to_utf8(array: [u8; X]) -> Result(string: String) -> Result<[u8; X], std::string::FromUtf8Error> { - let mut array = [0u8; X]; - let bytes = string.as_bytes(); - array[..bytes.len()].clone_from_slice(&bytes); - Ok(array) -}*/ - #[macro_export] macro_rules! utf8_to_array { ($s: expr, $size: expr) => { @@ -29,6 +21,19 @@ macro_rules! utf8_to_array { } } +#[macro_export] +macro_rules! utf8_to_utf16_array { + ($s: expr, $size: expr) => { + { + let mut array = [0u16; $size]; + //let bytes = $s.as_bytes(); + let bytes = $s.encode_utf16().collect::>(); + array[..bytes.len()].clone_from_slice(&bytes); + array + } + } +} + @@ -43,4 +48,16 @@ mod test { e[..4].clone_from_slice(b"asdf"); assert!(a == e); } + + #[test] + fn utf8_to_utf16_array() { + let utf16 = utf8_to_utf16_array!("asdf", 16); + assert!(utf16 == [97, 115, 100, 102, 0,0,0,0,0,0,0,0,0,0,0,0]) + } + + #[test] + fn utf8_to_utf16_array_unicode() { + let utf16 = utf8_to_utf16_array!("あいうえお", 16); + assert!(utf16 == [0x3042 , 0x3044, 0x3046, 0x3048, 0x304A, 0,0,0,0,0,0,0,0,0,0,0]) + } }