diff --git a/library/alloc/src/io/buf_read.rs b/library/alloc/src/io/buf_read.rs index bba1c2b8c8a45..0f763ae267bd0 100644 --- a/library/alloc/src/io/buf_read.rs +++ b/library/alloc/src/io/buf_read.rs @@ -16,14 +16,20 @@ use crate::vec::Vec; /// A locked standard input implements `BufRead`: /// /// ```no_run -/// use std::io; -/// use std::io::prelude::*; +/// # #![feature(alloc_io)] +/// # use alloc as std; +/// # use alloc::vec::Vec; +/// # use alloc::string::String; +/// use std::io::{self, BufRead}; /// -/// let stdin = io::stdin(); -/// for line in stdin.lock().lines() { -/// println!("{}", line?); -/// } -/// # std::io::Result::Ok(()) +/// let data = "Hello\nWorld!"; +/// let cursor = io::Cursor::new(data); +/// +/// let lines = cursor.lines().collect::>>()?; +/// +/// assert_eq!(&lines[0], "Hello"); +/// assert_eq!(&lines[1], "World!"); +/// # io::Result::Ok(()) /// ``` /// /// If you have something that implements [`Read`], you can use the `BufReader` @@ -36,21 +42,20 @@ use crate::vec::Vec; /// [`lines`]: BufRead::lines /// /// ```no_run -/// use std::io::{self, BufReader}; -/// use std::io::prelude::*; -/// use std::fs::File; +/// # #![feature(alloc_io)] +/// # use alloc as std; +/// # use alloc::vec::Vec; +/// # use alloc::string::String; +/// use std::io::{self, BufRead, BufReader}; /// -/// fn main() -> io::Result<()> { -/// let f = File::open("foo.txt")?; -/// let f = BufReader::new(f); +/// let mut data = b"Hello\nWorld!" as &[u8]; +/// let buffer = BufReader::new(&mut data); /// -/// for line in f.lines() { -/// let line = line?; -/// println!("{line}"); -/// } +/// let lines = buffer.lines().collect::>>()?; /// -/// Ok(()) -/// } +/// assert_eq!(&lines[0], "Hello"); +/// assert_eq!(&lines[1], "World!"); +/// # io::Result::Ok(()) /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "IoBufRead")] @@ -73,10 +78,15 @@ pub trait BufRead: Read { /// A locked standard input implements `BufRead`: /// /// ```no_run - /// use std::io; + /// # #![feature(alloc_io)] + /// # #![allow(unused_must_use)] + /// # use alloc as std; + /// # use alloc::format as println; /// use std::io::prelude::*; /// - /// let stdin = io::stdin(); + /// # struct StdinMock; + /// # impl StdinMock { fn lock(&self) -> impl BufRead { alloc::io::BufReader::new(&[0u8; 8][..]) } } + /// # let stdin = StdinMock; /// let mut stdin = stdin.lock(); /// /// let buffer = stdin.fill_buf()?; @@ -124,12 +134,17 @@ pub trait BufRead: Read { /// /// Examples /// - /// ``` + /// ```no_run + /// # #![feature(alloc_io)] + /// # #![allow(unused_must_use)] /// #![feature(buf_read_has_data_left)] - /// use std::io; + /// # use alloc as std; + /// # use alloc::format as println; /// use std::io::prelude::*; /// - /// let stdin = io::stdin(); + /// # struct StdinMock; + /// # impl StdinMock { fn lock(&self) -> impl BufRead { alloc::io::BufReader::new(&[0u8; 8][..]) } } + /// # let stdin = StdinMock; /// let mut stdin = stdin.lock(); /// /// while stdin.has_data_left()? { @@ -176,6 +191,8 @@ pub trait BufRead: Read { /// [`Cursor`]: crate::io::Cursor /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{self, BufRead}; /// /// let mut cursor = io::Cursor::new(b"lorem-ipsum"); @@ -240,6 +257,9 @@ pub trait BufRead: Read { /// [`Cursor`]: crate::io::Cursor /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::{self, BufRead}; /// /// let mut cursor = io::Cursor::new(b"Ferris\0Likes long walks on the beach\0Crustacean\0!"); @@ -313,6 +333,8 @@ pub trait BufRead: Read { /// [`Cursor`]: crate::io::Cursor /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{self, BufRead}; /// /// let mut cursor = io::Cursor::new(b"foo\nbar"); @@ -368,6 +390,8 @@ pub trait BufRead: Read { /// [`Cursor`]: crate::io::Cursor /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{self, BufRead}; /// /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor"); @@ -403,6 +427,8 @@ pub trait BufRead: Read { /// [`Cursor`]: crate::io::Cursor /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{self, BufRead}; /// /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor"); diff --git a/library/alloc/src/io/buffered/bufreader.rs b/library/alloc/src/io/buffered/bufreader.rs index e8b3302e29b98..67c05d32094a3 100644 --- a/library/alloc/src/io/buffered/bufreader.rs +++ b/library/alloc/src/io/buffered/bufreader.rs @@ -36,12 +36,16 @@ use crate::vec::Vec; /// # Examples /// /// ```no_run +/// # #![feature(alloc_io)] +/// # #![allow(unused_must_use)] +/// # use alloc as std; +/// # use alloc::format as println; +/// # use alloc::string::String; /// use std::io::prelude::*; /// use std::io::BufReader; -/// use std::fs::File; /// /// fn main() -> std::io::Result<()> { -/// let f = File::open("log.txt")?; +/// let f = b"Hello\nWorld!" as &[u8]; /// let mut reader = BufReader::new(f); /// /// let mut line = String::new(); @@ -64,11 +68,12 @@ impl BufReader { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f = File::open("log.txt")?; + /// let f = b"Hello\nWorld!" as &[u8]; /// let reader = BufReader::new(f); /// Ok(()) /// } @@ -97,11 +102,12 @@ impl BufReader { /// Creating a buffer with ten bytes of capacity: /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f = File::open("log.txt")?; + /// let f = b"Hello\nWorld!" as &[u8]; /// let reader = BufReader::with_capacity(10, f); /// Ok(()) /// } @@ -128,7 +134,9 @@ impl BufReader { /// ## Examples /// /// ```rust + /// # #![feature(alloc_io)] /// #![feature(bufreader_peek)] + /// # use alloc as std; /// use std::io::{Read, BufReader}; /// /// let mut bytes = &b"oh, hello there"[..]; @@ -169,11 +177,12 @@ impl BufReader { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f1 = File::open("log.txt")?; + /// let f1 = b"Hello\nWorld!" as &[u8]; /// let reader = BufReader::new(f1); /// /// let f2 = reader.get_ref(); @@ -192,11 +201,12 @@ impl BufReader { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f1 = File::open("log.txt")?; + /// let f1 = b"Hello\nWorld!" as &[u8]; /// let mut reader = BufReader::new(f1); /// /// let f2 = reader.get_mut(); @@ -217,11 +227,12 @@ impl BufReader { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{BufReader, BufRead}; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f = File::open("log.txt")?; + /// let f = b"Hello\nWorld!" as &[u8]; /// let mut reader = BufReader::new(f); /// assert!(reader.buffer().is_empty()); /// @@ -241,11 +252,12 @@ impl BufReader { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{BufReader, BufRead}; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f = File::open("log.txt")?; + /// let f = b"Hello\nWorld!" as &[u8]; /// let mut reader = BufReader::new(f); /// /// let capacity = reader.capacity(); @@ -267,11 +279,12 @@ impl BufReader { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let f1 = File::open("log.txt")?; + /// let f1 = b"Hello\nWorld!" as &[u8]; /// let reader = BufReader::new(f1); /// /// let f2 = reader.into_inner(); @@ -575,13 +588,17 @@ impl Seek for BufReader { /// # Example /// /// ```no_run - /// use std::{ - /// io::{self, BufRead, BufReader, Seek}, - /// fs::File, - /// }; + /// # #![feature(alloc_io)] + /// # #![allow(unused_must_use)] + /// # use alloc as std; + /// # use alloc::format as println; + /// # use alloc::string::String; + /// use std::io::{self, BufRead, BufReader, Seek}; /// /// fn main() -> io::Result<()> { - /// let mut f = BufReader::new(File::open("foo.txt")?); + /// let data = b"Hello\nWorld!" as &[u8]; + /// let cursor = io::Cursor::new(data); + /// let mut f = BufReader::new(cursor); /// /// let before = f.stream_position()?; /// f.read_line(&mut String::new())?; diff --git a/library/alloc/src/io/buffered/bufwriter.rs b/library/alloc/src/io/buffered/bufwriter.rs index 806e71c2772ae..42b472d5c8090 100644 --- a/library/alloc/src/io/buffered/bufwriter.rs +++ b/library/alloc/src/io/buffered/bufwriter.rs @@ -26,42 +26,6 @@ use crate::vec::Vec; /// ensures that the buffer is empty and thus dropping will not even attempt /// file operations. /// -/// # Examples -/// -/// Let's write the numbers one through ten to a [`TcpStream`]: -/// -/// ```no_run -/// use std::io::prelude::*; -/// use std::net::TcpStream; -/// -/// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap(); -/// -/// for i in 0..10 { -/// stream.write(&[i+1]).unwrap(); -/// } -/// ``` -/// -/// Because we're not buffering, we write each one in turn, incurring the -/// overhead of a system call per byte written. We can fix this with a -/// `BufWriter`: -/// -/// ```no_run -/// use std::io::prelude::*; -/// use std::io::BufWriter; -/// use std::net::TcpStream; -/// -/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); -/// -/// for i in 0..10 { -/// stream.write(&[i+1]).unwrap(); -/// } -/// stream.flush().unwrap(); -/// ``` -/// -/// By wrapping the stream with a `BufWriter`, these ten writes are all grouped -/// together by the buffer and will all be written out in one system call when -/// the `stream` is flushed. -/// // FIXME(#74481): Hard-links required to link from `alloc` to `std` /// [`TcpStream::write`]: ../../std/net/struct.TcpStream.html#method.write /// [`TcpStream`]: ../../std/net/struct.TcpStream.html @@ -87,11 +51,13 @@ impl BufWriter { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// /// # #[expect(unused_mut)] - /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let mut buffer = BufWriter::new(Vec::new()); /// ``` #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] @@ -119,12 +85,13 @@ impl BufWriter { /// Creating a buffer with a buffer of at least a hundred bytes. /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// - /// let stream = TcpStream::connect("127.0.0.1:34254").unwrap(); /// # #[expect(unused_mut)] - /// let mut buffer = BufWriter::with_capacity(100, stream); + /// let mut buffer = BufWriter::with_capacity(100, Vec::new()); /// ``` #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] @@ -143,14 +110,16 @@ impl BufWriter { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// /// # #[expect(unused_mut)] - /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let mut buffer = BufWriter::new(Vec::new()); /// - /// // unwrap the TcpStream and flush the buffer - /// let stream = buffer.into_inner().unwrap(); + /// // unwrap the Vec and flush the buffer + /// let vector = buffer.into_inner().unwrap(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(mut self) -> Result>> { @@ -172,6 +141,8 @@ impl BufWriter { /// # Examples /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{BufWriter, Write}; /// /// let mut buffer = [0u8; 10]; @@ -297,11 +268,13 @@ impl BufWriter { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// /// # #[expect(unused_mut)] - /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let mut buffer = BufWriter::new(Vec::new()); /// /// // we can use reference just like buffer /// let reference = buffer.get_ref(); @@ -318,10 +291,12 @@ impl BufWriter { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// - /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let mut buffer = BufWriter::new(Vec::new()); /// /// // we can use reference just like buffer /// let reference = buffer.get_mut(); @@ -336,10 +311,12 @@ impl BufWriter { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// - /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let buf_writer = BufWriter::new(Vec::new()); /// /// // See how many bytes are currently buffered /// let bytes_buffered = buf_writer.buffer().len(); @@ -368,10 +345,12 @@ impl BufWriter { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// - /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let buf_writer = BufWriter::new(Vec::new()); /// /// // Check the capacity of the inner buffer /// let capacity = buf_writer.capacity(); @@ -486,36 +465,6 @@ impl BufWriter { #[stable(feature = "bufwriter_into_parts", since = "1.56.0")] /// Error returned for the buffered data from `BufWriter::into_parts`, when the underlying /// writer has previously panicked. Contains the (possibly partly written) buffered data. -/// -/// # Example -/// -/// ``` -/// # // This test requires unwinding to work. -/// # // Disable it when unwinding isn't available. -/// # #[cfg(panic = "unwind")] -/// # fn main() { -/// use std::io::{self, BufWriter, Write}; -/// use std::panic::{catch_unwind, AssertUnwindSafe}; -/// -/// struct PanickingWriter; -/// impl Write for PanickingWriter { -/// fn write(&mut self, buf: &[u8]) -> io::Result { panic!() } -/// fn flush(&mut self) -> io::Result<()> { panic!() } -/// } -/// -/// let mut stream = BufWriter::new(PanickingWriter); -/// write!(stream, "some data").unwrap(); -/// let result = catch_unwind(AssertUnwindSafe(|| { -/// stream.flush().unwrap() -/// })); -/// assert!(result.is_err()); -/// let (recovered_writer, buffered_data) = stream.into_parts(); -/// assert!(matches!(recovered_writer, PanickingWriter)); -/// assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data"); -/// # } -/// # #[cfg(not(panic = "unwind"))] -/// # fn main() {} -/// ``` pub struct WriterPanicked { buf: Vec, } diff --git a/library/alloc/src/io/buffered/linewriter.rs b/library/alloc/src/io/buffered/linewriter.rs index bdb979e931f2e..fae0c6ee4a115 100644 --- a/library/alloc/src/io/buffered/linewriter.rs +++ b/library/alloc/src/io/buffered/linewriter.rs @@ -23,7 +23,9 @@ use crate::io::{self, BufWriter, IntoInnerError, IoSlice, Write}; /// reducing the number of actual writes to the file. /// /// ```no_run -/// use std::fs::{self, File}; +/// # #![feature(alloc_io)] +/// # use alloc as std; +/// # use alloc::vec::Vec; /// use std::io::prelude::*; /// use std::io::LineWriter; /// @@ -34,22 +36,22 @@ use crate::io::{self, BufWriter, IntoInnerError, IoSlice, Write}; /// I took the one less traveled by, /// And that has made all the difference."; /// -/// let file = File::create("poem.txt")?; -/// let mut file = LineWriter::new(file); +/// let buffer = Vec::new(); +/// let mut writer = LineWriter::new(buffer); /// -/// file.write_all(b"I shall be telling this with a sigh")?; +/// writer.write_all(b"I shall be telling this with a sigh")?; /// /// // No bytes are written until a newline is encountered (or /// // the internal buffer is filled). -/// assert_eq!(fs::read_to_string("poem.txt")?, ""); -/// file.write_all(b"\n")?; +/// assert_eq!(writer.get_ref().as_slice(), b"" as &[u8]); +/// writer.write_all(b"\n")?; /// assert_eq!( -/// fs::read_to_string("poem.txt")?, -/// "I shall be telling this with a sigh\n", +/// writer.get_ref().as_slice(), +/// b"I shall be telling this with a sigh\n" as &[u8], /// ); /// /// // Write the rest of the poem. -/// file.write_all(b"Somewhere ages and ages hence: +/// writer.write_all(b"Somewhere ages and ages hence: /// Two roads diverged in a wood, and I - /// I took the one less traveled by, /// And that has made all the difference.")?; @@ -57,10 +59,10 @@ use crate::io::{self, BufWriter, IntoInnerError, IoSlice, Write}; /// // The last line of the poem doesn't end in a newline, so /// // we have to flush or drop the `LineWriter` to finish /// // writing. -/// file.flush()?; +/// writer.flush()?; /// /// // Confirm the whole poem was written. -/// assert_eq!(fs::read("poem.txt")?, &road_not_taken[..]); +/// assert_eq!(writer.get_ref().as_slice(), &road_not_taken[..]); /// Ok(()) /// } /// ``` @@ -75,11 +77,13 @@ impl LineWriter { /// # Examples /// /// ```no_run - /// use std::fs::File; + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::LineWriter; /// /// fn main() -> std::io::Result<()> { - /// let file = File::create("poem.txt")?; + /// let file = Vec::new(); /// let file = LineWriter::new(file); /// Ok(()) /// } @@ -97,11 +101,13 @@ impl LineWriter { /// # Examples /// /// ```no_run - /// use std::fs::File; + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::LineWriter; /// /// fn main() -> std::io::Result<()> { - /// let file = File::create("poem.txt")?; + /// let file = Vec::new(); /// let file = LineWriter::with_capacity(100, file); /// Ok(()) /// } @@ -120,11 +126,13 @@ impl LineWriter { /// # Examples /// /// ```no_run - /// use std::fs::File; + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::LineWriter; /// /// fn main() -> std::io::Result<()> { - /// let file = File::create("poem.txt")?; + /// let file = Vec::new(); /// let mut file = LineWriter::new(file); /// /// // we can use reference just like file @@ -148,15 +156,17 @@ impl LineWriter { /// # Examples /// /// ```no_run - /// use std::fs::File; + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::LineWriter; /// /// fn main() -> std::io::Result<()> { - /// let file = File::create("poem.txt")?; + /// let buffer = Vec::new(); /// - /// let writer: LineWriter = LineWriter::new(file); + /// let writer: LineWriter> = LineWriter::new(buffer); /// - /// let file: File = writer.into_inner()?; + /// let buffer: Vec = writer.into_inner()?; /// Ok(()) /// } /// ``` @@ -172,11 +182,13 @@ impl LineWriter { /// # Examples /// /// ```no_run - /// use std::fs::File; + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::LineWriter; /// /// fn main() -> std::io::Result<()> { - /// let file = File::create("poem.txt")?; + /// let file = Vec::new(); /// let file = LineWriter::new(file); /// /// let reference = file.get_ref(); diff --git a/library/alloc/src/io/buffered/mod.rs b/library/alloc/src/io/buffered/mod.rs index 1bddcfb801932..1cf9b0450905b 100644 --- a/library/alloc/src/io/buffered/mod.rs +++ b/library/alloc/src/io/buffered/mod.rs @@ -21,15 +21,17 @@ use crate::io::Error; /// # Examples /// /// ```no_run +/// # #![feature(alloc_io)] +/// # use alloc as std; +/// # use alloc::vec::Vec; /// use std::io::BufWriter; -/// use std::net::TcpStream; /// /// # #[expect(unused_mut)] -/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); +/// let mut stream = BufWriter::new(Vec::new()); /// /// // do stuff with the stream /// -/// // we want to get our `TcpStream` back, so let's try: +/// // we want to get our `Vec` back, so let's try: /// /// let stream = match stream.into_inner() { /// Ok(s) => s, @@ -64,25 +66,23 @@ impl IntoInnerError { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// /// # #[expect(unused_mut)] - /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let mut stream = BufWriter::new(Vec::new()); /// /// // do stuff with the stream /// - /// // we want to get our `TcpStream` back, so let's try: + /// // we want to get our `Vec` back, so let's try: /// /// let stream = match stream.into_inner() { /// Ok(s) => s, /// Err(e) => { - /// // Here, e is an IntoInnerError, let's log the inner error. - /// // - /// // We'll just 'log' to stdout for this example. - /// println!("{}", e.error()); - /// - /// panic!("An unexpected error occurred."); + /// // Here, e is an IntoInnerError + /// panic!("An error occurred: {}", e.error()); /// } /// }; /// ``` @@ -99,15 +99,17 @@ impl IntoInnerError { /// # Examples /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io::BufWriter; - /// use std::net::TcpStream; /// /// # #[expect(unused_mut)] - /// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); + /// let mut stream = BufWriter::new(Vec::new()); /// /// // do stuff with the stream /// - /// // we want to get our `TcpStream` back, so let's try: + /// // we want to get our `Vec` back, so let's try: /// /// let stream = match stream.into_inner() { /// Ok(s) => s, @@ -132,7 +134,10 @@ impl IntoInnerError { /// obtain ownership of the underlying error. /// /// # Example + /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{BufWriter, ErrorKind, Write}; /// /// let mut not_enough_space = [0u8; 10]; @@ -154,7 +159,10 @@ impl IntoInnerError { /// advanced error recovery. /// /// # Example + /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{BufWriter, ErrorKind, Write}; /// /// let mut not_enough_space = [0u8; 10]; diff --git a/library/alloc/src/io/copy.rs b/library/alloc/src/io/copy.rs index 798bd2c1ec0a0..49d0e7f50b106 100644 --- a/library/alloc/src/io/copy.rs +++ b/library/alloc/src/io/copy.rs @@ -55,6 +55,8 @@ pub enum CopyState { /// # Examples /// /// ``` +/// # #![feature(alloc_io)] +/// # use alloc as std; /// use std::io; /// /// fn main() -> io::Result<()> { diff --git a/library/alloc/src/io/error.rs b/library/alloc/src/io/error.rs index 055d743dee6a1..d66ba8954fc11 100644 --- a/library/alloc/src/io/error.rs +++ b/library/alloc/src/io/error.rs @@ -23,6 +23,8 @@ impl Error { /// # Examples /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{Error, ErrorKind}; /// /// // errors can be created from strings @@ -61,6 +63,8 @@ impl Error { /// # Examples /// /// ``` + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::Error; /// /// // errors can be created from strings @@ -91,9 +95,12 @@ impl Error { /// /// # Examples /// - /// ``` + /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io::{Error, ErrorKind}; /// + /// # #[allow(unused_must_use)] /// fn print_error(err: Error) { /// if let Some(inner_err) = err.into_inner() { /// println!("Inner error: {inner_err}"); @@ -102,9 +109,10 @@ impl Error { /// } /// } /// + /// # #[allow(dead_code)] /// fn main() { /// // Will print "No inner error". - /// print_error(Error::last_os_error()); + /// print_error(Error::from(ErrorKind::Other)); /// // Will print "Inner error: ...". /// print_error(Error::new(ErrorKind::Other, "oh no!")); /// } @@ -149,6 +157,12 @@ impl Error { /// # Examples /// /// ``` + /// # #![feature(alloc_io)] + /// # mod std { + /// # pub use alloc::fmt; + /// # pub use alloc::io; + /// # pub use core::error; + /// # } /// use std::fmt; /// use std::io; /// use std::error::Error; diff --git a/library/alloc/src/io/mod.rs b/library/alloc/src/io/mod.rs index 44d780292317f..0767177d3e795 100644 --- a/library/alloc/src/io/mod.rs +++ b/library/alloc/src/io/mod.rs @@ -10,23 +10,24 @@ //! Because they are traits, [`Read`] and [`Write`] are implemented by a number //! of other types, and you can implement them for your types too. As such, //! you'll see a few different types of I/O throughout the documentation in -//! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec`]s. For -//! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on -//! [`File`]s: +//! this module. For example, [`Read`] adds a [`read`][`Read::read`] method +//! which we can use on byte slices: //! //! ```no_run -//! use std::io; -//! use std::io::prelude::*; -//! use std::fs::File; +//! # #![feature(alloc_io)] +//! use alloc::io; +//! use alloc::io::prelude::*; +//! use alloc::vec::Vec; //! //! fn main() -> io::Result<()> { -//! let mut f = File::open("foo.txt")?; +//! let data = (0..).into_iter().take(32).collect::>(); //! let mut buffer = [0; 10]; //! //! // read up to 10 bytes -//! let n = f.read(&mut buffer)?; +//! let n = data.as_slice().read(&mut buffer)?; +//! +//! assert_eq!(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][..n], &buffer[..n]); //! -//! println!("The bytes: {:?}", &buffer[..n]); //! Ok(()) //! } //! ``` @@ -43,23 +44,23 @@ //! coming from: //! //! ```no_run -//! use std::io; -//! use std::io::prelude::*; -//! use std::io::SeekFrom; -//! use std::fs::File; +//! # #![feature(alloc_io)] +//! use alloc::io; +//! use alloc::io::prelude::*; +//! use alloc::io::SeekFrom; +//! use alloc::vec::Vec; //! -//! fn main() -> io::Result<()> { -//! let mut f = File::open("foo.txt")?; -//! let mut buffer = [0; 10]; +//! # #[allow(dead_code)] +//! fn read_from_end(reader: &mut T) -> io::Result> { +//! let mut buffer = Vec::new(); //! //! // skip to the last 10 bytes of the file -//! f.seek(SeekFrom::End(-10))?; +//! reader.seek(SeekFrom::End(-10))?; //! //! // read up to 10 bytes -//! let n = f.read(&mut buffer)?; +//! let _n = reader.read(&mut buffer)?; //! -//! println!("The bytes: {:?}", &buffer[..n]); -//! Ok(()) +//! Ok(buffer) //! } //! ``` //! @@ -70,7 +71,7 @@ //! //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be //! making near-constant calls to the operating system. To help with this, -//! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap +//! `alloc::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap //! readers and writers. The wrapper uses a buffer, reducing the number of //! calls and providing nicer methods for accessing exactly what you want. //! @@ -78,21 +79,23 @@ //! methods to any reader: //! //! ```no_run -//! use std::io; -//! use std::io::prelude::*; -//! use std::io::BufReader; -//! use std::fs::File; +//! # #![feature(alloc_io)] +//! use alloc::io; +//! use alloc::io::BufReader; +//! use alloc::io::prelude::*; +//! use alloc::string::String; +//! +//! # #[allow(dead_code)] +//! fn read_one_line(reader: &mut T) -> io::Result { +//! // reader now implements BufRead +//! let mut reader = BufReader::new(reader); //! -//! fn main() -> io::Result<()> { -//! let f = File::open("foo.txt")?; -//! let mut reader = BufReader::new(f); //! let mut buffer = String::new(); //! //! // read a line into buffer //! reader.read_line(&mut buffer)?; //! -//! println!("{buffer}"); -//! Ok(()) +//! Ok(buffer) //! } //! ``` //! @@ -100,15 +103,15 @@ //! to [`write`][`Write::write`]: //! //! ```no_run -//! use std::io; -//! use std::io::prelude::*; -//! use std::io::BufWriter; -//! use std::fs::File; +//! # #![feature(alloc_io)] +//! use alloc::io; +//! use alloc::io::BufWriter; +//! use alloc::io::prelude::*; //! -//! fn main() -> io::Result<()> { -//! let f = File::create("foo.txt")?; +//! # #[allow(dead_code)] +//! fn write_the_answer(writer: &mut T) -> io::Result<()> { //! { -//! let mut writer = BufWriter::new(f); +//! let mut writer = BufWriter::new(writer); //! //! // write a byte to the buffer //! writer.write(&[42])?; @@ -121,23 +124,24 @@ //! //! ## Iterator types //! -//! A large number of the structures provided by `std::io` are for various +//! A large number of the structures provided by `alloc::io` are for various //! ways of iterating over I/O. For example, [`Lines`] is used to split over //! lines: //! //! ```no_run -//! use std::io; -//! use std::io::prelude::*; -//! use std::io::BufReader; -//! use std::fs::File; +//! # #![feature(alloc_io)] +//! use alloc::io; +//! use alloc::io::BufReader; +//! use alloc::io::prelude::*; //! -//! fn main() -> io::Result<()> { -//! let f = File::open("foo.txt")?; -//! let reader = BufReader::new(f); +//! # #[allow(dead_code)] +//! fn read_one_line(reader: &mut T) -> io::Result<()> { +//! let reader = BufReader::new(reader); //! //! for line in reader.lines() { -//! println!("{}", line?); +//! assert!(!line?.ends_with('\n')); //! } +//! //! Ok(()) //! } //! ``` @@ -150,27 +154,28 @@ //! module use the [`?` operator]: //! //! ```no_run -//! use std::io; +//! # #![feature(alloc_io)] +//! use alloc::io; +//! use alloc::io::prelude::*; //! //! # #[allow(dead_code)] -//! fn read_input() -> io::Result<()> { -//! let mut input = String::new(); -//! -//! io::stdin().read_line(&mut input)?; +//! fn read_one_line(reader: &mut T) -> io::Result<()> { +//! for line in reader.lines() { +//! // Reading a line could fail! We use ? to propagate the error +//! let line = line?; //! -//! println!("You typed: {}", input.trim()); +//! assert!(!line.ends_with('\n')); +//! } //! //! Ok(()) //! } //! ``` //! -//! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very +//! The return type of `read_one_line()`, [`io::Result<()>`][`io::Result`], is a very //! common type for functions which don't have a 'real' return value, but do want to //! return errors if they happen. In this case, the only purpose of this function is -//! to read the line and print it, so we use `()`. +//! to read the lines, so we use `()`. //! -//! [`File`]: ../../std/fs/struct.File.html -//! [`TcpStream`]: ../../std/net/struct.TcpStream.html //! [`Vec`]: crate::vec::Vec //! [`io::Result`]: self::Result //! [`?` operator]: ../../book/appendix-02-operators.html diff --git a/library/alloc/src/io/prelude.rs b/library/alloc/src/io/prelude.rs index 86ae040d1d6f6..d3ebc373e6284 100644 --- a/library/alloc/src/io/prelude.rs +++ b/library/alloc/src/io/prelude.rs @@ -4,8 +4,9 @@ //! by adding a glob import to the top of I/O heavy modules: //! //! ``` +//! # #![feature(alloc_io)] //! # #![allow(unused_imports)] -//! use std::io::prelude::*; +//! use alloc::io::prelude::*; //! ``` #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/alloc/src/io/read.rs b/library/alloc/src/io/read.rs index fe1a8d11ccefe..b22a226b16600 100644 --- a/library/alloc/src/io/read.rs +++ b/library/alloc/src/io/read.rs @@ -33,15 +33,16 @@ use crate::vec::Vec; /// /// # Examples /// -/// `File`s implement `Read`: -/// /// ```no_run +/// # #![feature(alloc_io)] +/// # use alloc as std; +/// # use alloc::string::String; /// use std::io; /// use std::io::prelude::*; -/// use std::fs::File; /// /// fn main() -> io::Result<()> { -/// let mut f = File::open("foo.txt")?; +/// let mut data = b"Hello World! This is a short byte-string." as &[u8]; +/// let f = &mut data; /// let mut buffer = [0; 10]; /// /// // read up to 10 bytes @@ -63,6 +64,8 @@ use crate::vec::Vec; /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`: /// /// ```no_run +/// # #![feature(alloc_io)] +/// # use alloc as std; /// # use std::io; /// use std::io::prelude::*; /// @@ -143,18 +146,20 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// [`Ok(n)`]: Ok /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted /// /// ```no_run + /// # #![feature(alloc_io)] + /// # #![allow(unused_must_use)] + /// # use alloc as std; + /// # use alloc::format as println; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; /// let mut buffer = [0; 10]; /// /// // read up to 10 bytes @@ -218,19 +223,19 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// [`Ok(0)`]: Ok /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted /// [`read()`]: Read::read /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; /// let mut buffer = Vec::new(); /// /// // read the whole file @@ -250,8 +255,9 @@ pub trait Read { /// situations gracefully. /// /// ```no_run + /// # #![feature(alloc_io)] /// # #![expect(dead_code)] - /// # use std::io::{self, BufRead}; + /// # use alloc::io::{self, BufRead}; /// # struct Example { example_datasource: io::Empty } impl Example { /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] } /// fn read_to_end(&mut self, dest_vec: &mut Vec) -> io::Result { @@ -308,15 +314,16 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::string::String; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; /// let mut buffer = String::new(); /// /// f.read_to_string(&mut buffer)?; @@ -373,19 +380,19 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof /// [`read`]: Read::read /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; /// let mut buffer = [0; 10]; /// /// // read exactly 10 bytes @@ -444,15 +451,16 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::vec::Vec; /// use std::io; - /// use std::io::Read; - /// use std::fs::File; + /// use std::io::prelude::*; /// /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; /// let mut buffer = Vec::new(); /// let mut other_buffer = Vec::new(); /// @@ -490,20 +498,20 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// [`Item`]: Iterator::Item /// [Result]: core::result::Result "Result" /// [io::Error]: crate::io::Error "io::Error" /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io; /// use std::io::prelude::*; - /// use std::io::BufReader; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let f = BufReader::new(File::open("foo.txt")?); + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; + /// let f = io::BufReader::new(f); /// /// for byte in f.bytes() { /// println!("{}", byte?); @@ -527,16 +535,18 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; + /// # use alloc::string::String; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let f1 = File::open("foo.txt")?; - /// let f2 = File::open("bar.txt")?; + /// let mut foo = b"My Foo Data" as &[u8]; + /// let mut bar = b"My Bar Data" as &[u8]; + /// let f1 = &mut foo; + /// let f2 = &mut bar; /// /// let mut handle = f1.chain(f2); /// let mut buffer = String::new(); @@ -564,18 +574,18 @@ pub trait Read { /// /// # Examples /// - /// `File`s implement `Read`: - /// /// [`Ok(0)`]: Ok /// [`read()`]: Read::read /// /// ```no_run + /// # #![feature(alloc_io)] + /// # use alloc as std; /// use std::io; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> io::Result<()> { - /// let f = File::open("foo.txt")?; + /// let mut data = b"Hello World! This is a short byte-string." as &[u8]; + /// let f = &mut data; /// let mut buffer = [0; 5]; /// /// // read at most five bytes @@ -607,7 +617,9 @@ pub trait Read { /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof /// /// ``` + /// # #![feature(alloc_io)] /// #![feature(read_array)] + /// # use alloc as std; /// use std::io::Cursor; /// use std::io::prelude::*; /// @@ -646,7 +658,9 @@ pub trait Read { /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof /// /// ``` + /// # #![feature(alloc_io)] /// #![feature(read_le)] + /// # use alloc as std; /// use std::io::Cursor; /// use std::io::prelude::*; /// @@ -681,7 +695,9 @@ pub trait Read { /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof /// /// ``` + /// # #![feature(alloc_io)] /// #![feature(read_le)] + /// # use alloc as std; /// use std::io::Cursor; /// use std::io::prelude::*; /// @@ -739,18 +755,6 @@ pub trait Read { /// that can occur. If any error occurs, you will get an [`Err`], so you /// don't have to worry about your buffer being empty or partially full. /// -/// # Examples -/// -/// ```no_run -/// # use std::io; -/// fn main() -> io::Result<()> { -/// let stdin = io::read_to_string(io::stdin())?; -/// println!("Stdin was:"); -/// println!("{stdin}"); -/// Ok(()) -/// } -/// ``` -/// /// # Usage Notes /// /// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams diff --git a/library/core/src/io/cursor.rs b/library/core/src/io/cursor.rs index fe4def531a84a..9dfb7cbef118c 100644 --- a/library/core/src/io/cursor.rs +++ b/library/core/src/io/cursor.rs @@ -22,15 +22,16 @@ use crate::io::{self, ErrorKind, IoSlice, SeekFrom, Write}; // FIXME(#74481): Hard-links required to link from `core` to `std` /// [bytes]: crate::slice "slice" /// [`File`]: ../../std/fs/struct.File.html -/// [`Read`]: ../../std/io/trait.Read.html +/// [`Read`]: ../../alloc/io/trait.Read.html /// [`Write`]: crate::io::Write /// [`Seek`]: crate::io::Seek /// [Vec]: ../../alloc/vec/struct.Vec.html /// /// ```no_run +/// # #![feature(core_io)] +/// # use core as std; /// use std::io::prelude::*; /// use std::io::{self, SeekFrom}; -/// use std::fs::File; /// /// // a library function we've written /// fn write_ten_bytes_at_end(mut writer: W) -> io::Result<()> { @@ -44,26 +45,13 @@ use crate::io::{self, ErrorKind, IoSlice, SeekFrom, Write}; /// Ok(()) /// } /// -/// # fn foo() -> io::Result<()> { -/// // Here's some code that uses this library function. -/// // -/// // We might want to use a BufReader here for efficiency, but let's -/// // keep this example focused. -/// let mut file = File::create("foo.txt")?; -/// // First, we need to allocate 10 bytes to be able to write into. -/// file.set_len(10)?; -/// -/// write_ten_bytes_at_end(&mut file)?; -/// # Ok(()) -/// # } -/// /// // now let's write a test -/// #[test] +/// # #[allow(dead_code)] /// fn test_writes_bytes() { /// // setting up a real File is much slower than an in-memory buffer, /// // let's use a cursor instead /// use std::io::Cursor; -/// let mut buff = Cursor::new(vec![0; 15]); +/// let mut buff = Cursor::new([0; 15]); /// /// write_ten_bytes_at_end(&mut buff).unwrap(); /// @@ -90,10 +78,12 @@ impl Cursor { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::Cursor; /// - /// let buff = Cursor::new(Vec::new()); - /// # fn force_inference(_: &Cursor>) {} + /// let buff = Cursor::new(&[1u8, 2u8, 3u8] as &[u8]); + /// # fn force_inference(_: &Cursor<&[u8]>) {} /// # force_inference(&buff); /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -107,13 +97,15 @@ impl Cursor { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::Cursor; /// - /// let buff = Cursor::new(Vec::new()); - /// # fn force_inference(_: &Cursor>) {} + /// let buff = Cursor::new(&[1u8, 2u8, 3u8] as &[u8]); + /// # fn force_inference(_: &Cursor<&[u8]>) {} /// # force_inference(&buff); /// - /// let vec = buff.into_inner(); + /// let slice = buff.into_inner(); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_inner(self) -> T { @@ -125,10 +117,12 @@ impl Cursor { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::Cursor; /// - /// let buff = Cursor::new(Vec::new()); - /// # fn force_inference(_: &Cursor>) {} + /// let buff = Cursor::new(&[1u8, 2u8, 3u8] as &[u8]); + /// # fn force_inference(_: &Cursor<&[u8]>) {} /// # force_inference(&buff); /// /// let reference = buff.get_ref(); @@ -147,10 +141,12 @@ impl Cursor { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::Cursor; /// - /// let mut buff = Cursor::new(Vec::new()); - /// # fn force_inference(_: &Cursor>) {} + /// let mut buff = Cursor::new(&[1u8, 2u8, 3u8] as &[u8]); + /// # fn force_inference(_: &Cursor<&[u8]>) {} /// # force_inference(&buff); /// /// let reference = buff.get_mut(); @@ -166,11 +162,13 @@ impl Cursor { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::Cursor; /// use std::io::prelude::*; /// use std::io::SeekFrom; /// - /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// let mut buff = Cursor::new([1, 2, 3, 4, 5]); /// /// assert_eq!(buff.position(), 0); /// @@ -191,9 +189,11 @@ impl Cursor { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::Cursor; /// - /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// let mut buff = Cursor::new([1, 2, 3, 4, 5]); /// /// assert_eq!(buff.position(), 0); /// @@ -226,10 +226,12 @@ where /// # Examples /// /// ``` + /// # #![feature(core_io)] /// #![feature(cursor_split)] + /// # use core as std; /// use std::io::Cursor; /// - /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// let mut buff = Cursor::new([1, 2, 3, 4, 5]); /// /// assert_eq!(buff.split(), ([].as_slice(), [1, 2, 3, 4, 5].as_slice())); /// @@ -257,10 +259,12 @@ where /// # Examples /// /// ``` + /// # #![feature(core_io)] /// #![feature(cursor_split)] + /// # use core as std; /// use std::io::Cursor; /// - /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// let mut buff = Cursor::new([1, 2, 3, 4, 5]); /// /// assert_eq!(buff.split_mut(), ([].as_mut_slice(), [1, 2, 3, 4, 5].as_mut_slice())); /// diff --git a/library/core/src/io/error.rs b/library/core/src/io/error.rs index 61abdb16d07da..df31a9eb5e149 100644 --- a/library/core/src/io/error.rs +++ b/library/core/src/io/error.rs @@ -55,15 +55,21 @@ use crate::{error, fmt, result}; /// /// A convenience function that bubbles an `io::Result` to its caller: /// -/// ``` +/// ```no_run +/// # #![feature(core_io)] +/// # use core as std; /// use std::io; /// -/// fn get_string() -> io::Result { -/// let mut buffer = String::new(); +/// # fn read_number_from_stdin() -> io::Result { Ok(42) } /// -/// io::stdin().read_line(&mut buffer)?; +/// # #[allow(dead_code)] +/// fn check_answer() -> io::Result { +/// let answer = read_number_from_stdin()?; /// -/// Ok(buffer) +/// match answer { +/// 42 => Ok(true), +/// _ => Err(io::Error::from(io::ErrorKind::InvalidInput)), +/// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -78,7 +84,7 @@ pub type Result = result::Result; /// [`ErrorKind`]. /// // FIXME(#74481): Hard-links required to link from `core` to `std` -/// [Read]: ../../std/io/trait.Read.html +/// [Read]: ../../alloc/io/trait.Read.html /// [Write]: crate::io::Write /// [Seek]: crate::io::Seek #[stable(feature = "rust1", since = "1.0.0")] @@ -178,7 +184,9 @@ pub struct SimpleMessage { /// /// # Example /// ``` +/// # #![feature(core_io)] /// #![feature(io_const_error)] +/// # use core as std; /// use std::io::{const_error, Error, ErrorKind}; /// /// const FAIL: Error = const_error!(ErrorKind::Unsupported, "tried something that never works"); @@ -207,11 +215,12 @@ impl From for Error { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::{Error, ErrorKind}; /// /// let not_found = ErrorKind::NotFound; /// let error = Error::from(not_found); - /// assert_eq!("entity not found", format!("{error}")); /// ``` #[inline] fn from(kind: ErrorKind) -> Error { @@ -295,23 +304,19 @@ impl Error { /// /// # Examples /// - /// ``` - /// use std::io::{Error, ErrorKind}; + /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Error; /// + /// # #[allow(dead_code)] /// fn print_os_error(err: &Error) { /// if let Some(raw_os_err) = err.raw_os_error() { - /// println!("raw OS error: {raw_os_err:?}"); + /// // ... /// } else { - /// println!("Not an OS error"); + /// // ... /// } /// } - /// - /// fn main() { - /// // Will print "raw OS error: ...". - /// print_os_error(&Error::last_os_error()); - /// // Will print "Not an OS error". - /// print_os_error(&Error::new(ErrorKind::Other, "oh no!")); - /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] @@ -334,23 +339,19 @@ impl Error { /// /// # Examples /// - /// ``` - /// use std::io::{Error, ErrorKind}; + /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Error; /// - /// fn print_error(err: &Error) { - /// if let Some(inner_err) = err.get_ref() { - /// println!("Inner error: {inner_err:?}"); + /// # #[allow(dead_code)] + /// fn print_os_error(err: &Error) { + /// if let Some(inner_ref) = err.get_ref() { + /// // ... /// } else { - /// println!("No inner error"); + /// // ... /// } /// } - /// - /// fn main() { - /// // Will print "No inner error". - /// print_error(&Error::last_os_error()); - /// // Will print "Inner error: ...". - /// print_error(&Error::new(ErrorKind::Other, "oh no!")); - /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] #[must_use] @@ -375,57 +376,19 @@ impl Error { /// /// # Examples /// - /// ``` - /// use std::io::{Error, ErrorKind}; - /// use std::{error, fmt}; - /// use std::fmt::Display; - /// - /// #[derive(Debug)] - /// struct MyError { - /// v: String, - /// } - /// - /// impl MyError { - /// fn new() -> MyError { - /// MyError { - /// v: "oh no!".to_string() - /// } - /// } - /// - /// fn change_message(&mut self, new_message: &str) { - /// self.v = new_message.to_string(); - /// } - /// } - /// - /// impl error::Error for MyError {} - /// - /// impl Display for MyError { - /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - /// write!(f, "MyError: {}", self.v) - /// } - /// } - /// - /// fn change_error(mut err: Error) -> Error { - /// if let Some(inner_err) = err.get_mut() { - /// inner_err.downcast_mut::().unwrap().change_message("I've been changed!"); - /// } - /// err - /// } + /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Error; /// - /// fn print_error(err: &Error) { - /// if let Some(inner_err) = err.get_ref() { - /// println!("Inner error: {inner_err}"); + /// # #[allow(dead_code)] + /// fn print_os_error(err: &mut Error) { + /// if let Some(inner_mut) = err.get_mut() { + /// // ... /// } else { - /// println!("No inner error"); + /// // ... /// } /// } - /// - /// fn main() { - /// // Will print "No inner error". - /// print_error(&change_error(Error::last_os_error())); - /// // Will print "Inner error: ...". - /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new()))); - /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] #[must_use] @@ -451,20 +414,14 @@ impl Error { /// /// # Examples /// - /// ``` + /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::{Error, ErrorKind}; /// - /// fn print_error(err: Error) { - /// println!("{:?}", err.kind()); - /// } + /// let error = Error::from(ErrorKind::AddrInUse); /// - /// fn main() { - /// // As no error has (visibly) occurred, this may print anything! - /// // It likely prints a placeholder for unidentified (non-)errors. - /// print_error(Error::last_os_error()); - /// // Will print "AddrInUse". - /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!")); - /// } + /// assert_eq!(ErrorKind::AddrInUse, error.kind()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] @@ -1115,7 +1072,9 @@ impl fmt::Display for ErrorKind { /// This is similar to `impl Display for Error`, but doesn't require first converting to Error. /// /// # Examples + /// /// ``` + /// # #![feature(core_io)] /// use core::io::ErrorKind; /// assert_eq!("entity not found", ErrorKind::NotFound.to_string()); /// ``` diff --git a/library/core/src/io/io_slice.rs b/library/core/src/io/io_slice.rs index 0bdd410d3e964..014854bb97aa2 100644 --- a/library/core/src/io/io_slice.rs +++ b/library/core/src/io/io_slice.rs @@ -67,6 +67,8 @@ impl<'a> IoSliceMut<'a> { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::IoSliceMut; /// use std::ops::Deref; /// @@ -99,6 +101,8 @@ impl<'a> IoSliceMut<'a> { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::IoSliceMut; /// use std::ops::Deref; /// @@ -145,7 +149,9 @@ impl<'a> IoSliceMut<'a> { /// # Examples /// /// ``` + /// # #![feature(core_io)] /// #![feature(io_slice_as_bytes)] + /// # use core as std; /// use std::io::IoSliceMut; /// /// let mut data = *b"abcdef"; @@ -226,6 +232,8 @@ impl<'a> IoSlice<'a> { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::IoSlice; /// use std::ops::Deref; /// @@ -258,6 +266,8 @@ impl<'a> IoSlice<'a> { /// # Examples /// /// ``` + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::IoSlice; /// use std::ops::Deref; /// @@ -309,7 +319,9 @@ impl<'a> IoSlice<'a> { /// # Examples /// /// ``` + /// # #![feature(core_io)] /// #![feature(io_slice_as_bytes)] + /// # use core as std; /// use std::io::IoSlice; /// /// let data = b"abcdef"; diff --git a/library/core/src/io/prelude.rs b/library/core/src/io/prelude.rs index 15dacaa3a4fa0..3ff5833fb6331 100644 --- a/library/core/src/io/prelude.rs +++ b/library/core/src/io/prelude.rs @@ -4,8 +4,9 @@ //! by adding a glob import to the top of I/O heavy modules: //! //! ``` +//! # #![feature(core_io)] //! # #![allow(unused_imports)] -//! use std::io::prelude::*; +//! use core::io::prelude::*; //! ``` #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/io/seek.rs b/library/core/src/io/seek.rs index 4c242c761dfe6..f5a315c9bec0b 100644 --- a/library/core/src/io/seek.rs +++ b/library/core/src/io/seek.rs @@ -8,19 +8,25 @@ use crate::io::Result; /// /// # Examples /// -/// `File`s implement `Seek`: -/// /// ```no_run -/// use std::io; +/// # #![feature(core_io)] +/// # use core as std; +/// use std::io::{self, Cursor, SeekFrom}; /// use std::io::prelude::*; -/// use std::fs::File; -/// use std::io::SeekFrom; /// /// fn main() -> io::Result<()> { -/// let mut f = File::open("foo.txt")?; +/// let mut buff = Cursor::new([0; 128]); +/// +/// // move the cursor 42 bytes after the start of the buffer +/// buff.seek(SeekFrom::Start(42))?; +/// +/// assert_eq!(buff.stream_position()?, 42); +/// +/// // move the cursor 28 bytes before the end of the buffer +/// buff.seek(SeekFrom::End(-28))?; +/// +/// assert_eq!(buff.stream_position()?, 100); /// -/// // move the cursor 42 bytes from the start of the file -/// f.seek(SeekFrom::Start(42))?; /// Ok(()) /// } /// ``` @@ -55,22 +61,20 @@ pub trait Seek { /// # Example /// /// ```no_run - /// use std::io::{Read, Seek, Write}; - /// use std::fs::OpenOptions; - /// - /// let mut f = OpenOptions::new() - /// .write(true) - /// .read(true) - /// .create(true) - /// .open("foo.txt")?; - /// - /// let hello = "Hello!\n"; - /// write!(f, "{hello}")?; - /// f.rewind()?; - /// - /// let mut buf = String::new(); - /// f.read_to_string(&mut buf)?; - /// assert_eq!(&buf, hello); + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::{Cursor, Seek, Write}; + /// + /// let mut buffer = [0u8; 5]; + /// let mut cursor = Cursor::new(&mut buffer as &mut [u8]); + /// + /// cursor.write_all(&[1, 2, 3])?; + /// + /// cursor.rewind()?; + /// + /// cursor.write_all(&[4, 5, 6])?; + /// + /// assert_eq!(&buffer, &[4u8, 5u8, 6u8, 0u8, 0u8]); /// # std::io::Result::Ok(()) /// ``` #[stable(feature = "seek_rewind", since = "1.55.0")] @@ -99,19 +103,14 @@ pub trait Seek { /// # Example /// /// ```no_run + /// # #![feature(core_io)] /// #![feature(seek_stream_len)] - /// use std::{ - /// io::{self, Seek}, - /// fs::File, - /// }; - /// - /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; + /// # use core as std; + /// use std::io::{Cursor, Seek}; /// - /// let len = f.stream_len()?; - /// println!("The file is currently {len} bytes long"); - /// Ok(()) - /// } + /// let mut cursor = Cursor::new([0; 42]); + /// assert_eq!(cursor.stream_len()?, 42); + /// # std::io::Result::Ok(()) /// ``` #[unstable(feature = "seek_stream_len", issue = "59359")] fn stream_len(&mut self) -> Result { @@ -125,19 +124,24 @@ pub trait Seek { /// # Example /// /// ```no_run - /// use std::{ - /// io::{self, BufRead, BufReader, Seek}, - /// fs::File, - /// }; + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::{self, Cursor, SeekFrom}; + /// use std::io::prelude::*; /// /// fn main() -> io::Result<()> { - /// let mut f = BufReader::new(File::open("foo.txt")?); + /// let mut buff = Cursor::new([0; 128]); + /// + /// // move the cursor 42 bytes after the start of the buffer + /// buff.seek(SeekFrom::Start(42))?; + /// + /// assert_eq!(buff.stream_position()?, 42); + /// + /// // move the cursor 28 bytes before the end of the buffer + /// buff.seek(SeekFrom::End(-28))?; /// - /// let before = f.stream_position()?; - /// f.read_line(&mut String::new())?; - /// let after = f.stream_position()?; + /// assert_eq!(buff.stream_position()?, 100); /// - /// println!("The first line was {} bytes long", after - before); /// Ok(()) /// } /// ``` @@ -155,15 +159,24 @@ pub trait Seek { /// # Example /// /// ```no_run - /// use std::{ - /// io::{self, Seek}, - /// fs::File, - /// }; + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::{self, Cursor}; + /// use std::io::prelude::*; /// /// fn main() -> io::Result<()> { - /// let mut f = File::open("foo.txt")?; - /// f.seek_relative(10)?; - /// assert_eq!(f.stream_position()?, 10); + /// let mut buff = Cursor::new([0; 64]); + /// + /// // move the cursor forward 42 bytes + /// buff.seek_relative(42)?; + /// + /// assert_eq!(buff.stream_position()?, 42); + /// + /// // move the cursor backwards 28 bytes + /// buff.seek_relative(-28)?; + /// + /// assert_eq!(buff.stream_position()?, 14); + /// /// Ok(()) /// } /// ``` diff --git a/library/core/src/io/util.rs b/library/core/src/io/util.rs index 07173f13eb08b..8281c771e5dae 100644 --- a/library/core/src/io/util.rs +++ b/library/core/src/io/util.rs @@ -5,7 +5,7 @@ use crate::{cmp, fmt}; /// (returning zero bytes) when read via [`Read`]. /// /// [`Write`]: crate::io::Write -/// [`Read`]: ../../std/io/trait.Read.html +/// [`Read`]: ../../alloc/io/trait.Read.html /// /// This struct is generally created by calling [`empty()`]. Please /// see the documentation of [`empty()`] for more details. @@ -130,26 +130,19 @@ impl Seek for Empty { /// [`Ok(0)`]: Ok /// /// [`write`]: crate::io::Write::write -/// [`read`]: ../../std/io/trait.Read.html#method.read +/// [`read`]: ../../alloc/io/trait.Read.html#method.read /// /// # Examples /// /// ```rust +/// # #![feature(core_io)] +/// # use core as std; /// use std::io::{self, Write}; /// -/// let buffer = vec![1, 2, 3, 5, 8]; +/// let buffer = [1, 2, 3, 5, 8]; /// let num_bytes = io::empty().write(&buffer).unwrap(); /// assert_eq!(num_bytes, 5); /// ``` -/// -/// -/// ```rust -/// use std::io::{self, Read}; -/// -/// let mut buffer = String::new(); -/// io::empty().read_to_string(&mut buffer).unwrap(); -/// assert!(buffer.is_empty()); -/// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_io_structs", since = "1.79.0")] @@ -190,12 +183,12 @@ impl SizeHint for Repeat { /// /// # Examples /// -/// ``` -/// use std::io::{self, Read}; -/// -/// let mut buffer = [0; 3]; -/// io::repeat(0b101).read_exact(&mut buffer).unwrap(); -/// assert_eq!(buffer, [0b101, 0b101, 0b101]); +/// ```no_run +/// # #![feature(core_io)] +/// # use core as std; +/// // Returns `0b101` infinitely. +/// # #[allow(dead_code)] +/// let repeating_reader = std::io::repeat(0b101); /// ``` #[must_use] #[stable(feature = "rust1", since = "1.0.0")] @@ -309,9 +302,11 @@ impl Write for &Sink { /// # Examples /// /// ```rust +/// # #![feature(core_io)] +/// # use core as std; /// use std::io::{self, Write}; /// -/// let buffer = vec![1, 2, 3, 5, 8]; +/// let buffer = [1, 2, 3, 5, 8]; /// let num_bytes = io::sink().write(&buffer).unwrap(); /// assert_eq!(num_bytes, 5); /// ``` @@ -327,7 +322,7 @@ pub const fn sink() -> Sink { /// This struct is generally created by calling [`chain`] on a reader. /// Please see the documentation of [`chain`] for more details. /// -/// [`chain`]: ../../std/io/trait.Read.html#method.chain +/// [`chain`]: ../../alloc/io/trait.Read.html#method.chain #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] #[non_exhaustive] @@ -366,17 +361,14 @@ impl Chain { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let mut foo_file = File::open("foo.txt")?; - /// let mut bar_file = File::open("bar.txt")?; - /// - /// let chain = foo_file.chain(bar_file); - /// let (foo_file, bar_file) = chain.into_inner(); - /// Ok(()) + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Chain; + /// + /// # #[allow(dead_code)] + /// fn get_first(chain: Chain) -> T { + /// let (first, _second) = chain.into_inner(); + /// first /// } /// ``` #[stable(feature = "more_io_inner_methods", since = "1.20.0")] @@ -393,17 +385,14 @@ impl Chain { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let mut foo_file = File::open("foo.txt")?; - /// let mut bar_file = File::open("bar.txt")?; - /// - /// let chain = foo_file.chain(bar_file); - /// let (foo_file, bar_file) = chain.get_ref(); - /// Ok(()) + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Chain; + /// + /// # #[allow(dead_code)] + /// fn get_first(chain: &Chain) -> &T { + /// let (first, _second) = chain.get_ref(); + /// first /// } /// ``` #[stable(feature = "more_io_inner_methods", since = "1.20.0")] @@ -420,17 +409,14 @@ impl Chain { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let mut foo_file = File::open("foo.txt")?; - /// let mut bar_file = File::open("bar.txt")?; - /// - /// let mut chain = foo_file.chain(bar_file); - /// let (foo_file, bar_file) = chain.get_mut(); - /// Ok(()) + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Chain; + /// + /// # #[allow(dead_code)] + /// fn get_first(chain: &mut Chain) -> &mut T { + /// let (first, _second) = chain.get_mut(); + /// first /// } /// ``` #[stable(feature = "more_io_inner_methods", since = "1.20.0")] @@ -452,7 +438,7 @@ pub const fn chain(first: T, second: U) -> Chain { /// This struct is generally created by calling [`take`] on a reader. /// Please see the documentation of [`take`] for more details. /// -/// [`take`]: ../../std/io/trait.Read.html#method.take +/// [`take`]: ../../alloc/io/trait.Read.html#method.take #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] #[non_exhaustive] @@ -494,23 +480,20 @@ impl Take { /// This instance may reach `EOF` after reading fewer bytes than indicated by /// this method if the underlying [`Read`] instance reaches EOF. /// - /// [`Read`]: ../../std/io/trait.Read.html + /// [`Read`]: ../../alloc/io/trait.Read.html /// /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let f = File::open("foo.txt")?; - /// - /// // read at most five bytes - /// let handle = f.take(5); - /// - /// println!("limit: {}", handle.limit()); - /// Ok(()) + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Take; + /// + /// # #[allow(dead_code)] + /// fn change_limit(take: &mut Take) { + /// if take.limit() < 123 { + /// take.set_limit(123); + /// } /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] @@ -533,19 +516,15 @@ impl Take { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let f = File::open("foo.txt")?; - /// - /// // read at most five bytes - /// let mut handle = f.take(5); - /// handle.set_limit(10); - /// - /// assert_eq!(handle.limit(), 10); - /// Ok(()) + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Take; + /// + /// # #[allow(dead_code)] + /// fn change_limit(take: &mut Take) { + /// if take.limit() < 123 { + /// take.set_limit(123); + /// } /// } /// ``` #[stable(feature = "take_set_limit", since = "1.27.0")] @@ -559,19 +538,13 @@ impl Take { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Take; /// - /// fn main() -> io::Result<()> { - /// let mut file = File::open("foo.txt")?; - /// - /// let mut buffer = [0; 5]; - /// let mut handle = file.take(5); - /// handle.read(&mut buffer)?; - /// - /// let file = handle.into_inner(); - /// Ok(()) + /// # #[allow(dead_code)] + /// fn decompose(take: Take) -> T { + /// take.into_inner() /// } /// ``` #[stable(feature = "io_take_into_inner", since = "1.15.0")] @@ -588,19 +561,13 @@ impl Take { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let mut file = File::open("foo.txt")?; + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Take; /// - /// let mut buffer = [0; 5]; - /// let mut handle = file.take(5); - /// handle.read(&mut buffer)?; - /// - /// let file = handle.get_ref(); - /// Ok(()) + /// # #[allow(dead_code)] + /// fn decompose(take: &Take) -> &T { + /// take.get_ref() /// } /// ``` #[stable(feature = "more_io_inner_methods", since = "1.20.0")] @@ -617,19 +584,13 @@ impl Take { /// # Examples /// /// ```no_run - /// use std::io; - /// use std::io::prelude::*; - /// use std::fs::File; - /// - /// fn main() -> io::Result<()> { - /// let mut file = File::open("foo.txt")?; - /// - /// let mut buffer = [0; 5]; - /// let mut handle = file.take(5); - /// handle.read(&mut buffer)?; + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::Take; /// - /// let file = handle.get_mut(); - /// Ok(()) + /// # #[allow(dead_code)] + /// fn decompose(take: &mut Take) -> &mut T { + /// take.get_mut() /// } /// ``` #[stable(feature = "more_io_inner_methods", since = "1.20.0")] diff --git a/library/core/src/io/write.rs b/library/core/src/io/write.rs index cdddd380885f4..9c56febce7046 100644 --- a/library/core/src/io/write.rs +++ b/library/core/src/io/write.rs @@ -25,17 +25,19 @@ use crate::io::{Error, IoSlice, Result}; /// # Examples /// /// ```no_run +/// # #![feature(core_io)] +/// # use core as std; /// 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")?; +/// let mut buffer = [0u8; 32]; +/// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); /// /// while pos < data.len() { -/// let bytes_written = buffer.write(&data[pos..])?; +/// let bytes_written = cursor.write(&data[pos..])?; /// pos += bytes_written; /// } /// Ok(()) @@ -84,14 +86,21 @@ pub trait Write { /// # Examples /// /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let mut buffer = File::create("foo.txt")?; + /// let data = b"some bytes"; /// - /// // Writes some prefix of the byte string, not necessarily all of it. - /// buffer.write(b"some bytes")?; + /// let mut pos = 0; + /// let mut buffer = [0u8; 32]; + /// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); + /// + /// while pos < data.len() { + /// let bytes_written = cursor.write(&data[pos..])?; + /// pos += bytes_written; + /// } /// Ok(()) /// } /// ``` @@ -112,9 +121,10 @@ pub trait Write { /// # Examples /// /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::IoSlice; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { /// let data1 = [1; 8]; @@ -122,10 +132,11 @@ pub trait Write { /// let io_slice1 = IoSlice::new(&data1); /// let io_slice2 = IoSlice::new(&data2); /// - /// let mut buffer = File::create("foo.txt")?; + /// let mut buffer = [0u8; 32]; + /// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); /// /// // Writes some prefix of the byte string, not necessarily all of it. - /// buffer.write_vectored(&[io_slice1, io_slice2])?; + /// cursor.write_vectored(&[io_slice1, io_slice2])?; /// Ok(()) /// } /// ``` @@ -162,15 +173,19 @@ pub trait Write { /// # Examples /// /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; /// 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")?); + /// let data = b"some bytes" as &[u8]; + /// + /// let mut buffer = [0u8; 32]; + /// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); + /// + /// cursor.write_all(data)?; + /// cursor.flush()?; /// - /// buffer.write_all(b"some bytes")?; - /// buffer.flush()?; /// Ok(()) /// } /// ``` @@ -200,13 +215,19 @@ pub trait Write { /// # Examples /// /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let mut buffer = File::create("foo.txt")?; + /// let data = b"some bytes" as &[u8]; + /// + /// let mut buffer = [0u8; 32]; + /// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); + /// + /// cursor.write_all(data)?; + /// cursor.flush()?; /// - /// buffer.write_all(b"some bytes")?; /// Ok(()) /// } /// ``` @@ -256,7 +277,9 @@ pub trait Write { /// # Examples /// /// ``` + /// # #![feature(core_io)] /// #![feature(write_all_vectored)] + /// # use core as std; /// # fn main() -> std::io::Result<()> { /// /// use std::io::{Write, IoSlice}; @@ -314,16 +337,15 @@ pub trait Write { /// # Examples /// /// ```no_run + /// # #![feature(core_io)] + /// # use core as std; /// use std::io::prelude::*; - /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let mut buffer = File::create("foo.txt")?; + /// let mut buffer = [0u8; 32]; + /// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); /// - /// // this call - /// write!(buffer, "{:.*}", 2, 1.234567)?; - /// // turns into this: - /// buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?; + /// cursor.write_fmt(format_args!("{:.*}", 2, 1.234567))?; /// Ok(()) /// } /// ``` @@ -344,16 +366,19 @@ pub trait Write { /// # Examples /// /// ```no_run - /// use std::io::Write; - /// use std::fs::File; + /// # #![feature(core_io)] + /// # use core as std; + /// use std::io::prelude::*; /// /// fn main() -> std::io::Result<()> { - /// let mut buffer = File::create("foo.txt")?; + /// let mut buffer = [0u8; 32]; + /// let mut cursor = std::io::Cursor::new(&mut buffer as &mut [u8]); /// - /// let reference = buffer.by_ref(); + /// let reference = cursor.by_ref(); /// /// // we can use reference just like our original buffer /// reference.write_all(b"some bytes")?; + /// /// Ok(()) /// } /// ``` diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index b673abdff7ba1..876c88077d240 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -40,6 +40,9 @@ use crate::time::Duration; /// /// # Examples /// +/// A [`TcpStream`] is unbuffered, so each write and/or read will immediately +/// invoke the relevant underlying system call: +/// /// ```no_run /// use std::io::prelude::*; /// use std::net::TcpStream; @@ -53,6 +56,28 @@ use crate::time::Duration; /// } // the stream is closed here /// ``` /// +/// A simple way to buffer the stream is to use a [`BufWriter`]: +/// +/// ```no_run +/// use std::io::prelude::*; +/// use std::io::BufWriter; +/// use std::net::TcpStream; +/// +/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap()); +/// +/// for i in 0..10 { +/// stream.write(&[i+1]).unwrap(); +/// } +/// stream.flush().unwrap(); +/// ``` +/// +/// By wrapping the stream with a `BufWriter`, these ten writes are all grouped +/// together by the buffer and will all be written out in one system call when +/// the `stream` is flushed. +/// +/// [`flush`]: crate::io::BufWriter::flush +/// [`BufWriter`]: crate::io::BufWriter +/// /// # Platform-specific Behavior /// /// On Unix, writes to the underlying socket in `SOCK_STREAM` mode are made with