summaryrefslogtreecommitdiffstats
path: root/third_party/rust/pulse/src/error.rs
blob: 2e6f7074f27a44621a8d77fecabc9dfd97a9e626 (plain)
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
// Copyright © 2017 Mozilla Foundation
//
// This program is made available under an ISC-style license.  See the
// accompanying file LICENSE for details.

use ffi;
use std::ffi::CStr;

#[macro_export]
macro_rules! error_result {
    ($t:expr, $err:expr) => {
        if $err >= 0 {
            Ok($t)
        } else {
            Err(ErrorCode::from_error_result($err))
        }
    };
}

#[derive(Debug, PartialEq)]
pub struct ErrorCode {
    err: ffi::pa_error_code_t,
}

impl ErrorCode {
    pub fn from_error_result(err: i32) -> Self {
        debug_assert!(err < 0);
        ErrorCode {
            err: (-err) as ffi::pa_error_code_t,
        }
    }

    pub fn from_error_code(err: ffi::pa_error_code_t) -> Self {
        debug_assert!(err > 0);
        ErrorCode { err: err }
    }

    fn desc(&self) -> &'static str {
        let cstr = unsafe { CStr::from_ptr(ffi::pa_strerror(self.err)) };
        cstr.to_str().unwrap()
    }
}

impl ::std::error::Error for ErrorCode {
    fn description(&self) -> &str {
        self.desc()
    }
}

impl ::std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "{:?}: {}", self, self.desc())
    }
}