• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::fmt::{self, Display};
6 use std::io;
7 use std::result;
8 
9 use libc::__errno_location;
10 
11 /// An error number, retrieved from errno (man 3 errno), set by a libc
12 /// function that returned an error.
13 #[derive(Clone, Copy, Debug, PartialEq)]
14 pub struct Error(i32);
15 pub type Result<T> = result::Result<T, Error>;
16 
17 impl Error {
18     /// Constructs a new error with the given errno.
new(e: i32) -> Error19     pub fn new(e: i32) -> Error {
20         Error(e)
21     }
22 
23     /// Constructs an error from the current errno.
24     ///
25     /// The result of this only has any meaning just after a libc call that returned a value
26     /// indicating errno was set.
last() -> Error27     pub fn last() -> Error {
28         Error(unsafe { *__errno_location() })
29     }
30 
31     /// Gets the errno for this error
errno(self) -> i3232     pub fn errno(self) -> i32 {
33         self.0
34     }
35 }
36 
37 impl From<io::Error> for Error {
from(e: io::Error) -> Self38     fn from(e: io::Error) -> Self {
39         Error::new(e.raw_os_error().unwrap_or_default())
40     }
41 }
42 
43 impl std::error::Error for Error {}
44 
45 impl Display for Error {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result46     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47         io::Error::from_raw_os_error(self.0).fmt(f)
48     }
49 }
50 
51 /// Returns the last errno as a Result that is always an error.
errno_result<T>() -> Result<T>52 pub fn errno_result<T>() -> Result<T> {
53     Err(Error::last())
54 }
55 
56 /// Sets errno to given error code.
57 /// Only defined when we compile tests as normal code does not
58 /// normally need set errno.
59 #[cfg(test)]
set_errno(e: i32)60 pub fn set_errno(e: i32) {
61     unsafe {
62         *__errno_location() = e;
63     }
64 }
65