windowed_infinity/lib.rs
1//! This crate provides the [WindowedInfinity] struct, which is written to through its methods or
2//! [`embedded_io::Write`].
3//!
4//! Its purpose is to wrap a small buffer such that writes to it advance a cursor over a larger
5//! imaginary buffer, only persisting writes to the small buffer. After the buffer has been
6//! processed, a new WindowedInfinity can be set up and the writing process repeated. This is
7//! wasteful when the writes are computationally expensive, but convenient when operations only
8//! rarely exceed the buffer.
9//!
10//! A typical practical example of a WindowedInfinity application is the implementation of CoAP
11//! block-wise transfer according to [RFC7959](https://tools.ietf.org/html/rfc7959); a simpler
12//! example is available in the `demo.rs` example.
13//!
14//! Related crates
15//! --------------
16//!
17//! This crate provides the bare minimum functionality of Doing One Thing (hopefully) Right. Before
18//! adopting [`embedded_io::Write`] as The Interface to this crate, it used to provide a `Tee`
19//! adapter (now in [`tee-embedded-io`]) as well as implementing other `Write` traits or providing
20//! a compatible implementation into hashes and CRCs (now in [`extra-embedded-io-adapters`]). Those
21//! crates can be combined, for example, to build a combined writer that hashes its text input
22//! while preserving only a small portion in memory, thus allowing checked recombination of the
23//! parts (e.g. to provide an ETag value in CoAP block-wise transfer).
24#![no_std]
25
26/// A WindowedInfinity represents an infinite writable space. A small section of it is mapped to a
27/// &mut [u8] to which writes are forwarded; writes to the area outside only advance a cursor.
28pub struct WindowedInfinity<'a> {
29 view: &'a mut [u8],
30 cursor: isize,
31}
32
33impl<'a> WindowedInfinity<'a> {
34 /// Create a new infinity with the window passed as view. The cursor parameter indicates where
35 /// (in the index space of the view) the infinity's write operations should start, and is
36 /// typically either 0 or negative.
37 pub fn new(view: &'a mut [u8], cursor: isize) -> Self {
38 WindowedInfinity { view, cursor }
39 }
40
41 /// Report the current write cursor position in the index space of the view.
42 ///
43 /// This typically used at the end of an infinity's life time to see whether the view needs to
44 /// be truncated before further processing, and whether there was any data discarded after the
45 /// view.
46 pub fn cursor(&self) -> isize {
47 self.cursor
48 }
49
50 /// At the current cursor position, insert the given data.
51 ///
52 /// The operation is always successful, and at least changes the write cursor.
53 pub fn write(&mut self, data: &[u8]) {
54 let start = self.cursor;
55 // FIXME determine overflowing and wrapping behavior
56 self.cursor += data.len() as isize;
57 let end = self.cursor;
58
59 if end <= 0 {
60 // Not in view yet
61 return;
62 }
63
64 if start >= self.view.len() as isize {
65 // Already out of view
66 return;
67 }
68
69 #[rustfmt::skip]
70 let (fronttrim, start) = if start < 0 {
71 (-start, 0)
72 } else {
73 (0, start)
74 };
75 let data = &data[fronttrim as usize..];
76
77 let overshoot = start + data.len() as isize - self.view.len() as isize;
78 let (tailtrim, end) = if overshoot > 0 {
79 (overshoot, end - overshoot)
80 } else {
81 (0, end)
82 };
83 let data = &data[..data.len() - tailtrim as usize];
84 self.view[start as usize..end as usize].copy_from_slice(data);
85 }
86
87 /// Obtain the written content inside the window, if any.
88 ///
89 /// The slices could be made to have a longer lifetime if there is demand for that by using the
90 /// `sealingslice` crate.
91 pub fn written(&self) -> &[u8] {
92 if self.cursor > 0 {
93 // The unwrap_or case is only triggered in the pathological zero-length-view case.
94 self.view.chunks(self.cursor as usize).next().unwrap_or(&[])
95 } else {
96 &[]
97 }
98 }
99}
100
101impl embedded_io::ErrorType for WindowedInfinity<'_> {
102 type Error = core::convert::Infallible;
103}
104
105impl embedded_io::Write for WindowedInfinity<'_> {
106 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
107 self.write(buf);
108 Ok(buf.len())
109 }
110
111 fn flush(&mut self) -> Result<(), Self::Error> {
112 // No action needed; all writes go into the window immediately.
113 Ok(())
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use super::WindowedInfinity;
120
121 #[test]
122 fn zero_length() {
123 let mut data: [u8; 0] = [];
124 let mut writer = WindowedInfinity::new(&mut data, -10);
125 writer.write(&[42; 20]);
126 assert_eq!(writer.cursor(), 10);
127 assert_eq!(writer.written(), &[]);
128 }
129
130 #[test]
131 fn single_write() {
132 let mut data: [u8; 5] = [0; 5];
133 let mut writer = WindowedInfinity::new(&mut data, -10);
134 writer.write(&[42; 20]);
135 assert_eq!(writer.cursor(), 10);
136 assert_eq!(writer.written(), &[42; 5]);
137 assert_eq!(data, [42; 5]);
138 }
139
140 #[test]
141 fn small_chunks() {
142 let mut data: [u8; 5] = [0; 5];
143 let mut writer = WindowedInfinity::new(&mut data, -10);
144 for i in 0..10 {
145 writer.write(&[i as u8; 2]);
146 assert_eq!(writer.cursor(), -10 + (i + 1) * 2);
147 if i == 5 {
148 assert_eq!(writer.written(), &[5; 2]);
149 }
150 }
151 assert_eq!(writer.written(), [5, 5, 6, 6, 7]);
152 assert_eq!(data, [5, 5, 6, 6, 7]);
153 }
154
155 #[test]
156 fn write_embedded_io() {
157 use embedded_io::Write;
158
159 let mut data: [u8; 5] = [0; 5];
160 let mut writer = WindowedInfinity::new(&mut data, -10);
161 writer.write_all(b"Hello ").unwrap();
162 writer.flush().unwrap();
163
164 writer.write_fmt(format_args!("Worl{}", "d")).unwrap();
165 // It's 3 in other places b/c they encode a CBOR array and a string header, and we're just
166 // writing the text.
167 assert_eq!(writer.cursor(), 1);
168 }
169}