]> git.proxmox.com Git - rustc.git/blob - src/libstd/io/error.rs
Imported Upstream version 1.7.0+dfsg1
[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 specialized [`Result`](../result/enum.Result.html) type for I/O
21 /// operations.
22 ///
23 /// This type is broadly used across `std::io` for any operation which may
24 /// produce an error.
25 ///
26 /// This typedef is generally used to avoid writing out `io::Error` directly and
27 /// is otherwise a direct mapping to `Result`.
28 ///
29 /// While usual Rust style is to import types directly, aliases of `Result`
30 /// often are not, to make it easier to distinguish between them. `Result` is
31 /// generally assumed to be `std::result::Result`, and so users of this alias
32 /// will generally use `io::Result` instead of shadowing the prelude's import
33 /// of `std::result::Result`.
34 ///
35 /// # Examples
36 ///
37 /// A convenience function that bubbles an `io::Result` to its caller:
38 ///
39 /// ```
40 /// use std::io;
41 ///
42 /// fn get_string() -> io::Result<String> {
43 /// let mut buffer = String::new();
44 ///
45 /// try!(io::stdin().read_line(&mut buffer));
46 ///
47 /// Ok(buffer)
48 /// }
49 /// ```
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub type Result<T> = result::Result<T, Error>;
52
53 /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
54 /// associated traits.
55 ///
56 /// Errors mostly originate from the underlying OS, but custom instances of
57 /// `Error` can be created with crafted error messages and a particular value of
58 /// `ErrorKind`.
59 #[derive(Debug)]
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Error {
62 repr: Repr,
63 }
64
65 enum Repr {
66 Os(i32),
67 Custom(Box<Custom>),
68 }
69
70 #[derive(Debug)]
71 struct Custom {
72 kind: ErrorKind,
73 error: Box<error::Error+Send+Sync>,
74 }
75
76 /// A list specifying general categories of I/O error.
77 ///
78 /// This list is intended to grow over time and it is not recommended to
79 /// exhaustively match against it.
80 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
81 #[stable(feature = "rust1", since = "1.0.0")]
82 #[allow(deprecated)]
83 pub enum ErrorKind {
84 /// An entity was not found, often a file.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 NotFound,
87 /// The operation lacked the necessary privileges to complete.
88 #[stable(feature = "rust1", since = "1.0.0")]
89 PermissionDenied,
90 /// The connection was refused by the remote server.
91 #[stable(feature = "rust1", since = "1.0.0")]
92 ConnectionRefused,
93 /// The connection was reset by the remote server.
94 #[stable(feature = "rust1", since = "1.0.0")]
95 ConnectionReset,
96 /// The connection was aborted (terminated) by the remote server.
97 #[stable(feature = "rust1", since = "1.0.0")]
98 ConnectionAborted,
99 /// The network operation failed because it was not connected yet.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 NotConnected,
102 /// A socket address could not be bound because the address is already in
103 /// use elsewhere.
104 #[stable(feature = "rust1", since = "1.0.0")]
105 AddrInUse,
106 /// A nonexistent interface was requested or the requested address was not
107 /// local.
108 #[stable(feature = "rust1", since = "1.0.0")]
109 AddrNotAvailable,
110 /// The operation failed because a pipe was closed.
111 #[stable(feature = "rust1", since = "1.0.0")]
112 BrokenPipe,
113 /// An entity already exists, often a file.
114 #[stable(feature = "rust1", since = "1.0.0")]
115 AlreadyExists,
116 /// The operation needs to block to complete, but the blocking operation was
117 /// requested to not occur.
118 #[stable(feature = "rust1", since = "1.0.0")]
119 WouldBlock,
120 /// A parameter was incorrect.
121 #[stable(feature = "rust1", since = "1.0.0")]
122 InvalidInput,
123 /// Data not valid for the operation were encountered.
124 ///
125 /// Unlike `InvalidInput`, this typically means that the operation
126 /// parameters were valid, however the error was caused by malformed
127 /// input data.
128 ///
129 /// For example, a function that reads a file into a string will error with
130 /// `InvalidData` if the file's contents are not valid UTF-8.
131 #[stable(feature = "io_invalid_data", since = "1.2.0")]
132 InvalidData,
133 /// The I/O operation's timeout expired, causing it to be canceled.
134 #[stable(feature = "rust1", since = "1.0.0")]
135 TimedOut,
136 /// An error returned when an operation could not be completed because a
137 /// call to `write` returned `Ok(0)`.
138 ///
139 /// This typically means that an operation could only succeed if it wrote a
140 /// particular number of bytes but only a smaller number of bytes could be
141 /// written.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 WriteZero,
144 /// This operation was interrupted.
145 ///
146 /// Interrupted operations can typically be retried.
147 #[stable(feature = "rust1", since = "1.0.0")]
148 Interrupted,
149 /// Any I/O error not part of this list.
150 #[stable(feature = "rust1", since = "1.0.0")]
151 Other,
152
153 #[allow(missing_docs)]
154 #[unstable(feature = "read_exact_old", reason = "recently added",
155 issue = "0")]
156 #[rustc_deprecated(since = "1.6.0", reason = "renamed to UnexpectedEof")]
157 UnexpectedEOF,
158
159 /// An error returned when an operation could not be completed because an
160 /// "end of file" was reached prematurely.
161 ///
162 /// This typically means that an operation could only succeed if it read a
163 /// particular number of bytes but only a smaller number of bytes could be
164 /// read.
165 #[stable(feature = "read_exact", since = "1.6.0")]
166 UnexpectedEof,
167
168 /// Any I/O error not part of this list.
169 #[unstable(feature = "io_error_internals",
170 reason = "better expressed through extensible enums that this \
171 enum cannot be exhaustively matched against",
172 issue = "0")]
173 #[doc(hidden)]
174 __Nonexhaustive,
175 }
176
177 impl Error {
178 /// Creates a new I/O error from a known kind of error as well as an
179 /// arbitrary error payload.
180 ///
181 /// This function is used to generically create I/O errors which do not
182 /// originate from the OS itself. The `error` argument is an arbitrary
183 /// payload which will be contained in this `Error`.
184 ///
185 /// # Examples
186 ///
187 /// ```
188 /// use std::io::{Error, ErrorKind};
189 ///
190 /// // errors can be created from strings
191 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
192 ///
193 /// // errors can also be created from other errors
194 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
195 /// ```
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn new<E>(kind: ErrorKind, error: E) -> Error
198 where E: Into<Box<error::Error+Send+Sync>>
199 {
200 Self::_new(kind, error.into())
201 }
202
203 fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
204 Error {
205 repr: Repr::Custom(Box::new(Custom {
206 kind: kind,
207 error: error,
208 }))
209 }
210 }
211
212 /// Returns an error representing the last OS error which occurred.
213 ///
214 /// This function reads the value of `errno` for the target platform (e.g.
215 /// `GetLastError` on Windows) and will return a corresponding instance of
216 /// `Error` for the error code.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn last_os_error() -> Error {
219 Error::from_raw_os_error(sys::os::errno() as i32)
220 }
221
222 /// Creates a new instance of an `Error` from a particular OS error code.
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn from_raw_os_error(code: i32) -> Error {
225 Error { repr: Repr::Os(code) }
226 }
227
228 /// Returns the OS error that this error represents (if any).
229 ///
230 /// If this `Error` was constructed via `last_os_error` or
231 /// `from_raw_os_error`, then this function will return `Some`, otherwise
232 /// it will return `None`.
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn raw_os_error(&self) -> Option<i32> {
235 match self.repr {
236 Repr::Os(i) => Some(i),
237 Repr::Custom(..) => None,
238 }
239 }
240
241 /// Returns a reference to the inner error wrapped by this error (if any).
242 ///
243 /// If this `Error` was constructed via `new` then this function will
244 /// return `Some`, otherwise it will return `None`.
245 #[stable(feature = "io_error_inner", since = "1.3.0")]
246 pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
247 match self.repr {
248 Repr::Os(..) => None,
249 Repr::Custom(ref c) => Some(&*c.error),
250 }
251 }
252
253 /// Returns a mutable reference to the inner error wrapped by this error
254 /// (if any).
255 ///
256 /// If this `Error` was constructed via `new` then this function will
257 /// return `Some`, otherwise it will return `None`.
258 #[stable(feature = "io_error_inner", since = "1.3.0")]
259 pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
260 match self.repr {
261 Repr::Os(..) => None,
262 Repr::Custom(ref mut c) => Some(&mut *c.error),
263 }
264 }
265
266 /// Consumes the `Error`, returning its inner error (if any).
267 ///
268 /// If this `Error` was constructed via `new` then this function will
269 /// return `Some`, otherwise it will return `None`.
270 #[stable(feature = "io_error_inner", since = "1.3.0")]
271 pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
272 match self.repr {
273 Repr::Os(..) => None,
274 Repr::Custom(c) => Some(c.error)
275 }
276 }
277
278 /// Returns the corresponding `ErrorKind` for this error.
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn kind(&self) -> ErrorKind {
281 match self.repr {
282 Repr::Os(code) => sys::decode_error_kind(code),
283 Repr::Custom(ref c) => c.kind,
284 }
285 }
286 }
287
288 impl fmt::Debug for Repr {
289 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
290 match *self {
291 Repr::Os(ref code) =>
292 fmt.debug_struct("Os").field("code", code)
293 .field("message", &sys::os::error_string(*code)).finish(),
294 Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
295 }
296 }
297 }
298
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl fmt::Display for Error {
301 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
302 match self.repr {
303 Repr::Os(code) => {
304 let detail = sys::os::error_string(code);
305 write!(fmt, "{} (os error {})", detail, code)
306 }
307 Repr::Custom(ref c) => c.error.fmt(fmt),
308 }
309 }
310 }
311
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl error::Error for Error {
314 #[allow(deprecated)] // remove with UnexpectedEOF
315 fn description(&self) -> &str {
316 match self.repr {
317 Repr::Os(..) => match self.kind() {
318 ErrorKind::NotFound => "entity not found",
319 ErrorKind::PermissionDenied => "permission denied",
320 ErrorKind::ConnectionRefused => "connection refused",
321 ErrorKind::ConnectionReset => "connection reset",
322 ErrorKind::ConnectionAborted => "connection aborted",
323 ErrorKind::NotConnected => "not connected",
324 ErrorKind::AddrInUse => "address in use",
325 ErrorKind::AddrNotAvailable => "address not available",
326 ErrorKind::BrokenPipe => "broken pipe",
327 ErrorKind::AlreadyExists => "entity already exists",
328 ErrorKind::WouldBlock => "operation would block",
329 ErrorKind::InvalidInput => "invalid input parameter",
330 ErrorKind::InvalidData => "invalid data",
331 ErrorKind::TimedOut => "timed out",
332 ErrorKind::WriteZero => "write zero",
333 ErrorKind::Interrupted => "operation interrupted",
334 ErrorKind::Other => "other os error",
335 ErrorKind::UnexpectedEOF => "unexpected end of file",
336 ErrorKind::UnexpectedEof => "unexpected end of file",
337 ErrorKind::__Nonexhaustive => unreachable!()
338 },
339 Repr::Custom(ref c) => c.error.description(),
340 }
341 }
342
343 fn cause(&self) -> Option<&error::Error> {
344 match self.repr {
345 Repr::Os(..) => None,
346 Repr::Custom(ref c) => c.error.cause(),
347 }
348 }
349 }
350
351 fn _assert_error_is_sync_send() {
352 fn _is_sync_send<T: Sync+Send>() {}
353 _is_sync_send::<Error>();
354 }
355
356 #[cfg(test)]
357 mod test {
358 use prelude::v1::*;
359 use super::{Error, ErrorKind};
360 use error;
361 use error::Error as error_Error;
362 use fmt;
363 use sys::os::error_string;
364
365 #[test]
366 fn test_debug_error() {
367 let code = 6;
368 let msg = error_string(code);
369 let err = Error { repr: super::Repr::Os(code) };
370 let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
371 assert_eq!(format!("{:?}", err), expected);
372 }
373
374 #[test]
375 fn test_downcasting() {
376 #[derive(Debug)]
377 struct TestError;
378
379 impl fmt::Display for TestError {
380 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
381 Ok(())
382 }
383 }
384
385 impl error::Error for TestError {
386 fn description(&self) -> &str {
387 "asdf"
388 }
389 }
390
391 // we have to call all of these UFCS style right now since method
392 // resolution won't implicitly drop the Send+Sync bounds
393 let mut err = Error::new(ErrorKind::Other, TestError);
394 assert!(err.get_ref().unwrap().is::<TestError>());
395 assert_eq!("asdf", err.get_ref().unwrap().description());
396 assert!(err.get_mut().unwrap().is::<TestError>());
397 let extracted = err.into_inner().unwrap();
398 extracted.downcast::<TestError>().unwrap();
399 }
400 }