Io Stream Read and Read Again
Trait std::io::Read one.0.0 [−] [src]
pub trait Read { fn read(&mut self, buf: &mut [u8]) -> Result<usize>; fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> { ... } fn is_read_vectored(&self) -> bool { ... } fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> { ... } fn read_to_string(&mut cocky, buf: &mut Cord) -> Result<usize> { ... } fn read_exact(&mut cocky, buf: &mut [u8]) -> Result<()> { ... } fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Upshot<()> { ... } fn read_buf_exact(&mut cocky, buf: &mut ReadBuf<'_>) -> Result<()> { ... } fn by_ref(&mut self) -> &mut Self
where
Cocky: Sized, { ... } fn bytes(cocky) -> Bytes<Cocky> ⓘ Notable traits for Bytes<R>
impl<R: Read> Iterator for Bytes<R> blazon Particular = Upshot<u8>;
where
Self: Sized, { ... } fn chain<R: Read>(self, adjacent: R) -> Chain<Self, R> ⓘ Notable traits for Chain<T, U>
impl<T: Read, U: Read> Read for Chain<T, U>
where
Self: Sized, { ... } fn take(cocky, limit: u64) -> Take<Cocky> ⓘ Notable traits for Accept<T>
impl<T: Read> Read for Accept<T>
where
Cocky: Sized, { ... } } Expand clarification
The Read trait allows for reading bytes from a source.
Implementors of the Read trait are called 'readers'.
Readers are defined by ane required method, read(). Each call to read() will attempt to pull bytes from this source into a provided buffer. A number of other methods are implemented in terms of read(), giving implementors a number of means to read bytes while but needing to implement a unmarried method.
Readers are intended to be composable with 1 another. Many implementors throughout std::io take and provide types which implement the Read trait.
Please notation that each call to read() may involve a system phone call, and therefore, using something that implements BufRead, such as BufReader, will be more efficient.
Files implement Read:
utilise std::io; utilise std::io::prelude::*; use std::fs::File; fn main() -> io::Result <()> { allow mut f = File::open("foo.txt")?; let mut buffer = [0; 10]; // read up to ten bytes f.read(&mut buffer)?; permit mut buffer = Vec::new(); // read the whole file f.read_to_end(&mut buffer)?; // read into a Cord, so that you don't demand to exercise the conversion. let mut buffer = String::new(); f.read_to_string(&mut buffer)?; // and more than! See the other methods for more than details. Ok(()) } Run
Read from &str because &[u8] implements Read:
employ std::io::prelude::*; fn primary() -> io::Result <()> { let mut b = "This string volition exist read".as_bytes(); allow mut buffer = [0; 10]; // read upwardly to 10 bytes b.read(&mut buffer)?; // etc... it works exactly as a File does! Ok(()) } Run
Pull some bytes from this source into the specified buffer, returning how many bytes were read.
This function does not provide any guarantees about whether it blocks waiting for data, merely if an object needs to block for a read and cannot, information technology will typically point this via an Err render value.
If the render value of this method is Ok(n), and so implementations must guarantee that 0 <= n <= buf.len(). A nonzero n value indicates that the buffer buf has been filled in with north bytes of data from this source. If n is 0, then it can indicate one of ii scenarios:
- This reader has reached its "cease of file" and volition likely no longer exist able to produce bytes. Note that this does not mean that the reader volition always no longer be able to produce bytes. Every bit an example, on Linux, this method will call the
recvsyscall for aTcpStream, where returning zero indicates the connexion was close down correctly. While forFile, it is possible to reach the end of file and get zero as outcome, merely if more than information is appended to the file, future calls toreadwill render more data. - The buffer specified was 0 bytes in length.
Information technology is not an error if the returned value n is smaller than the buffer size, even when the reader is not at the terminate of the stream yet. This may happen for example because fewer bytes are actually available right now (due east. g. beingness close to cease-of-file) or because read() was interrupted by a point.
As this trait is safe to implement, callers cannot rely on n <= buf.len() for condom. Actress care needs to be taken when unsafe functions are used to access the read bytes. Callers have to ensure that no unchecked out-of-bounds accesses are possible even if n > buf.len().
No guarantees are provided about the contents of buf when this function is called, implementations cannot rely on whatsoever holding of the contents of buf being true. Information technology is recommended that implementations only write data to buf instead of reading its contents.
Correspondingly, however, callers of this method must non presume any guarantees nearly how the implementation uses buf. The trait is safe to implement, so it is possible that the code that'south supposed to write to the buffer might also read from it. Information technology is your responsibility to make sure that buf is initialized before calling read. Calling read with an uninitialized buf (of the kind one obtains via MaybeUninit<T>) is not prophylactic, and can pb to undefined behavior.
If this function encounters any form of I/O or other error, an error variant will be returned. If an mistake is returned so information technology must be guaranteed that no bytes were read.
An error of the ErrorKind::Interrupted kind is non-fatal and the read operation should be retried if there is nothing else to do.
Files implement Read:
apply std::io; use std::io::prelude::*; use std::fs::File; fn main() -> io::Issue <()> { let mut f = File::open up("foo.txt")?; permit mut buffer = [0; 10]; // read up to ten bytes let due north = f.read(&mut buffer[..])?; println!("The bytes: {:?}", & buffer[..north]); Ok(()) } Run
Like read, except that it reads into a slice of buffers.
Data is copied to fill each buffer in gild, with the final buffer written to possibly being only partially filled. This method must behave equivalently to a unmarried call to read with concatenated buffers.
The default implementation calls read with either the showtime nonempty buffer provided, or an empty i if none exists.
🔬 This is a nightly-merely experimental API. (can_vector #69941)
Determines if this Reader has an efficient read_vectored implementation.
If a Reader does not override the default read_vectored implementation, lawmaking using it may want to avert the method all together and coagulate writes into a single buffer for college performance.
The default implementation returns fake.
Read all bytes until EOF in this source, placing them into buf.
All bytes read from this source will be appended to the specified buffer buf. This function will continuously call read() to append more than data to buf until read() returns either Ok(0) or an error of non-ErrorKind::Interrupted kind.
If successful, this function volition return the full number of bytes read.
If this part encounters an error of the kind ErrorKind::Interrupted then the error is ignored and the operation will go along.
If any other read mistake is encountered and so this function immediately returns. Any bytes which have already been read will be appended to buf.
Files implement Read:
use std::io; use std::io::prelude::*; employ std::fs::File; fn main() -> io::Outcome <()> { let mut f = File::open("foo.txt")?; allow mut buffer = Vec::new(); // read the whole file f.read_to_end(&mut buffer)?; Ok(()) } Run
(See likewise the std::fs::read convenience function for reading from a file.)
Read all bytes until EOF in this source, appending them to buf.
If successful, this part returns the number of bytes which were read and appended to buf.
If the data in this stream is not valid UTF-8 and then an mistake is returned and buf is unchanged.
Meet read_to_end for other fault semantics.
Filesouthward implement Read:
use std::io; use std::io::prelude::*; use std::fs::File; fn main() -> io::Upshot <()> { let mut f = File::open up("foo.txt")?; let mut buffer = String::new(); f.read_to_string(&mut buffer)?; Ok(()) } Run
(See also the std::fs::read_to_string convenience function for reading from a file.)
Read the exact number of bytes required to fill up buf.
This function reads as many bytes as necessary to completely fill the specified buffer buf.
No guarantees are provided nigh the contents of buf when this function is called, implementations cannot rely on any property of the contents of buf being true. It is recommended that implementations only write data to buf instead of reading its contents. The documentation on read has a more detailed caption on this subject.
If this function encounters an error of the kind ErrorKind::Interrupted so the error is ignored and the operation will continue.
If this part encounters an "end of file" earlier completely filling the buffer, information technology returns an fault of the kind ErrorKind::UnexpectedEof. The contents of buf are unspecified in this case.
If any other read error is encountered then this function immediately returns. The contents of buf are unspecified in this case.
If this office returns an error, it is unspecified how many bytes it has read, merely it will never read more than would exist necessary to completely fill the buffer.
Files implement Read:
use std::io; use std::io::prelude::*; use std::fs::File; fn chief() -> io::Outcome <()> { let mut f = File::open("foo.txt")?; let mut buffer = [0; 10]; // read exactly 10 bytes f.read_exact(&mut buffer)?; Ok(()) } Run
🔬 This is a nightly-only experimental API. (read_buf #78485)
Pull some bytes from this source into the specified buffer.
This is equivalent to the read method, except that it is passed a ReadBuf rather than [u8] to permit use with uninitialized buffers. The new data will be appended to any existing contents of buf.
The default implementation delegates to read.
🔬 This is a nightly-only experimental API. (read_buf #78485)
Read the exact number of bytes required to fill buf.
This is equivalent to the read_exact method, except that it is passed a ReadBuf rather than [u8] to allow use with uninitialized buffers.
Creates a "by reference" adaptor for this instance of Read.
The returned adapter also implements Read and will simply infringe this electric current reader.
Files implement Read:
apply std::io; use std::io::Read; use std::fs::File; fn primary() -> io::Issue <()> { let mut f = File::open("foo.txt")?; allow mut buffer = Vec::new(); let mut other_buffer = Vec::new(); { allow reference = f.by_ref(); // read at most v bytes reference.have(v).read_to_end(&mut buffer)?; } // drop our &mut reference and so we can employ f again // original file nonetheless usable, read the balance f.read_to_end(&mut other_buffer)?; Ok(()) } Run
Transforms this Read instance to an Iterator over its bytes.
The returned blazon implements Iterator where the Particular is Issue<u8, io::Fault>. The yielded item is Ok if a byte was successfully read and Err otherwise. EOF is mapped to returning None from this iterator.
Filedue south implement Read:
use std::io; utilize std::io::prelude::*; use std::fs::File; fn principal() -> io::Result <()> { let mut f = File::open("foo.txt")?; for byte in f.bytes() { println!("{}", byte.unwrap()); } Ok(()) } Run
Creates an adapter which will concatenation this stream with another.
The returned Read instance will kickoff read all bytes from this object until EOF is encountered. Afterwards the output is equivalent to the output of next.
Files implement Read:
employ std::io; use std::io::prelude::*; use std::fs::File; fn main() -> io::Outcome <()> { let mut f1 = File::open up("foo.txt")?; allow mut f2 = File::open("bar.txt")?; let mut handle = f1.concatenation(f2); let mut buffer = String::new(); // read the value into a String. We could utilise any Read method here, // this is only one instance. handle.read_to_string(&mut buffer)?; Ok(()) } Run
Creates an adapter which will read at well-nigh limit bytes from information technology.
This function returns a new instance of Read which will read at most limit bytes, after which it will always return EOF (Ok(0)). Any read errors will not count towards the number of bytes read and future calls to read() may succeed.
Files implement Read:
use std::io; use std::io::prelude::*; employ std::fs::File; fn main() -> io::Result <()> { let mut f = File::open("foo.txt")?; permit mut buffer = [0; 5]; // read at most five bytes let mut handle = f.take(5); handle.read(&mut buffer)?; Ok(()) } Run
Read is implemented for &[u8] past copying from the slice.
Note that reading updates the piece to bespeak to the yet unread part. The slice volition exist empty when EOF is reached.
Source: https://doc.rust-lang.org/std/io/trait.Read.html
0 Response to "Io Stream Read and Read Again"
Post a Comment