Skip to content
This repository was archived by the owner on Nov 30, 2022. It is now read-only.

Commit a37f2be

Browse files
committed
Add take to literacy::Read trait
1 parent 9e49b27 commit a37f2be

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/literacy.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,14 @@
2626
pub trait Read {
2727
/// The error type returned in Result
2828
type Error;
29+
/// The type to implement limited reads
30+
type Take;
2931
/// see [std::io::Read::read]
3032
fn read(&mut self, buf: &mut [u8]) -> ::core::result::Result<usize, Self::Error>;
3133
/// see [std::io::Read::read_exact]
3234
fn read_exact(&mut self, buf: &mut [u8]) -> ::core::result::Result<(), Self::Error>;
35+
/// see [std::io::Read::take]
36+
fn take(self, limit: u64) -> Self::Take;
3337
}
3438

3539
/// The Write trait allows to write bytes in the object implementing it.
@@ -50,6 +54,7 @@ mod std_impl {
5054

5155
impl<R: ::std::io::Read> Read for R {
5256
type Error = ::std::io::Error;
57+
type Take = ::std::io::Take<R>;
5358

5459
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
5560
<Self as ::std::io::Read>::read(self, buf)
@@ -58,6 +63,11 @@ mod std_impl {
5863
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
5964
<Self as ::std::io::Read>::read_exact(self, buf)
6065
}
66+
67+
fn take(self, limit: u64) -> Self::Take {
68+
<Self as ::std::io::Read>::take(self, limit)
69+
}
70+
6171
}
6272

6373
impl<W: ::std::io::Write> Write for W {
@@ -83,6 +93,7 @@ mod core2_impl {
8393

8494
impl<R: core2::io::Read> Read for R {
8595
type Error = core2::io::Error;
96+
type Take = core2::io::Take<R>;
8697

8798
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
8899
<Self as core2::io::Read>::read(self, buf)
@@ -91,6 +102,10 @@ mod core2_impl {
91102
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
92103
<Self as core2::io::Read>::read_exact(self, buf)
93104
}
105+
106+
fn take(self, limit: u64) -> Self::Take {
107+
<Self as core2::io::Read>::take(self, limit)
108+
}
94109
}
95110

96111
impl<W: core2::io::Write> Write for W {
@@ -114,12 +129,14 @@ mod core2_impl {
114129
mod default_impl {
115130
use super::{Read, Write};
116131

132+
#[derive(Debug)]
117133
pub enum DefaultError {
118134
UnexpectedEof,
119135
}
120136

121-
impl Read for &[u8] {
137+
impl<'a> Read for &'a [u8] {
122138
type Error = DefaultError;
139+
type Take = &'a [u8];
123140

124141
fn read(&mut self, buf: &mut [u8]) -> ::core::result::Result<usize, Self::Error> {
125142
let amt = ::core::cmp::min(buf.len(), self.len());
@@ -156,6 +173,10 @@ mod default_impl {
156173
*self = b;
157174
Ok(())
158175
}
176+
177+
fn take(self, limit: u64) -> Self::Take {
178+
&self[..limit as usize]
179+
}
159180
}
160181

161182
impl Write for ::alloc::vec::Vec<u8> {

0 commit comments

Comments
 (0)