use std::{ffi::CString, str};
pub trait ToPicoStr {
fn into_pico_i8_string(self) -> Vec<i8>;
}
impl<'a> ToPicoStr for &'a str {
fn into_pico_i8_string(self) -> Vec<i8> {
CString::new(self)
.expect("invalid CString")
.into_bytes_with_nul()
.iter()
.map(|&x| x as i8)
.collect()
}
}
pub trait FromPicoStr {
#[allow(clippy::wrong_self_convention)]
fn from_pico_i8_string(self, buf_len: usize) -> String;
}
impl FromPicoStr for &[i8] {
fn from_pico_i8_string(self, buf_len: usize) -> String {
let serial_vec: Vec<u8> = self[..(buf_len - 1)].iter().map(|&x| x as u8).collect();
str::from_utf8(&serial_vec)
.expect("invalid utf8 string")
.trim_matches(char::from(0))
.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pico_strings() {
let s1 = "something here";
let ps = s1.into_pico_i8_string();
assert_eq!(
ps,
vec![115, 111, 109, 101, 116, 104, 105, 110, 103, 32, 104, 101, 114, 101, 0]
);
let s2 = ps.from_pico_i8_string(ps.len());
assert_eq!(s1, s2)
}
#[test]
fn pico_strings_ps5000a_bug() {
let s1 = "something here";
let ps = [s1.into_pico_i8_string(), vec![0; 200]].concat();
let s2 = ps.from_pico_i8_string(ps.len());
assert_eq!(s1, s2)
}
}