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
#![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.

/// 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.
///
/// The set of traits it implements 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.
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 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 get_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 {
            &[]
        }
    }
}

#[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(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.get_cursor(), 10);
        assert_eq!(writer.get_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.get_cursor(), 10);
        assert_eq!(writer.get_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.get_cursor(), -10 + (i + 1) * 2);
            if i == 5 {
                assert_eq!(writer.get_written(), &[5; 2]);
            }
        }
        assert_eq!(writer.get_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.get_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.get_cursor(), 3);
    }
}