Browse Source

move util to libpso

pull/3/head
jake 5 years ago
parent
commit
ae521ccbb2
  1. 3
      src/lib.rs
  2. 63
      src/util.rs

3
src/lib.rs

@ -1,6 +1,9 @@
#![feature(const_generics)]
pub mod crypto; pub mod crypto;
pub mod packet; pub mod packet;
pub mod character; pub mod character;
pub mod util;
use std::io::Read; use std::io::Read;
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]

63
src/util.rs

@ -0,0 +1,63 @@
pub fn array_to_utf8<const X: usize>(array: [u8; X]) -> Result<String, std::string::FromUtf8Error> {
String::from_utf8(array.to_vec())
.map(|mut s| {
if let Some(index) = s.find("\u{0}") {
s.truncate(index);
}
s
})
}
// TODO: const fn version of this! (helpful with tests)
#[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
}
}
}
#[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::<Vec<_>>();
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);
}
#[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])
}
}
Loading…
Cancel
Save