]> git.proxmox.com Git - rustc.git/blob - src/libstd/io/error.rs
97c5a29d308a11c8975611bac9680094f78a153e
[rustc.git] / src / libstd / io / error.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use boxed::Box;
12 use convert::Into;
13 use error;
14 use fmt;
15 use marker::{Send, Sync};
16 use option::Option::{self, Some, None};
17 use result;
18 use sys;
19
20 /// A type for results generated by I/O related functions where the `Err` type
21 /// is hard-wired to `io::Error`.
22 ///
23 /// This typedef is generally used to avoid writing out `io::Error` directly and
24 /// is otherwise a direct mapping to `std::result::Result`.
25 #[stable(feature = "rust1", since = "1.0.0")]
26 pub type Result<T> = result::Result<T, Error>;
27
28 /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
29 /// associated traits.
30 ///
31 /// Errors mostly originate from the underlying OS, but custom instances of
32 /// `Error` can be created with crafted error messages and a particular value of
33 /// `ErrorKind`.
34 #[derive(Debug)]
35 #[stable(feature = "rust1", since = "1.0.0")]
36 pub struct Error {
37 repr: Repr,
38 }
39
40 #[derive(Debug)]
41 enum Repr {
42 Os(i32),
43 Custom(Box<Custom>),
44 }
45
46 #[derive(Debug)]
47 struct Custom {
48 kind: ErrorKind,
49 error: Box<error::Error+Send+Sync>,
50 }
51
52 /// A list specifying general categories of I/O error.
53 ///
54 /// This list is intended to grow over time and it is not recommended to
55 /// exhaustively match against it.
56 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub enum ErrorKind {
59 /// An entity was not found, often a file.
60 #[stable(feature = "rust1", since = "1.0.0")]
61 NotFound,
62 /// The operation lacked the necessary privileges to complete.
63 #[stable(feature = "rust1", since = "1.0.0")]
64 PermissionDenied,
65 /// The connection was refused by the remote server.
66 #[stable(feature = "rust1", since = "1.0.0")]
67 ConnectionRefused,
68 /// The connection was reset by the remote server.
69 #[stable(feature = "rust1", since = "1.0.0")]
70 ConnectionReset,
71 /// The connection was aborted (terminated) by the remote server.
72 #[stable(feature = "rust1", since = "1.0.0")]
73 ConnectionAborted,
74 /// The network operation failed because it was not connected yet.
75 #[stable(feature = "rust1", since = "1.0.0")]
76 NotConnected,
77 /// A socket address could not be bound because the address is already in
78 /// use elsewhere.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 AddrInUse,
81 /// A nonexistent interface was requested or the requested address was not
82 /// local.
83 #[stable(feature = "rust1", since = "1.0.0")]
84 AddrNotAvailable,
85 /// The operation failed because a pipe was closed.
86 #[stable(feature = "rust1", since = "1.0.0")]
87 BrokenPipe,
88 /// An entity already exists, often a file.
89 #[stable(feature = "rust1", since = "1.0.0")]
90 AlreadyExists,
91 /// The operation needs to block to complete, but the blocking operation was
92 /// requested to not occur.
93 #[stable(feature = "rust1", since = "1.0.0")]
94 WouldBlock,
95 /// A parameter was incorrect.
96 #[stable(feature = "rust1", since = "1.0.0")]
97 InvalidInput,
98 /// The I/O operation's timeout expired, causing it to be canceled.
99 #[stable(feature = "rust1", since = "1.0.0")]
100 TimedOut,
101 /// An error returned when an operation could not be completed because a
102 /// call to `write` returned `Ok(0)`.
103 ///
104 /// This typically means that an operation could only succeed if it wrote a
105 /// particular number of bytes but only a smaller number of bytes could be
106 /// written.
107 #[stable(feature = "rust1", since = "1.0.0")]
108 WriteZero,
109 /// This operation was interrupted.
110 ///
111 /// Interrupted operations can typically be retried.
112 #[stable(feature = "rust1", since = "1.0.0")]
113 Interrupted,
114 /// Any I/O error not part of this list.
115 #[stable(feature = "rust1", since = "1.0.0")]
116 Other,
117
118 /// Any I/O error not part of this list.
119 #[unstable(feature = "std_misc",
120 reason = "better expressed through extensible enums that this \
121 enum cannot be exhaustively matched against")]
122 #[doc(hidden)]
123 __Nonexhaustive,
124 }
125
126 impl Error {
127 /// Creates a new I/O error from a known kind of error as well as an
128 /// arbitrary error payload.
129 ///
130 /// This function is used to generically create I/O errors which do not
131 /// originate from the OS itself. The `error` argument is an arbitrary
132 /// payload which will be contained in this `Error`. Accessors as well as
133 /// downcasting will soon be added to this type as well to access the custom
134 /// information.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use std::io::{Error, ErrorKind};
140 ///
141 /// // errors can be created from strings
142 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
143 ///
144 /// // errors can also be created from other errors
145 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
146 /// ```
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn new<E>(kind: ErrorKind, error: E) -> Error
149 where E: Into<Box<error::Error+Send+Sync>>
150 {
151 Error {
152 repr: Repr::Custom(Box::new(Custom {
153 kind: kind,
154 error: error.into(),
155 }))
156 }
157 }
158
159 /// Returns an error representing the last OS error which occurred.
160 ///
161 /// This function reads the value of `errno` for the target platform (e.g.
162 /// `GetLastError` on Windows) and will return a corresponding instance of
163 /// `Error` for the error code.
164 #[stable(feature = "rust1", since = "1.0.0")]
165 pub fn last_os_error() -> Error {
166 Error::from_raw_os_error(sys::os::errno() as i32)
167 }
168
169 /// Creates a new instance of an `Error` from a particular OS error code.
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub fn from_raw_os_error(code: i32) -> Error {
172 Error { repr: Repr::Os(code) }
173 }
174
175 /// Returns the OS error that this error represents (if any).
176 ///
177 /// If this `Error` was constructed via `last_os_error` then this function
178 /// will return `Some`, otherwise it will return `None`.
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn raw_os_error(&self) -> Option<i32> {
181 match self.repr {
182 Repr::Os(i) => Some(i),
183 Repr::Custom(..) => None,
184 }
185 }
186
187 /// Returns the corresponding `ErrorKind` for this error.
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub fn kind(&self) -> ErrorKind {
190 match self.repr {
191 Repr::Os(code) => sys::decode_error_kind(code),
192 Repr::Custom(ref c) => c.kind,
193 }
194 }
195 }
196
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl fmt::Display for Error {
199 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
200 match self.repr {
201 Repr::Os(code) => {
202 let detail = sys::os::error_string(code);
203 write!(fmt, "{} (os error {})", detail, code)
204 }
205 Repr::Custom(ref c) => c.error.fmt(fmt),
206 }
207 }
208 }
209
210 #[stable(feature = "rust1", since = "1.0.0")]
211 impl error::Error for Error {
212 fn description(&self) -> &str {
213 match self.repr {
214 Repr::Os(..) => "os error",
215 Repr::Custom(ref c) => c.error.description(),
216 }
217 }
218 }
219
220 fn _assert_error_is_sync_send() {
221 fn _is_sync_send<T: Sync+Send>() {}
222 _is_sync_send::<Error>();
223 }