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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#![cfg_attr(not(feature = "std"), no_std)]
//! This crate provides the [WindowedInfinity] struct and implementations of various traits to
//! write to it.
//!
//! Its primary is to wrap a small buffer such that writes to it advance a cursor over a larger
//! imaginary buffer, only persisting writes to the small buffer. After the buffer has been
//! processed, a new WindowedInfinity can be set up and the writing process repeated. This is
//! wasteful when the writes are computationally expensive, but convenient when operations only
//! rarely exceed the buffer.
//!
//! A typical practical example of WindowedInfinity application is the implementation of CoAP
//! block-wise transfer according to [RFC7959](https://tools.ietf.org/html/rfc7959); a simpler
//! example is available in the `demo.rs` example.
//!
//! Features
//! --------
//!
//! The set of traits implemented by [WindowedInfinity] depends on the configured cargo features:
//!
//! * With the `std` feature, it implements [std::io::Write](https://doc.rust-lang.org/std/io/trait.Write.html)
//! * With the `with_serde_cbor` feature, it uses
//!   [serde_cbor](https://crates.io/crates/serde_cbor)'s trait unsealing feature to implement its
//!   [Write](https://docs.rs/serde_cbor/*/serde_cbor/ser/trait.Write.html) trait.
//! * Likewise, there are features for ciborium and minicbor. The minicbor version is a bit special
//!   in that there is both a `with_minicbor` / `with_minicbor_0_19` feature.
//! * Starting at `with_minicbor_0_19`, features carry a version. This allows users of different
//!   minicbor versions to coexist in the same crate, and moreover ensures that the dependencies
//!   expressed in the Cargo.toml files to describe the requirements precisely.
//! * With the `with_embedded_io_0_4` feature, the Write trait of embedded-io is implemented.
//!
//! Crate size
//! ----------
//!
//! Compared to the original plan of "doing one thing, and doing that right", this crate has grown
//! a bit, in that it contains trait implementations for several serializers, and extra mechanism
//! for combining the own writer with others (from cryptographic digests or CRCs). Both these are
//! temporary -- once there is a 1.0 version of embedded-io, the Tee will be split out into a
//! dedicated crate (with only compatibility re-exports and constructors / destructors remaining),
//! and once serializers start using the stable embedded-io, no more writer implementations will
//! need to be added.

mod tee;
mod wrappers;

/// Return type for [`WindowedInfinity::tee_digest()`]
///
/// This implements all the same writers as [`WindowedInfinity`], and can be destructured
/// `.into_windowed_and_digest(self) -> (WindowedInfinity, D)`.
pub type TeeForDigest<'a, D> = tee::Tee<WindowedInfinity<'a>, wrappers::WritableDigest<D>>;
/// Return type for [`WindowedInfinity::tee_crc32()`] and 64
///
/// This implements all the same writers as [`WindowedInfinity`], and can be destructured
/// `.into_windowed_and_crc(self) -> (WindowedInfinity, crc::Digest<'c, W>)`.
pub type TeeForCrc<'a, 'c, W> = tee::Tee<WindowedInfinity<'a>, wrappers::WritableCrc<'c, W>>;

/// A local trait standing in for embedded_io::blocking::Write while we don't have a stable version
/// to depend on and re-export publicly
///
/// The semantics of write are those of the write_all of embedded_io; the error would be in a
/// separate trait there.
trait MyWrite {
    type Error;
    fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
    fn flush(&mut self) -> Result<(), Self::Error>;
}

/// A WindowedInfinity represents an infinite writable space. A small section of it is mapped to a
/// &mut [u8] to which writes are forwarded; writes to the area outside only advance a cursor.
pub struct WindowedInfinity<'a> {
    view: &'a mut [u8],
    cursor: isize,
}

impl<'a> WindowedInfinity<'a> {
    /// Create a new infinity with the window passed as view. The cursor parameter indicates where
    /// (in the index space of the view) the infinity's write operations should start, and is
    /// typically either 0 or negative.
    pub fn new(view: &'a mut [u8], cursor: isize) -> Self {
        WindowedInfinity { view, cursor }
    }

    /// Report the current write cursor position in the index space of the view.
    ///
    /// This typically used at the end of an infinity's life time to see whether the view needs to
    /// be truncated before further processing, and whether there was any data discarded after the
    /// view.
    pub fn cursor(&self) -> isize {
        self.cursor
    }

    #[deprecated(note = "Renamed to .cursor()")]
    pub fn get_cursor(&self) -> isize {
        self.cursor()
    }

    /// At the current cursor position, insert the given data.
    ///
    /// The operation is always successful, and at least changes the write cursor.
    pub fn write(&mut self, data: &[u8]) {
        let start = self.cursor;
        // FIXME determine overflowing and wrapping behavior
        self.cursor += data.len() as isize;
        let end = self.cursor;

        if end <= 0 {
            // Not in view yet
            return;
        }

        if start >= self.view.len() as isize {
            // Already out of view
            return;
        }

        #[rustfmt::skip]
        let (fronttrim, start) = if start < 0 {
            (-start, 0)
        } else {
            (0, start)
        };
        let data = &data[fronttrim as usize..];

        let overshoot = start + data.len() as isize - self.view.len() as isize;
        let (tailtrim, end) = if overshoot > 0 {
            (overshoot, end - overshoot)
        } else {
            (0, end)
        };
        let data = &data[..data.len() - tailtrim as usize];
        self.view[start as usize..end as usize].copy_from_slice(data);
    }

    /// Obtain the written content inside the window, if any.
    ///
    /// The slices could be made to have a longer lifetime if there is demand for that by using the
    /// `sealingslice` crate.
    pub fn written(&self) -> &[u8] {
        if self.cursor > 0 {
            // The unwrap_or case is only triggered in the pathological zero-length-view case.
            self.view.chunks(self.cursor as usize).next().unwrap_or(&[])
        } else {
            &[]
        }
    }

    #[deprecated(note = "Renamed to .written()")]
    pub fn get_written(&self) -> &[u8] {
        self.written()
    }

    /// Create a Tee (a T-shaped writer) that writes both to this WindowedInfinity and some
    /// [digest::Digest].
    ///
    /// The resulting type implements all the same writers as the WindowedInfinity, and offers an
    /// `into_windowed_and_digest(self) -> (WindowedInfinity, Digest)` to get both back after
    /// writing as completed.
    pub fn tee_digest<D: digest::Digest>(
        self,
    ) -> TeeForDigest<'a, D> {
        tee::Tee {
            w1: self,
            w2: wrappers::WritableDigest(D::new()),
        }
    }

    /// Create a Tee (a T-shaped writer) that writes both to this WindowedInfinity and some
    /// [crc::Digest].
    ///
    /// This is limited to u64 CRCs due to <https://github.com/mrhooray/crc-rs/issues/79>, and
    /// indirectly the availability of const traits.
    pub fn tee_crc64<'c>(self, crc: &'c crc::Crc<u64>) -> TeeForCrc<'a, 'c, u64> {
        tee::Tee { w1: self, w2: wrappers::WritableCrc(crc.digest()) }
    }

    /// Create a Tee (a T-shaped writer) that writes both to this WindowedInfinity and some
    /// [crc::Digest].
    ///
    /// This is limited to u32 CRCs due to <https://github.com/mrhooray/crc-rs/issues/79>, and
    /// indirectly the availability of const traits.
    pub fn tee_crc32<'c>(self, crc: &'c crc::Crc<u32>) -> TeeForCrc<'a, 'c, u32> {
        tee::Tee { w1: self, w2: wrappers::WritableCrc(crc.digest()) }
    }
}

impl MyWrite for WindowedInfinity<'_> {
    type Error = core::convert::Infallible;

    fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        self.write(buf);
        Ok(())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

#[cfg(feature = "std")]
impl std::io::Write for WindowedInfinity<'_> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.write(buf);
        // As far as success is concerned, everything was written; that not all of it (or none of
        // it) may have made its way to memory is immaterial.
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl<'a> core::fmt::Write for WindowedInfinity<'a> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
        Ok(self.write(s.as_bytes()))
    }
}

#[cfg(feature = "serde_cbor")]
impl<'a> serde_cbor::ser::Write for WindowedInfinity<'a> {
    // To be changed to ! once that's stable and implements Into-all
    type Error = serde_cbor::error::Error;

    fn write_all(&mut self, buf: &[u8]) -> Result<(), serde_cbor::error::Error> {
        Ok(self.write(buf))
    }
}

#[cfg(feature = "with_minicbor")]
impl<'a> minicbor::encode::Write for WindowedInfinity<'a> {
    type Error = core::convert::Infallible;

    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Ok(self.write(buf))
    }
}

#[cfg(feature = "with_minicbor_0_19")]
impl<'a> minicbor_0_19::encode::Write for WindowedInfinity<'a> {
    type Error = core::convert::Infallible;

    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Ok(self.write(buf))
    }
}

#[cfg(feature = "with_ciborium")]
impl<'a> ciborium_io::Write for WindowedInfinity<'a> {
    type Error = core::convert::Infallible;

    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        Ok(self.write(buf))
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

#[cfg(feature = "with_embedded_io_0_4")]
impl<'a> embedded_io::Io for WindowedInfinity<'a> {
    type Error = core::convert::Infallible;
}

#[cfg(feature = "with_embedded_io_0_4")]
impl<'a> embedded_io::blocking::Write for WindowedInfinity<'a> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write(buf);

        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::WindowedInfinity;

    #[test]
    fn zero_length() {
        let mut data: [u8; 0] = [];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        writer.write(&[42; 20]);
        assert_eq!(writer.cursor(), 10);
        assert_eq!(writer.written(), &[]);
    }

    #[test]
    fn single_write() {
        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        writer.write(&[42; 20]);
        assert_eq!(writer.cursor(), 10);
        assert_eq!(writer.written(), &[42; 5]);
        assert_eq!(data, [42; 5]);
    }

    #[test]
    fn small_chunks() {
        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        for i in 0..10 {
            writer.write(&[i as u8; 2]);
            assert_eq!(writer.cursor(), -10 + (i + 1) * 2);
            if i == 5 {
                assert_eq!(writer.written(), &[5; 2]);
            }
        }
        assert_eq!(writer.written(), [5, 5, 6, 6, 7]);
        assert_eq!(data, [5, 5, 6, 6, 7]);
    }

    #[cfg(feature = "std")]
    #[test]
    fn single_write_std() {
        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        std::io::Write::write(&mut writer, &[42; 20]).unwrap();
        assert_eq!(writer.cursor(), 10);
    }

    #[cfg(feature = "with_serde_cbor")]
    #[test]
    fn single_write_cbor() {
        use serde::ser::Serialize;

        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        let cbordata = ["Hello World"];
        cbordata
            .serialize(&mut serde_cbor::ser::Serializer::new(&mut writer))
            .unwrap();
        assert_eq!(writer.cursor(), 3);
    }

    #[cfg(feature = "with_minicbor")]
    #[test]
    fn single_write_minicbor() {
        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        minicbor::encode(&["Hello World"], &mut writer).unwrap();
        assert_eq!(writer.cursor(), 3);
    }

    #[cfg(feature = "with_minicbor_0_19")]
    #[test]
    fn single_write_minicbor_0_19() {
        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        minicbor_0_19::encode(&["Hello World"], &mut writer).unwrap();
        assert_eq!(writer.cursor(), 3);
    }

    #[cfg(feature = "with_ciborium")]
    #[test]
    fn single_write_cborium() {
        use ciborium_ll;

        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        let mut encoder = ciborium_ll::Encoder::from(&mut writer);
        encoder.push(ciborium_ll::Header::Array(Some(1))).unwrap();
        encoder.text("Hello World", None).unwrap();
        assert_eq!(writer.cursor(), 3);
    }

    #[cfg(feature = "with_embedded_io_0_4")]
    #[test]
    fn write_embedded_io_blocking() {
        use embedded_io::blocking::Write;

        let mut data: [u8; 5] = [0; 5];
        let mut writer = WindowedInfinity::new(&mut data, -10);
        writer.write_all(b"Hello ").unwrap();
        writer.flush().unwrap();

        writer.write_fmt(format_args!("Worl{}", "d")).unwrap();
        // It's 3 in other places b/c they encode a CBOR array and a string header, and we're just
        // writing the text.
        assert_eq!(writer.cursor(), 1);
    }
}