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};

/// Pico drivers require strings as *mut i8. This converts from Rust
/// to Pico string format
pub trait ToPicoStr {
    /// Converts Rust strings to Pico null terminated Vec<i8> format
    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()
    }
}

/// Pico drivers return strings as *i8. This converts from Pico to Rust string
/// formats
pub trait FromPicoStr {
    /// Converts from Pico null terminated Vec<i8> string format to Rust Strings
    #[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")
            // This should not be required but older versions of the 5000a
            // driver return the wrong buf_len for the driver version string.
            // This trims the extra nulls that we get in the buffer
            .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";
        // Add a load of nulls on the end
        let ps = [s1.into_pico_i8_string(), vec![0; 200]].concat();
        let s2 = ps.from_pico_i8_string(ps.len());
        assert_eq!(s1, s2)
    }
}