Trait Write
trait Write
A trait for objects which are byte-oriented sinks.
Implementors of the Write trait are sometimes called 'writers'.
Writers are defined by two required methods, write and flush:
-
The
writemethod will attempt to write some data into the object, returning how many bytes were successfully written. -
The
flushmethod is useful for adapters and explicit buffers themselves for ensuring that all buffered data has been pushed out to the 'true sink'.
Writers are intended to be composable with one another. Many implementors
throughout std::io take and provide types which implement the Write
trait.
Examples
use std::io::prelude::*;
use std::fs::File;
fn main() -> std::io::Result<()> {
let data = b"some bytes";
let mut pos = 0;
let mut buffer = File::create("foo.txt")?;
while pos < data.len() {
let bytes_written = buffer.write(&data[pos..])?;
pos += bytes_written;
}
Ok(())
}
The trait also provides convenience methods like write_all, which calls
write in a loop until its entire input has been written.
Required Methods
fn write(self: &mut Self, buf: &[u8]) -> Result<usize>Writes a buffer into this writer, returning how many bytes were written.
This function will attempt to write the entire contents of
buf, but the entire write might not succeed, or the write may also generate an error. Typically, a call towriterepresents one attempt to write to any wrapped object.Calls to
writeare not guaranteed to block waiting for data to be written, and a write which would otherwise block can be indicated through anErrvariant.If this method consumed
n > 0bytes ofbufit must returnOk(n). If the return value isOk(n)thennmust satisfyn <= buf.len(). A return value ofOk(0)typically means that the underlying object is no longer able to accept bytes and will likely not be able to in the future as well, or that the buffer provided is empty.Errors
Each call to
writemay generate an I/O error indicating that the operation could not be completed. If an error is returned then no bytes in the buffer were written to this writer.It is not considered an error if the entire buffer could not be written to this writer.
An error of the
ErrorKind::Interruptedkind is non-fatal and the write operation should be retried if there is nothing else to do.Examples
use std::io::prelude::*; use std::fs::File; fn main() -> std::io::Result<()> { let mut buffer = File::create("foo.txt")?; // Writes some prefix of the byte string, not necessarily all of it. buffer.write(b"some bytes")?; Ok(()) }fn flush(self: &mut Self) -> Result<()>Flushes this output stream, ensuring that all intermediately buffered contents reach their destination.
Errors
It is considered an error if not all bytes could be written due to I/O errors or EOF being reached.
Examples
use std::io::prelude::*; use std::io::BufWriter; use std::fs::File; fn main() -> std::io::Result<()> { let mut buffer = BufWriter::new(File::create("foo.txt")?); buffer.write_all(b"some bytes")?; buffer.flush()?; Ok(()) }
Provided Methods
fn write_vectored(self: &mut Self, bufs: &[IoSlice<'_>]) -> Result<usize>Like
write, except that it writes from a slice of buffers.Data is copied from each buffer in order, with the final buffer read from possibly being only partially consumed. This method must behave as a call to
writewith the buffers concatenated would.The default implementation calls
writewith either the first nonempty buffer provided, or an empty one if none exists.Examples
use std::io::IoSlice; use std::io::prelude::*; use std::fs::File; fn main() -> std::io::Result<()> { let data1 = [1; 8]; let data2 = [15; 8]; let io_slice1 = IoSlice::new(&data1); let io_slice2 = IoSlice::new(&data2); let mut buffer = File::create("foo.txt")?; // Writes some prefix of the byte string, not necessarily all of it. buffer.write_vectored(&[io_slice1, io_slice2])?; Ok(()) }fn is_write_vectored(self: &Self) -> boolDetermines if this
Writer has an efficientwrite_vectoredimplementation.If a
Writer does not override the defaultwrite_vectoredimplementation, code using it may want to avoid the method all together and coalesce writes into a single buffer for higher performance.The default implementation returns
false.fn write_all(self: &mut Self, buf: &[u8]) -> Result<()>Attempts to write an entire buffer into this writer.
This method will continuously call
writeuntil there is no more data to be written or an error of non-ErrorKind::Interruptedkind is returned. This method will not return until the entire buffer has been successfully written or such an error occurs. The first error that is not ofErrorKind::Interruptedkind generated from this method will be returned.If the buffer contains no data, this will never call
write.Errors
This function will return the first error of non-
ErrorKind::Interruptedkind thatwritereturns.Examples
use std::io::prelude::*; use std::fs::File; fn main() -> std::io::Result<()> { let mut buffer = File::create("foo.txt")?; buffer.write_all(b"some bytes")?; Ok(()) }fn write_all_vectored(self: &mut Self, bufs: &mut [IoSlice<'_>]) -> Result<()>Attempts to write multiple buffers into this writer.
This method will continuously call
write_vectoreduntil there is no more data to be written or an error of non-ErrorKind::Interruptedkind is returned. This method will not return until all buffers have been successfully written or such an error occurs. The first error that is not ofErrorKind::Interruptedkind generated from this method will be returned.If the buffer contains no data, this will never call
write_vectored.Notes
Unlike
write_vectored, this takes a mutable reference to a slice ofIoSlices, not an immutable one. That's because we need to modify the slice to keep track of the bytes already written.Once this function returns, the contents of
bufsare unspecified, as this depends on how many calls towrite_vectoredwere necessary. It is best to understand this function as taking ownership ofbufsand to not usebufsafterwards. The underlying buffers, to which theIoSlices point (but not theIoSlices themselves), are unchanged and can be reused.Examples
#fn write_fmt(self: &mut Self, args: fmt::Arguments<'_>) -> Result<()>Writes a formatted string into this writer, returning any error encountered.
This method is primarily used to interface with the [
format_args!()] macro, and it is rare that this should explicitly be called. The [write!()] macro should be favored to invoke this method instead.This function internally uses the
write_allmethod on this trait and hence will continuously write data so long as no errors are received. This also means that partial writes are not indicated in this signature.Errors
This function will return any I/O error reported while formatting.
Examples
use std::io::prelude::*; use std::fs::File; fn main() -> std::io::Result<()> { let mut buffer = File::create("foo.txt")?; // this call write!(buffer, "{:.*}", 2, 1.234567)?; // turns into this: buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?; Ok(()) }fn by_ref(self: &mut Self) -> &mut Self where Self: SizedCreates a "by reference" adapter for this instance of
Write.The returned adapter also implements
Writeand will simply borrow this current writer.Examples
use std::io::Write; use std::fs::File; fn main() -> std::io::Result<()> { let mut buffer = File::create("foo.txt")?; let reference = buffer.by_ref(); // we can use reference just like our original buffer reference.write_all(b"some bytes")?; Ok(()) }
Implementors
impl Write for &Stdoutimpl Write for PipeWriterimpl Write for &Fileimpl Write for Cursor<&mut [u8]>impl<W: Write + ?Sized> Write for Box<W>impl Write for StdoutLock<'_>impl Write for &Stderrimpl<A> Write for Cursor<&mut Vec<u8, A>>impl Write for &mut [u8]impl Write for Emptyimpl Write for crate::sync::Arc<File>impl Write for &TcpStreamimpl<'a> Write for &'a UnixStreamimpl<A> Write for Cursor<Vec<u8, A>>impl<A: Allocator> Write for Vec<u8, A>impl Write for StderrLock<'_>impl<W: ?Sized + Write> Write for BufWriter<W>impl<A> Write for Cursor<Box<[u8], A>>impl<A: Allocator> Write for crate::collections::VecDeque<u8, A>impl Write for &PipeWriterimpl Write for Sinkimpl Write for Fileimpl<N: usize> Write for Cursor<[u8; N]>impl<'a> Write for core::io::BorrowedCursor<'a>impl Write for Stdoutimpl<W: ?Sized + Write> Write for LineWriter<W>impl Write for &ChildStdinimpl Write for &Emptyimpl<W: Write + ?Sized> Write for &mut Wimpl Write for Stderrimpl Write for TcpStreamimpl Write for UnixStreamimpl Write for ChildStdinimpl Write for &Sink