Skip to main content

tranche/
std.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7use core::cmp;
8use core::str;
9
10use std::error::Error;
11use std::io;
12
13use crate::{BasedBufTranche, BufTranche, UnexpectedEndError};
14
15impl io::Read for BufTranche<'_> {
16    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
17        let slice = self
18            .take_front(cmp::max(self.len(), buf.len()))
19            .unwrap()
20            .as_slice();
21        let len = slice.len();
22        if len == 1 {
23            buf[0] = slice[0];
24        } else {
25            buf[..len].copy_from_slice(slice);
26        }
27        Ok(len)
28    }
29}
30
31impl io::Read for BasedBufTranche<'_> {
32    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
33        self.inner.read(buf)
34    }
35}
36
37impl io::BufRead for BufTranche<'_> {
38    fn fill_buf(&mut self) -> io::Result<&[u8]> {
39        Ok(self.as_slice())
40    }
41
42    fn consume(&mut self, len: usize) {
43        if let Err(err) = self.take_front(len) {
44            panic!("{}", err);
45        }
46    }
47}
48
49impl io::BufRead for BasedBufTranche<'_> {
50    fn fill_buf(&mut self) -> io::Result<&[u8]> {
51        self.inner.fill_buf()
52    }
53
54    fn consume(&mut self, len: usize) {
55        self.inner.consume(len)
56    }
57}
58
59impl From<UnexpectedEndError> for io::Error {
60    fn from(error: UnexpectedEndError) -> Self {
61        io::Error::new(io::ErrorKind::UnexpectedEof, error)
62    }
63}
64
65impl Error for UnexpectedEndError {
66    fn description(&self) -> &str {
67        "unexpected end"
68    }
69}