android_usb_serial/
rx_filter.rs1use crate::xonxoff::XonXoffFilter;
4
5const FTDI_READ_HEADER: usize = 2;
6
7pub fn strip_ftdi_header(packet: &[u8], mps: usize) -> Vec<u8> {
9 let mut out = Vec::new();
10 let mut pos = 0;
11 while pos < packet.len() {
12 let chunk = (pos + mps).min(packet.len());
13 if chunk - pos <= FTDI_READ_HEADER {
14 break;
15 }
16 out.extend_from_slice(&packet[pos + FTDI_READ_HEADER..chunk]);
17 pos += mps;
18 }
19 out
20}
21
22pub trait RxFilter: Send {
23 fn filter(&mut self, input: &[u8]) -> Vec<u8>;
24}
25
26pub struct FtdiHeaderFilter {
27 mps: usize,
28}
29
30impl FtdiHeaderFilter {
31 pub fn new(mps: u16) -> Self {
32 Self {
33 mps: mps.max(1) as usize,
34 }
35 }
36}
37
38impl RxFilter for FtdiHeaderFilter {
39 fn filter(&mut self, input: &[u8]) -> Vec<u8> {
40 strip_ftdi_header(input, self.mps)
41 }
42}
43
44pub struct XonXoffRxFilter {
45 inner: XonXoffFilter,
46}
47
48impl XonXoffRxFilter {
49 pub fn new(enabled: bool) -> Self {
50 Self {
51 inner: XonXoffFilter::new(enabled),
52 }
53 }
54}
55
56impl RxFilter for XonXoffRxFilter {
57 fn filter(&mut self, input: &[u8]) -> Vec<u8> {
58 self.inner.filter(input)
59 }
60}
61
62pub struct ChainedRxFilter {
63 filters: Vec<Box<dyn RxFilter>>,
64}
65
66impl ChainedRxFilter {
67 pub fn new(filters: Vec<Box<dyn RxFilter>>) -> Self {
68 Self { filters }
69 }
70}
71
72impl RxFilter for ChainedRxFilter {
73 fn filter(&mut self, input: &[u8]) -> Vec<u8> {
74 let mut data = input.to_vec();
75 for f in &mut self.filters {
76 data = f.filter(&data);
77 }
78 data
79 }
80}
81
82pub fn apply_filters(filters: &mut [Box<dyn RxFilter>], input: &[u8]) -> Vec<u8> {
83 let mut data = input.to_vec();
84 for f in filters.iter_mut() {
85 data = f.filter(&data);
86 }
87 data
88}