Skip to main content

alloc/io/
mod.rs

1//! Traits, helpers, and type definitions for core I/O functionality.
2//!
3//! The `io` module contains a number of common things you'll need
4//! when doing input and output. The most core part of this module is
5//! the [`Read`] and [`Write`] traits, which provide the
6//! most general interface for reading and writing input and output.
7//!
8//! ## Read and Write
9//!
10//! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11//! of other types, and you can implement them for your types too. As such,
12//! you'll see a few different types of I/O throughout the documentation in
13//! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14//! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
15//! [`File`]s:
16//!
17//! ```no_run
18//! use std::io;
19//! use std::io::prelude::*;
20//! use std::fs::File;
21//!
22//! fn main() -> io::Result<()> {
23//!     let mut f = File::open("foo.txt")?;
24//!     let mut buffer = [0; 10];
25//!
26//!     // read up to 10 bytes
27//!     let n = f.read(&mut buffer)?;
28//!
29//!     println!("The bytes: {:?}", &buffer[..n]);
30//!     Ok(())
31//! }
32//! ```
33//!
34//! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35//! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36//! of 'a type that implements the [`Read`] trait'. Much easier!
37//!
38//! ## Seek and BufRead
39//!
40//! Beyond that, there are two important traits that are provided: [`Seek`]
41//! and [`BufRead`]. Both of these build on top of a reader to control
42//! how the reading happens. [`Seek`] lets you control where the next byte is
43//! coming from:
44//!
45//! ```no_run
46//! use std::io;
47//! use std::io::prelude::*;
48//! use std::io::SeekFrom;
49//! use std::fs::File;
50//!
51//! fn main() -> io::Result<()> {
52//!     let mut f = File::open("foo.txt")?;
53//!     let mut buffer = [0; 10];
54//!
55//!     // skip to the last 10 bytes of the file
56//!     f.seek(SeekFrom::End(-10))?;
57//!
58//!     // read up to 10 bytes
59//!     let n = f.read(&mut buffer)?;
60//!
61//!     println!("The bytes: {:?}", &buffer[..n]);
62//!     Ok(())
63//! }
64//! ```
65//!
66//! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67//! to show it off, we'll need to talk about buffers in general. Keep reading!
68//!
69//! ## BufReader and BufWriter
70//!
71//! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72//! making near-constant calls to the operating system. To help with this,
73//! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74//! readers and writers. The wrapper uses a buffer, reducing the number of
75//! calls and providing nicer methods for accessing exactly what you want.
76//!
77//! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78//! methods to any reader:
79//!
80//! ```no_run
81//! use std::io;
82//! use std::io::prelude::*;
83//! use std::io::BufReader;
84//! use std::fs::File;
85//!
86//! fn main() -> io::Result<()> {
87//!     let f = File::open("foo.txt")?;
88//!     let mut reader = BufReader::new(f);
89//!     let mut buffer = String::new();
90//!
91//!     // read a line into buffer
92//!     reader.read_line(&mut buffer)?;
93//!
94//!     println!("{buffer}");
95//!     Ok(())
96//! }
97//! ```
98//!
99//! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100//! to [`write`][`Write::write`]:
101//!
102//! ```no_run
103//! use std::io;
104//! use std::io::prelude::*;
105//! use std::io::BufWriter;
106//! use std::fs::File;
107//!
108//! fn main() -> io::Result<()> {
109//!     let f = File::create("foo.txt")?;
110//!     {
111//!         let mut writer = BufWriter::new(f);
112//!
113//!         // write a byte to the buffer
114//!         writer.write(&[42])?;
115//!
116//!     } // the buffer is flushed once writer goes out of scope
117//!
118//!     Ok(())
119//! }
120//! ```
121//!
122//! ## Iterator types
123//!
124//! A large number of the structures provided by `std::io` are for various
125//! ways of iterating over I/O. For example, [`Lines`] is used to split over
126//! lines:
127//!
128//! ```no_run
129//! use std::io;
130//! use std::io::prelude::*;
131//! use std::io::BufReader;
132//! use std::fs::File;
133//!
134//! fn main() -> io::Result<()> {
135//!     let f = File::open("foo.txt")?;
136//!     let reader = BufReader::new(f);
137//!
138//!     for line in reader.lines() {
139//!         println!("{}", line?);
140//!     }
141//!     Ok(())
142//! }
143//! ```
144//!
145//! ## io::Result
146//!
147//! Last, but certainly not least, is [`io::Result`]. This type is used
148//! as the return type of many `std::io` functions that can cause an error, and
149//! can be returned from your own functions as well. Many of the examples in this
150//! module use the [`?` operator]:
151//!
152//! ```no_run
153//! use std::io;
154//!
155//! # #[allow(dead_code)]
156//! fn read_input() -> io::Result<()> {
157//!     let mut input = String::new();
158//!
159//!     io::stdin().read_line(&mut input)?;
160//!
161//!     println!("You typed: {}", input.trim());
162//!
163//!     Ok(())
164//! }
165//! ```
166//!
167//! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
168//! common type for functions which don't have a 'real' return value, but do want to
169//! return errors if they happen. In this case, the only purpose of this function is
170//! to read the line and print it, so we use `()`.
171//!
172//! [`File`]: ../../std/fs/struct.File.html
173//! [`TcpStream`]: ../../std/net/struct.TcpStream.html
174//! [`Vec<T>`]: crate::vec::Vec
175//! [`io::Result`]: self::Result
176//! [`?` operator]: ../../book/appendix-02-operators.html
177
178mod buf_read;
179mod buffered;
180mod copy;
181mod cursor;
182mod error;
183mod impls;
184#[unstable(feature = "alloc_io", issue = "154046")]
185pub mod prelude;
186mod read;
187mod util;
188
189#[unstable(feature = "raw_os_error_ty", issue = "107792")]
190pub use core::io::RawOsError;
191#[unstable(feature = "io_const_error_internals", issue = "none")]
192pub use core::io::SimpleMessage;
193#[unstable(feature = "io_const_error", issue = "133448")]
194pub use core::io::const_error;
195#[unstable(feature = "core_io_borrowed_buf", issue = "117693")]
196pub use core::io::{BorrowedBuf, BorrowedCursor};
197#[unstable(feature = "alloc_io", issue = "154046")]
198pub use core::io::{
199    Chain, Cursor, Empty, Error, ErrorKind, IoSlice, IoSliceMut, Repeat, Result, Seek, SeekFrom,
200    Sink, Take, Write, empty, repeat, sink,
201};
202#[doc(hidden)]
203#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
204pub use core::io::{IoHandle, OsFunctions, default_write_vectored, stream_len_default};
205use core::io::{
206    SizeHint, WriteThroughCursor, chain, slice_write, slice_write_all, slice_write_all_vectored,
207    slice_write_vectored, take,
208};
209
210use self::read::{append_to_string, default_read_buf_exact, default_read_exact};
211use self::util::{bytes, lines, split, uninlined_slow_read_byte};
212#[unstable(feature = "alloc_io", issue = "154046")]
213pub use self::{
214    buf_read::BufRead,
215    buffered::{BufReader, BufWriter, IntoInnerError, LineWriter, WriterPanicked},
216    copy::copy,
217    read::{Read, read_to_string},
218    util::{Bytes, Lines, Split},
219};
220#[doc(hidden)]
221#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
222pub use self::{
223    copy::{CopyState, SpecCopy},
224    read::{
225        DEFAULT_BUF_SIZE, default_read_buf, default_read_to_end, default_read_to_string,
226        default_read_vectored,
227    },
228    util::SpecReadByte,
229};