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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use crate::{
    result::{Result},
    lmem,
    util::{
        data::{d8},
        error::{DeviceFull, NoError},
    },
};
use core::{mem, fmt};

/// Objects that wrap a byte-stream for reading.
pub trait Read {
    /// Reads from the byte-stream into multiple buffers.
    ///
    /// [argument, buf]
    /// The buffers that will be filled.
    ///
    /// [return_value]
    /// Returns the total number of bytes read.
    ///
    /// = Remarks
    ///
    /// The method starts at the first buffer and fills a buffer completely before moving
    /// to the next one. A `0` return value usually signals end-of-file unless the
    /// implementation documentation says something else. Many functions and structures
    /// will assume the `0` <-> end-of-file equivalence.
    fn scatter_read(&mut self, buf: &mut [&mut [d8]]) -> Result<usize>;

    /// Reads from the byte-stream into a buffer.
    ///
    /// [argument, buf]
    /// The buffer that will be filled.
    ///
    /// [return_value]
    /// Returns the total number of bytes read.
    ///
    /// = Remarks
    ///
    /// :scatter: link:lrs::io::Read::scatter_read[scatter_read]
    ///
    /// If the length of the buffer is `0`, the meaning of a `0` return value is
    /// unspecified. Otherwise a return value of `0` signals End-Of-File.
    ///
    /// The default implementation calls {scatter} with a single buffer element.
    ///
    /// = See also
    ///
    /// * {scatter}
    fn read(&mut self, buf: &mut [d8]) -> Result<usize> {
        self.scatter_read(&mut [buf])
    }

    /// Tries to read bytes until the buffer is buffer.
    ///
    /// [argument, buf]
    /// The buffer that will be filled.
    ///
    /// [return_value]
    /// Returns the total number of bytes read.
    ///
    /// = Remarks
    ///
    /// :read: link:lrs::io::Read::read[read]
    ///
    /// The default implementation calls {read} multiple times until the buffer is full or
    /// `0` is returned. If an error occurs the error is returned immediately and all
    /// bytes read up to that point are lost. This convenience method should thus not be
    /// used in reliable programs.
    ///
    /// = See also
    ///
    /// * {read}
    fn read_all(&mut self, mut buf: &mut [d8]) -> Result<usize> {
        let mut read = 0;
        while buf.len() > 0 {
            match self.read(buf) {
                e @ Err(_) => return e,
                Ok(0) => break,
                Ok(n) => {
                    read += n;
                    buf = &mut buf[n..];
                }
            }
        }
        Ok(read)
    }
}

/// Objects that wrap a byte-stream for reading and contain a buffer.
pub trait BufRead : Read {
    /// Copies bytes from the stream to a writer until a certain byte occurs.
    ///
    /// [argument, dst]
    /// The writer into which the stream will be piped.
    ///
    /// [argument, b]
    /// The byte at which to stop.
    ///
    /// [return_value]
    /// Returns the total number of bytes copied.
    ///
    /// = Remarks
    ///
    /// The stop-byte itself is copied to the destination. The copied bytes are no longer
    /// available for further read operations. If an error occurs, the error is returned
    /// immediately. In this case no bytes are lost since all read bytes have already been
    /// copied to the dst variable. The number of copied bytes is lost unless the dst
    /// variable has a means to obtain the number of copied bytes.
    fn copy_until<W: Write>(&mut self, dst: &mut W, b: u8) -> Result<usize>;

    /// Removes a certain number of bytes from the buffer.
    ///
    /// [argument, num]
    /// The number of bytes to remove.
    ///
    /// [return_value]
    /// Returns the actual number of bytes removed.
    ///
    /// = Remarks
    ///
    /// The returned value can be less than the num argument because there are fewer than
    /// num bytes currently buffered.
    fn consume(&mut self, num: usize) -> usize;
}

/// Objects that wrap a byte-stream for writing.
pub trait Write {
    /// Writes multiple buffers to the byte-stream.
    ///
    /// [argument, buf]
    /// The buffers to be written.
    ///
    /// [return_value]
    /// Returns the total number of bytes written.
    ///
    /// = Remarks
    ///
    /// The method starts at the first buffer and writes each buffer completely before
    /// moving to the next one.
    fn gather_write(&mut self, buf: &[&[u8]]) -> Result<usize>;

    /// Write a buffer to the byte stream.
    ///
    /// [argument, buf]
    /// The buffer to be written.
    ///
    /// [return_value]
    /// Returns the total number of bytes written.
    ///
    /// = Remarks
    ///
    /// :gather: link:lrs::io::Write::gather_write[gather_write]
    ///
    /// The default implementation calls {gather} with a single buffer.
    ///
    /// = See also
    ///
    /// * {gather}
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        self.gather_write(&[buf])
    }

    fn flush(&mut self) -> Result<()>;

    /// Tries to write the complete buffer to the byte-stream.
    ///
    /// [argument, buf]
    /// The buffer to be written.
    ///
    /// [return_value]
    /// Returns the total number of bytes written.
    ///
    /// = Remarks
    ///
    /// :write: link:lrs::io::Write::write[write]
    ///
    /// The default implementation calls `write` multiple times until the whole buffer has
    /// been written. If an error occurs, the error is returned immediately and the number
    /// of bytes written is lost. This method should thus not be used in reliable
    /// applications.
    fn write_all(&mut self, mut buf: &[u8]) -> Result<usize> {
        let mut written = 0;
        while buf.len() > 0 {
            match self.write(buf) {
                e @ Err(_) => return e,
                Ok(0) => return Err(DeviceFull),
                Ok(n) => {
                    written += n;
                    buf = &buf[n..];
                }
            }
        }
        Ok(written)
    }

    /// Writes a string to the byte-stream.
    ///
    /// [argument, buf]
    /// The string to be written.
    ///
    /// [return_value]
    /// Returns the total number of bytes written.
    ///
    /// = Remarks
    ///
    /// This is a convenience method that simply calls `write`.
    fn write_str(&mut self, buf: &str) -> Result<usize> {
        self.write(buf.as_bytes())
    }

    fn write_fmt_linux(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
        // Create a shim which translates a Write to a fmt::Write and saves
        // off I/O errors. instead of discarding them
        struct Adaptor<'a, T: ?Sized + 'a> {
            inner: &'a mut T,
            error: Result<()>,
        }

        impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
            fn write_str(&mut self, s: &str) -> fmt::Result {
                match self.inner.write_all(s.as_bytes()) {
                    Ok(_) => Ok(()),
                    Err(e) => {
                        self.error = Err(e);
                        Err(fmt::Error)
                    }
                }
            }
        }

        let mut output = Adaptor { inner: self, error: Ok(()) };
        match fmt::write(&mut output, fmt) {
            Ok(()) => Ok(()),
            Err(..) => {
                // check if the error came from the underlying `Write` or not
                if output.error.is_err() {
                    output.error
                } else {
                    Err(NoError)
                }
            }
        }
    }

}

/// Objects that wrap a byte-stream for writing and contain a buffer.
pub trait BufWrite : Write {
    /// Reads bytes from a `Read` object and writes them to the stream until end-of-file.
    ///
    /// [argument, r]
    /// The object from which to read.
    ///
    /// [return_value]
    /// Returns the number of bytes written.
    ///
    /// = Remarks
    ///
    /// If an error occurs, the error is returned immediately and the number of bytes
    /// copied is lost. No data is lost even if an error occurs.
    fn read_to_eof<R>(&mut self, r: R) -> Result<usize>
        where R: Read;

    /// Reads up to a specified number of bytes for a `Read` object.
    ///
    /// [argument, r]
    /// The object from which to read.
    ///
    /// [argument, n]
    /// The maximum number of bytes to read.
    fn read<R>(&mut self, r: R, n: usize) -> Result<usize>
        where R: Read;
}

impl<'a> Read for &'a [u8] {
    fn scatter_read(&mut self, mut buf: &mut [&mut [d8]]) -> Result<usize> {
        let mut sum = 0;
        while self.len() > 0 && buf.len() > 0 {
            sum += self.read(&mut buf[0])?;
            let b = buf;
            buf = &mut b[1..];
        }
        Ok(sum)
    }

    fn read(&mut self, buf: &mut [d8]) -> Result<usize> {
        let n = lmem::copy(buf, d8::from_byte_slice(*self));
        *self = &self[n..];
        Ok(n)
    }
}

impl<'a> BufRead for &'a [u8] {
    fn copy_until<W: Write+?Sized>(&mut self, dst: &mut W, b: u8) -> Result<usize> {
        let mut len = match memchr::memchr(b, self) {
            Some(pos) => pos + 1,
            _ => self.len(),
        };
        let total = len;
        while len > 0 {
            let consumed = match dst.write(&self[..len])? {
                0 => break,
                n => n,
            };
            len -= consumed;
            self.consume(consumed);
        }
        Ok(total - len)
    }

    fn consume(&mut self, num: usize) -> usize {
        let num = num.min(self.len());
        *self = &self[num..];
        num
    }
}

impl<'a> Write for &'a mut [u8] {
    fn gather_write(&mut self, mut buf: &[&[u8]]) -> Result<usize> {
        let mut sum = 0;
        while self.len() > 0 && buf.len() > 0 {
            sum += self.write(&buf[0])?;
            buf = &buf[1..];
        }
        Ok(sum)
    }

    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let n = lmem::copy(*self, buf);
        unsafe {
            // Compiler bug.
            *self = mem::transmute::<&mut [u8], &'a mut [u8]>(&mut self[n..]);
        }
        Ok(n)
    }

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

impl<'a> Write for &'a mut [d8] {
    fn gather_write(&mut self, mut buf: &[&[u8]]) -> Result<usize> {
        let mut sum = 0;
        while self.len() > 0 && buf.len() > 0 {
            sum += self.write(&buf[0])?;
            buf = &buf[1..];
        }
        Ok(sum)
    }

    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let n = lmem::copy(*self, d8::from_byte_slice(buf));
        unsafe {
            // Compiler bug.
            *self = mem::transmute::<&mut [d8], &'a mut [d8]>(&mut self[n..]);
        }
        Ok(n)
    }

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

impl<'a, T: Read+?Sized> Read for &'a mut T {
    fn scatter_read(&mut self, buf: &mut [&mut [d8]]) -> Result<usize> {
        (**self).scatter_read(buf)
    }

    fn read(&mut self, buf: &mut [d8]) -> Result<usize> {
        (**self).read(buf)
    }

    fn read_all(&mut self, mut buf: &mut [d8]) -> Result<usize> {
        (**self).read_all(buf)
    }
}

impl<'a, T: Write+?Sized> Write for &'a mut T {
    fn gather_write(&mut self, buf: &[&[u8]]) -> Result<usize> {
        (**self).gather_write(buf)
    }

    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        (**self).write(buf)
    }

    fn flush(&mut self) -> Result<()> {
        (**self).flush()
    }

    fn write_all(&mut self, buf: &[u8]) -> Result<usize> {
        (**self).write_all(buf)
    }

    fn write_str(&mut self, buf: &str) -> Result<usize> {
        (**self).write_str(buf)
    }
}