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 serde::{Deserialize, Serialize};
10
11 /// An error number, retrieved from errno (man 3 errno), set by a libc
12 /// function that returned an error.
13 #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
14 #[serde(transparent)]
15 pub struct Error(i32);
16 pub type Result<T> = result::Result<T, Error>;
17
18 impl Error {
19 /// Constructs a new error with the given errno.
new(e: i32) -> Error20 pub fn new(e: i32) -> Error {
21 Error(e)
22 }
23
24 /// Constructs an error from the current errno.
25 ///
26 /// The result of this only has any meaning just after a libc call that returned a value
27 /// indicating errno was set.
last() -> Error28 pub fn last() -> Error {
29 Error(io::Error::last_os_error().raw_os_error().unwrap())
30 }
31
32 /// Gets the errno for this error
errno(self) -> i3233 pub fn errno(self) -> i32 {
34 self.0
35 }
36 }
37
38 impl From<io::Error> for Error {
from(e: io::Error) -> Self39 fn from(e: io::Error) -> Self {
40 Error::new(e.raw_os_error().unwrap_or_default())
41 }
42 }
43
44 impl From<Error> for io::Error {
from(e: Error) -> io::Error45 fn from(e: Error) -> io::Error {
46 io::Error::from_raw_os_error(e.0)
47 }
48 }
49
50 impl std::error::Error for Error {}
51
52 impl Display for Error {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 Into::<io::Error>::into(*self).fmt(f)
55 }
56 }
57
58 /// Returns the last errno as a Result that is always an error.
errno_result<T>() -> Result<T>59 pub fn errno_result<T>() -> Result<T> {
60 Err(Error::last())
61 }
62