1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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)
}
}