pub trait Read { // Required method fnread(&mut self, buf: &mut [u8]) ->Result<usize>; // Provided methods fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize> { ... } fnis_read_vectored(&self) ->bool { ... } fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize> { ... } fnread_to_string(&mut self, buf: &mutString) ->Result<usize> { ... } fnread_exact(&mut self, buf: &mut [u8]) ->Result<()> { ... } fnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()> { ... } fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()> { ... } fnby_ref(&mut self) -> &mut Selfwhere Self:Sized { ... } fnbytes(self) ->Bytes<Self>ⓘwhere Self:Sized { ... } fnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized { ... } fntake(self, limit:u64) ->Take<Self>ⓘwhere Self:Sized { ... }}
Expand description
TheRead
trait allows for reading bytes from a source.
Implementors of theRead
trait are called ‘readers’.
Readers are defined by one required method,read()
. Each call toread()
will attempt to pull bytes from this source into a provided buffer. Anumber of other methods are implemented in terms ofread()
, givingimplementors a number of ways to read bytes while only needing to implementa single method.
Readers are intended to be composable with one another. Many implementorsthroughoutstd::io
take and provide types which implement theRead
trait.
Please note that each call toread()
may involve a system call, andtherefore, using something that implementsBufRead
, such asBufReader
, will be more efficient.
Repeated calls to the reader use the same cursor, so for examplecallingread_to_end
twice on aFile
will only return the file’scontents once. It’s recommended to first callrewind()
in that case.
§Examples
File
s implementRead
:
usestd::io;usestd::io::prelude::*;usestd::fs::File;fnmain() -> io::Result<()> {letmutf = File::open("foo.txt")?;letmutbuffer = [0;10];// read up to 10 bytesf.read(&mutbuffer)?;letmutbuffer = Vec::new();// read the whole filef.read_to_end(&mutbuffer)?;// read into a String, so that you don't need to do the conversion.letmutbuffer = String::new(); f.read_to_string(&mutbuffer)?;// and more! See the other methods for more details.Ok(())}
Required Methods§
1.0.0 ·Sourcefnread(&mut self, buf: &mut [u8]) ->Result<usize>
fnread(&mut self, buf: &mut [u8]) ->Result<usize>
Pull some bytes from this source into the specified buffer, returninghow many bytes were read.
This function does not provide any guarantees about whether it blockswaiting for data, but if an object needs to block for a read and cannot,it will typically signal this via anErr
return value.
If the return value of this method isOk(n)
, then implementations mustguarantee that0 <= n <= buf.len()
. A nonzeron
value indicatesthat the bufferbuf
has been filled in withn
bytes of data from thissource. Ifn
is0
, then it can indicate one of two scenarios:
- This reader has reached its “end of file” and will likely no longerbe able to produce bytes. Note that this does not mean that thereader willalways no longer be able to produce bytes. As an example,on Linux, this method will call the
recv
syscall for aTcpStream
,where returning zero indicates the connection was shut down correctly. WhileforFile
, it is possible to reach the end of file and get zero as result,but if more data is appended to the file, future calls toread
will returnmore data. - The buffer specified was 0 bytes in length.
It is not an error if the returned valuen
is smaller than the buffer size,even when the reader is not at the end of the stream yet.This may happen for example because fewer bytes are actually available right now(e. g. being close to end-of-file) or because read() was interrupted by a signal.
As this trait is safe to implement, callers in unsafe code cannot rely onn <= buf.len()
for safety.Extra care needs to be taken whenunsafe
functions are used to access the read bytes.Callers have to ensure that no unchecked out-of-bounds accesses are possible even ifn > buf.len()
.
Implementations of this method can make no assumptions about the contents ofbuf
whenthis function is called. It is recommended that implementations only write data tobuf
instead of reading its contents.
Correspondingly, however,callers of this method in unsafe code must not assumeany guarantees about how the implementation usesbuf
. The trait is safe to implement,so it is possible that the code that’s supposed to write to the buffer might also readfrom it. It is your responsibility to make sure thatbuf
is initializedbefore callingread
. Callingread
with an uninitializedbuf
(of the kind oneobtains viaMaybeUninit<T>
) is not safe, and can lead to undefined behavior.
§Errors
If this function encounters any form of I/O or other error, an errorvariant will be returned. If an error is returned then it must beguaranteed that no bytes were read.
An error of theErrorKind::Interrupted
kind is non-fatal and the readoperation should be retried if there is nothing else to do.
§Examples
File
s implementRead
:
Provided Methods§
1.36.0 ·Sourcefnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>
fnread_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) ->Result<usize>
Likeread
, except that it reads into a slice of buffers.
Data is copied to fill each buffer in order, with the final bufferwritten to possibly being only partially filled. This method mustbehave equivalently to a single call toread
with concatenatedbuffers.
The default implementation callsread
with either the first nonemptybuffer provided, or an empty one if none exists.
Sourcefnis_read_vectored(&self) ->bool
🔬This is a nightly-only experimental API. (can_vector
#69941)
fnis_read_vectored(&self) ->bool
can_vector
#69941)Determines if thisRead
er has an efficientread_vectored
implementation.
If aRead
er does not override the defaultread_vectored
implementation, code using it may want to avoid the method all togetherand coalesce writes into a single buffer for higher performance.
The default implementation returnsfalse
.
1.0.0 ·Sourcefnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>
fnread_to_end(&mut self, buf: &mutVec<u8>) ->Result<usize>
Reads all bytes until EOF in this source, placing them intobuf
.
All bytes read from this source will be appended to the specified bufferbuf
. This function will continuously callread()
to append more data tobuf
untilread()
returns eitherOk(0)
or an error ofnon-ErrorKind::Interrupted
kind.
If successful, this function will return the total number of bytes read.
§Errors
If this function encounters an error of the kindErrorKind::Interrupted
then the error is ignored and the operationwill continue.
If any other read error is encountered then this function immediatelyreturns. Any bytes which have already been read will be appended tobuf
.
§Examples
File
s implementRead
:
usestd::io;usestd::io::prelude::*;usestd::fs::File;fnmain() -> io::Result<()> {letmutf = File::open("foo.txt")?;letmutbuffer = Vec::new();// read the whole filef.read_to_end(&mutbuffer)?;Ok(())}
(See also thestd::fs::read
convenience function for reading from afile.)
§Implementingread_to_end
When implementing theio::Read
trait, it is recommended to allocatememory usingVec::try_reserve
. However, this behavior is not guaranteedby all implementations, andread_to_end
may not handle out-of-memorysituations gracefully.
fnread_to_end(&mutself, dest_vec:&mutVec<u8>) -> io::Result<usize> {letinitial_vec_len = dest_vec.len();loop{letsrc_buf =self.example_datasource.fill_buf()?;ifsrc_buf.is_empty() {break; } dest_vec.try_reserve(src_buf.len())?; dest_vec.extend_from_slice(src_buf);// Any irreversible side effects should happen after `try_reserve` succeeds, // to avoid losing data on allocation error.letread = src_buf.len();self.example_datasource.consume(read); }Ok(dest_vec.len() - initial_vec_len)}
1.0.0 ·Sourcefnread_to_string(&mut self, buf: &mutString) ->Result<usize>
fnread_to_string(&mut self, buf: &mutString) ->Result<usize>
Reads all bytes until EOF in this source, appending them tobuf
.
If successful, this function returns the number of bytes which were readand appended tobuf
.
§Errors
If the data in this stream isnot valid UTF-8 then an error isreturned andbuf
is unchanged.
Seeread_to_end
for other error semantics.
§Examples
File
s implementRead
:
usestd::io;usestd::io::prelude::*;usestd::fs::File;fnmain() -> io::Result<()> {letmutf = File::open("foo.txt")?;letmutbuffer = String::new(); f.read_to_string(&mutbuffer)?;Ok(())}
(See also thestd::fs::read_to_string
convenience function forreading from a file.)
1.6.0 ·Sourcefnread_exact(&mut self, buf: &mut [u8]) ->Result<()>
fnread_exact(&mut self, buf: &mut [u8]) ->Result<()>
Reads the exact number of bytes required to fillbuf
.
This function reads as many bytes as necessary to completely fill thespecified bufferbuf
.
Implementations of this method can make no assumptions about the contents ofbuf
whenthis function is called. It is recommended that implementations only write data tobuf
instead of reading its contents. The documentation onread
has a more detailedexplanation of this subject.
§Errors
If this function encounters an error of the kindErrorKind::Interrupted
then the error is ignored and the operationwill continue.
If this function encounters an “end of file” before completely fillingthe buffer, it returns an error of the kindErrorKind::UnexpectedEof
.The contents ofbuf
are unspecified in this case.
If any other read error is encountered then this function immediatelyreturns. The contents ofbuf
are unspecified in this case.
If this function returns an error, it is unspecified how many bytes ithas read, but it will never read more than would be necessary tocompletely fill the buffer.
§Examples
File
s implementRead
:
Sourcefnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()>
🔬This is a nightly-only experimental API. (read_buf
#78485)
fnread_buf(&mut self, buf:BorrowedCursor<'_>) ->Result<()>
read_buf
#78485)Pull some bytes from this source into the specified buffer.
This is equivalent to theread
method, except that it is passed aBorrowedCursor
rather than[u8]
to allow usewith uninitialized buffers. The new data will be appended to any existing contents ofbuf
.
The default implementation delegates toread
.
This method makes it possible to return both data and an error but it is advised against.
Sourcefnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>
🔬This is a nightly-only experimental API. (read_buf
#78485)
fnread_buf_exact(&mut self, cursor:BorrowedCursor<'_>) ->Result<()>
read_buf
#78485)Reads the exact number of bytes required to fillcursor
.
This is similar to theread_exact
method, exceptthat it is passed aBorrowedCursor
rather than[u8]
to allow usewith uninitialized buffers.
§Errors
If this function encounters an error of the kindErrorKind::Interrupted
then the error is ignored and the operation will continue.
If this function encounters an “end of file” before completely fillingthe buffer, it returns an error of the kindErrorKind::UnexpectedEof
.
If any other read error is encountered then this function immediatelyreturns.
If this function returns an error, all bytes read will be appended tocursor
.
1.0.0 ·Sourcefnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
fnby_ref(&mut self) -> &mut Selfwhere Self:Sized,
Creates a “by reference” adaptor for this instance ofRead
.
The returned adapter also implementsRead
and will simply borrow thiscurrent reader.
§Examples
File
s implementRead
:
usestd::io;usestd::io::Read;usestd::fs::File;fnmain() -> io::Result<()> {letmutf = File::open("foo.txt")?;letmutbuffer = Vec::new();letmutother_buffer = Vec::new(); {letreference = f.by_ref();// read at most 5 bytesreference.take(5).read_to_end(&mutbuffer)?; }// drop our &mut reference so we can use f again // original file still usable, read the restf.read_to_end(&mutother_buffer)?;Ok(())}
1.0.0 ·Sourcefnbytes(self) ->Bytes<Self>ⓘwhere Self:Sized,
fnbytes(self) ->Bytes<Self>ⓘwhere Self:Sized,
Transforms thisRead
instance to anIterator
over its bytes.
The returned type implementsIterator
where theItem
isResult<u8,io::Error>
.The yielded item isOk
if a byte was successfully read andErr
otherwise. EOF is mapped to returningNone
from this iterator.
The default implementation callsread
for each byte,which can be very inefficient for data that’s not in memory,such asFile
. Consider using aBufReader
in such cases.
§Examples
File
s implementRead
:
1.0.0 ·Sourcefnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized,
fnchain<R:Read>(self, next: R) ->Chain<Self, R>ⓘwhere Self:Sized,
Creates an adapter which will chain this stream with another.
The returnedRead
instance will first read all bytes from this objectuntil EOF is encountered. Afterwards the output is equivalent to theoutput ofnext
.
§Examples
File
s implementRead
:
usestd::io;usestd::io::prelude::*;usestd::fs::File;fnmain() -> io::Result<()> {letf1 = File::open("foo.txt")?;letf2 = File::open("bar.txt")?;letmuthandle = f1.chain(f2);letmutbuffer = String::new();// read the value into a String. We could use any Read method here, // this is just one example.handle.read_to_string(&mutbuffer)?;Ok(())}
1.0.0 ·Sourcefntake(self, limit:u64) ->Take<Self>ⓘwhere Self:Sized,
fntake(self, limit:u64) ->Take<Self>ⓘwhere Self:Sized,
Creates an adapter which will read at mostlimit
bytes from it.
This function returns a new instance ofRead
which will read at mostlimit
bytes, after which it will always return EOF (Ok(0)
). Anyread errors will not count towards the number of bytes read and futurecalls toread()
may succeed.
§Examples
File
s implementRead
:
Implementors§
implRead for &File
implRead for &TcpStream
implRead for &PipeReader
implRead for &Stdin
implRead for &[u8]
Read is implemented for&[u8]
by copying from the slice.
Note that reading updates the slice to point to the yet unread part.The slice will be empty when EOF is reached.
implRead forFile
implRead forTcpStream
implRead forUnixStream
implRead forChildStderr
implRead forChildStdout
implRead forArc<File>
implRead forEmpty
implRead forPipeReader
implRead forRepeat
implRead forStdin
implRead forStdinLock<'_>
impl<'a>Read for &'aUnixStream
impl<A:Allocator>Read forVecDeque<u8, A>
Read is implemented forVecDeque<u8>
by consuming bytes from the front of theVecDeque
.