zx_status/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Type-safe bindings for Zircon status.

use std::ffi::NulError;
use std::{error, fmt, io};
use zx_types as sys;

// Creates associated constants of TypeName of the form
// `pub const NAME: TypeName = TypeName(path::to::value);`
// and provides a private `assoc_const_name` method and a `Debug` implementation
// for the type based on `$name`.
// If multiple names match, the first will be used in `name` and `Debug`.
#[macro_export]
macro_rules! assoc_values {
    ($typename:ident, [$($(#[$attr:meta])* $name:ident = $value:path;)*]) => {
        #[allow(non_upper_case_globals)]
        impl $typename {
            $(
                $(#[$attr])*
                pub const $name: $typename = $typename($value);
            )*

            fn assoc_const_name(&self) -> Option<&'static str> {
                match self.0 {
                    $(
                        $(#[$attr])*
                        $value => Some(stringify!($name)),
                    )*
                    _ => None,
                }
            }
        }

        impl ::std::fmt::Debug for $typename {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                f.write_str(concat!(stringify!($typename), "("))?;
                match self.assoc_const_name() {
                    Some(name) => f.write_str(&name)?,
                    None => ::std::fmt::Debug::fmt(&self.0, f)?,
                }
                f.write_str(")")
            }
        }
    }
}

/// Status type indicating the result of a Fuchsia syscall.
///
/// This type is generally used to indicate the reason for an error.
/// While this type can contain `Status::OK` (`ZX_OK` in C land), elements of this type are
/// generally constructed using the `ok` method, which checks for `ZX_OK` and returns a
/// `Result<(), Status>` appropriately.
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
#[repr(transparent)]
pub struct Status(sys::zx_status_t);
impl Status {
    /// Returns `Ok(())` if the status was `OK`,
    /// otherwise returns `Err(status)`.
    pub fn ok(raw: sys::zx_status_t) -> Result<(), Status> {
        if raw == Status::OK.0 {
            Ok(())
        } else {
            Err(Status(raw))
        }
    }

    pub fn from_raw(raw: sys::zx_status_t) -> Self {
        Status(raw)
    }

    pub fn into_raw(self) -> sys::zx_status_t {
        self.0
    }
}

/// Convenience re-export of `Status::ok`.
pub fn ok(raw: sys::zx_status_t) -> Result<(), Status> {
    Status::ok(raw)
}

assoc_values!(Status, [
    OK                     = sys::ZX_OK;
    INTERNAL               = sys::ZX_ERR_INTERNAL;
    NOT_SUPPORTED          = sys::ZX_ERR_NOT_SUPPORTED;
    NO_RESOURCES           = sys::ZX_ERR_NO_RESOURCES;
    NO_MEMORY              = sys::ZX_ERR_NO_MEMORY;
    INTERRUPTED_RETRY      = sys::ZX_ERR_INTERRUPTED_RETRY;
    INVALID_ARGS           = sys::ZX_ERR_INVALID_ARGS;
    BAD_HANDLE             = sys::ZX_ERR_BAD_HANDLE;
    WRONG_TYPE             = sys::ZX_ERR_WRONG_TYPE;
    BAD_SYSCALL            = sys::ZX_ERR_BAD_SYSCALL;
    OUT_OF_RANGE           = sys::ZX_ERR_OUT_OF_RANGE;
    BUFFER_TOO_SMALL       = sys::ZX_ERR_BUFFER_TOO_SMALL;
    BAD_STATE              = sys::ZX_ERR_BAD_STATE;
    TIMED_OUT              = sys::ZX_ERR_TIMED_OUT;
    SHOULD_WAIT            = sys::ZX_ERR_SHOULD_WAIT;
    CANCELED               = sys::ZX_ERR_CANCELED;
    PEER_CLOSED            = sys::ZX_ERR_PEER_CLOSED;
    NOT_FOUND              = sys::ZX_ERR_NOT_FOUND;
    ALREADY_EXISTS         = sys::ZX_ERR_ALREADY_EXISTS;
    ALREADY_BOUND          = sys::ZX_ERR_ALREADY_BOUND;
    UNAVAILABLE            = sys::ZX_ERR_UNAVAILABLE;
    ACCESS_DENIED          = sys::ZX_ERR_ACCESS_DENIED;
    IO                     = sys::ZX_ERR_IO;
    IO_REFUSED             = sys::ZX_ERR_IO_REFUSED;
    IO_DATA_INTEGRITY      = sys::ZX_ERR_IO_DATA_INTEGRITY;
    IO_DATA_LOSS           = sys::ZX_ERR_IO_DATA_LOSS;
    IO_NOT_PRESENT         = sys::ZX_ERR_IO_NOT_PRESENT;
    IO_OVERRUN             = sys::ZX_ERR_IO_OVERRUN;
    IO_MISSED_DEADLINE     = sys::ZX_ERR_IO_MISSED_DEADLINE;
    IO_INVALID             = sys::ZX_ERR_IO_INVALID;
    BAD_PATH               = sys::ZX_ERR_BAD_PATH;
    NOT_DIR                = sys::ZX_ERR_NOT_DIR;
    NOT_FILE               = sys::ZX_ERR_NOT_FILE;
    FILE_BIG               = sys::ZX_ERR_FILE_BIG;
    NO_SPACE               = sys::ZX_ERR_NO_SPACE;
    NOT_EMPTY              = sys::ZX_ERR_NOT_EMPTY;
    STOP                   = sys::ZX_ERR_STOP;
    NEXT                   = sys::ZX_ERR_NEXT;
    ASYNC                  = sys::ZX_ERR_ASYNC;
    PROTOCOL_NOT_SUPPORTED = sys::ZX_ERR_PROTOCOL_NOT_SUPPORTED;
    ADDRESS_UNREACHABLE    = sys::ZX_ERR_ADDRESS_UNREACHABLE;
    ADDRESS_IN_USE         = sys::ZX_ERR_ADDRESS_IN_USE;
    NOT_CONNECTED          = sys::ZX_ERR_NOT_CONNECTED;
    CONNECTION_REFUSED     = sys::ZX_ERR_CONNECTION_REFUSED;
    CONNECTION_RESET       = sys::ZX_ERR_CONNECTION_RESET;
    CONNECTION_ABORTED     = sys::ZX_ERR_CONNECTION_ABORTED;
]);

impl Status {
    pub fn into_io_error(self) -> io::Error {
        self.into()
    }

    pub fn from_result(res: Result<(), Self>) -> Self {
        res.into()
    }
}

impl From<io::ErrorKind> for Status {
    fn from(kind: io::ErrorKind) -> Self {
        use std::io::ErrorKind::*;
        match kind {
            NotFound => Status::NOT_FOUND,
            PermissionDenied => Status::ACCESS_DENIED,
            ConnectionRefused => Status::IO_REFUSED,
            ConnectionAborted => Status::PEER_CLOSED,
            AddrInUse => Status::ALREADY_BOUND,
            AddrNotAvailable => Status::UNAVAILABLE,
            BrokenPipe => Status::PEER_CLOSED,
            AlreadyExists => Status::ALREADY_EXISTS,
            WouldBlock => Status::SHOULD_WAIT,
            InvalidInput => Status::INVALID_ARGS,
            TimedOut => Status::TIMED_OUT,
            Interrupted => Status::INTERRUPTED_RETRY,
            UnexpectedEof | WriteZero | ConnectionReset | NotConnected | Other | _ => Status::IO,
        }
    }
}

impl From<Status> for io::ErrorKind {
    fn from(status: Status) -> io::ErrorKind {
        use std::io::ErrorKind::*;
        match status {
            Status::INTERRUPTED_RETRY => Interrupted,
            Status::BAD_HANDLE => BrokenPipe,
            Status::TIMED_OUT => TimedOut,
            Status::SHOULD_WAIT => WouldBlock,
            Status::PEER_CLOSED => ConnectionAborted,
            Status::NOT_FOUND => NotFound,
            Status::ALREADY_EXISTS => AlreadyExists,
            Status::ALREADY_BOUND => AlreadyExists,
            Status::UNAVAILABLE => AddrNotAvailable,
            Status::ACCESS_DENIED => PermissionDenied,
            Status::IO_REFUSED => ConnectionRefused,
            Status::IO_DATA_INTEGRITY => InvalidData,

            Status::BAD_PATH | Status::INVALID_ARGS | Status::OUT_OF_RANGE | Status::WRONG_TYPE => {
                InvalidInput
            }

            Status::OK
            | Status::NEXT
            | Status::STOP
            | Status::NO_SPACE
            | Status::FILE_BIG
            | Status::NOT_FILE
            | Status::NOT_DIR
            | Status::IO_DATA_LOSS
            | Status::IO
            | Status::CANCELED
            | Status::BAD_STATE
            | Status::BUFFER_TOO_SMALL
            | Status::BAD_SYSCALL
            | Status::INTERNAL
            | Status::NOT_SUPPORTED
            | Status::NO_RESOURCES
            | Status::NO_MEMORY
            | _ => Other,
        }
    }
}

impl fmt::Display for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.assoc_const_name() {
            Some(name) => name.fmt(f),
            None => write!(f, "Unknown zircon status code: {}", self.0),
        }
    }
}

impl error::Error for Status {}

impl From<io::Error> for Status {
    fn from(err: io::Error) -> Status {
        err.kind().into()
    }
}

impl From<Status> for io::Error {
    fn from(status: Status) -> io::Error {
        io::Error::from(io::ErrorKind::from(status))
    }
}

impl From<NulError> for Status {
    fn from(_error: NulError) -> Status {
        Status::INVALID_ARGS
    }
}

impl From<Result<(), Status>> for Status {
    fn from(res: Result<(), Status>) -> Status {
        match res {
            Ok(()) => Self::OK,
            Err(status) => status,
        }
    }
}

impl From<Status> for Result<(), Status> {
    fn from(src: Status) -> Result<(), Status> {
        Status::ok(src.into_raw())
    }
}

#[cfg(test)]
mod test {
    use super::Status;

    #[test]
    fn status_debug_format() {
        let cases = [
            ("Status(OK)", Status::OK),
            ("Status(BAD_SYSCALL)", Status::BAD_SYSCALL),
            ("Status(NEXT)", Status::NEXT),
            ("Status(-5050)", Status(-5050)),
        ];
        for &(expected, value) in &cases {
            assert_eq!(expected, format!("{:?}", value));
        }
    }

    #[test]
    fn status_into_result() {
        let ok_result: Result<(), Status> = Status::OK.into();
        assert_eq!(ok_result, Ok(()));

        let err_result: Result<(), Status> = Status::BAD_SYSCALL.into();
        assert_eq!(err_result, Err(Status::BAD_SYSCALL));
    }
}