Skip to main content

steel_utils/serial/
prefixed_write.rs

1use std::io::{Error, Result, Write};
2
3use crate::serial::{PrefixedWrite, WriteTo};
4
5impl PrefixedWrite for String {
6    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
7        &self,
8        writer: &mut impl Write,
9        bound: usize,
10    ) -> Result<()> {
11        if self.len() > bound {
12            return Err(Error::other("Too long"));
13        }
14
15        let len: P = self
16            .len()
17            .try_into()
18            .map_err(|_| Error::other("This cant happen"))?;
19        len.write(writer)?;
20
21        writer.write_all(self.as_bytes())
22    }
23}
24
25impl PrefixedWrite for str {
26    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
27        &self,
28        writer: &mut impl Write,
29        bound: usize,
30    ) -> Result<()> {
31        if self.len() > bound {
32            return Err(Error::other("Too long"));
33        }
34
35        let len: P = self
36            .len()
37            .try_into()
38            .map_err(|_| Error::other("This cant happen"))?;
39        len.write(writer)?;
40
41        writer.write_all(self.as_bytes())
42    }
43}
44
45impl<T: WriteTo> PrefixedWrite for Vec<T> {
46    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
47        &self,
48        writer: &mut impl Write,
49        bound: usize,
50    ) -> Result<()> {
51        self.as_slice().write_prefixed_bound::<P>(writer, bound)
52    }
53}
54
55impl<T: WriteTo> PrefixedWrite for [T] {
56    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
57        &self,
58        writer: &mut impl Write,
59        bound: usize,
60    ) -> Result<()> {
61        if self.len() > bound {
62            return Err(Error::other("Too long"));
63        }
64
65        let len: P = self
66            .len()
67            .try_into()
68            .map_err(|_| Error::other("This cant happen"))?;
69
70        len.write(writer)?;
71
72        T::write_slice(self, writer)
73    }
74}
75
76impl<T: WriteTo, const N: usize> PrefixedWrite for [T; N] {
77    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
78        &self,
79        writer: &mut impl Write,
80        bound: usize,
81    ) -> Result<()> {
82        self.as_slice().write_prefixed_bound::<P>(writer, bound)
83    }
84}
85
86impl<T: PrefixedWrite> PrefixedWrite for Option<T> {
87    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
88        &self,
89        writer: &mut impl Write,
90        bound: usize,
91    ) -> Result<()> {
92        if let Some(value) = self {
93            true.write(writer)?;
94            value.write_prefixed_bound::<P>(writer, bound)
95        } else {
96            false.write(writer)
97        }
98    }
99}