windowed-infinity 0.2.0

A data structure representing an infinite sequentially writable u8 vector of which a small view has writes to it preserved. This is primarily useful when implementing CoAP block-wise transfers, and also convenient for logging on constrained devices.
Documentation
//! This crate provides the [WindowedInfinity] struct, which is written to through its methods or
//! [`embedded_io::Write`].
//!
//! Its purpose 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 a 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.
//!
//! Related crates
//! --------------
//!
//! This crate provides the bare minimum functionality of Doing One Thing (hopefully) Right. Before
//! adopting [`embedded_io::Write`] as The Interface to this crate, it used to provide a `Tee`
//! adapter (now in [`tee-embedded-io`]) as well as implementing other `Write` traits or providing
//! a compatible implementation into hashes and CRCs (now in [`extra-embedded-io-adapters`]). Those
//! crates can be combined, for example, to build a combined writer that hashes its text input
//! while preserving only a small portion in memory, thus allowing checked recombination of the
//! parts (e.g. to provide an ETag value in CoAP block-wise transfer).
#![no_std]

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

    /// 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 {
            &[]
        }
    }
}

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

impl embedded_io::Write for WindowedInfinity<'_> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
        self.write(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        // No action needed; all writes go into the window immediately.
        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]);
    }

    #[test]
    fn write_embedded_io() {
        use embedded_io::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);
    }
}