From ac5919e44d4b19f859c45546294c248a3221c96c Mon Sep 17 00:00:00 2001 From: Jake Probst Date: Sat, 24 Aug 2019 14:45:33 -0700 Subject: [PATCH] utf8_to_array macro --- src/common/util.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/common/util.rs b/src/common/util.rs index ec13e9c..c88e214 100644 --- a/src/common/util.rs +++ b/src/common/util.rs @@ -7,5 +7,40 @@ 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) => { + { + let mut array = [0u8; $size]; + let bytes = $s.as_bytes(); + array[..bytes.len()].clone_from_slice(&bytes); + array + } + } +} + + + + +#[cfg(test)] +mod test { + #[test] + fn test_utf8_to_array() { + let s = "asdf".to_owned(); + let a = utf8_to_array!(s, 8); + let mut e = [0u8; 8]; + e[..4].clone_from_slice(b"asdf"); + assert!(a == e); + } }