Coverage Report

Created: 2024-04-26 06:25

/rust/registry/src/index.crates.io-6f17d22bba15001f/dbus-0.9.7/src/error.rs
Line
Count
Source (jump to first uncovered line)
1
use crate::arg::TypeMismatchError;
2
use std::ffi::CString;
3
use std::{ptr, fmt};
4
use crate::{arg, to_c_str, c_str_to_slice, init_dbus, Message};
5
use crate::strings::ErrorName;
6
use std::error::Error as stdError;
7
8
/// D-Bus Error wrapper.
9
///
10
/// This is a wrapper around the libc dbus error object.
11
pub struct Error {
12
    e: ffi::DBusError,
13
}
14
15
unsafe impl Send for Error {}
16
17
// Note! For this Sync impl to be safe, it requires that no functions that take &self,
18
// actually calls into FFI. All functions that call into FFI with a ffi::DBusError
19
// must take &mut self.
20
21
unsafe impl Sync for Error {}
22
23
impl Error {
24
25
    /// Create a new custom D-Bus Error.
26
0
    pub fn new_custom<'a, N: Into<ErrorName<'a>>>(name: N, message: &str) -> Error {
27
0
        let n = to_c_str(&name.into());
28
0
        let m = to_c_str(&message.replace("%","%%"));
29
0
        let mut e = Error::empty();
30
0
31
0
        unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
32
0
        e
33
0
    }
Unexecuted instantiation: <dbus::error::Error>::new_custom::<&dbus::strings::ErrorName>
Unexecuted instantiation: <dbus::error::Error>::new_custom::<&str>
34
35
    /// Create a new generic D-Bus Error with "org.freedesktop.DBus.Error.Failed" as the Error name.
36
0
    pub fn new_failed(message: &str) -> Error {
37
0
        Error::new_custom("org.freedesktop.DBus.Error.Failed", message)
38
0
    }
39
40
0
    pub (crate) fn empty() -> Error {
41
0
        init_dbus();
42
0
        let mut e = ffi::DBusError {
43
0
            name: ptr::null(),
44
0
            message: ptr::null(),
45
0
            dummy: 0,
46
0
            padding1: ptr::null()
47
0
        };
48
0
        unsafe { ffi::dbus_error_init(&mut e); }
49
0
        Error{ e: e }
50
0
    }
51
52
    /// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
53
0
    pub fn name(&self) -> Option<&str> {
54
0
        c_str_to_slice(&self.e.name)
55
0
    }
56
57
    /// Custom message, e g 'Could not find a matching object path'
58
0
    pub fn message(&self) -> Option<&str> {
59
0
        c_str_to_slice(&self.e.message)
60
0
    }
61
62
0
    pub (crate) fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
63
}
64
65
impl Drop for Error {
66
0
    fn drop(&mut self) {
67
0
        unsafe { ffi::dbus_error_free(&mut self.e); }
68
0
    }
69
}
70
71
impl fmt::Debug for Error {
72
0
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
73
0
        write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
74
0
            self.name().unwrap_or(""))
75
0
    }
76
}
77
78
impl stdError for Error {
79
0
    fn description(&self) -> &str { "D-Bus error" }
80
}
81
82
impl fmt::Display for Error {
83
0
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
84
0
        if let Some(x) = self.message() {
85
0
             write!(f, "{}", x)
86
0
        } else { Ok(()) }
87
0
    }
88
}
89
90
impl From<arg::TypeMismatchError> for Error {
91
0
    fn from(t: arg::TypeMismatchError) -> Error {
92
0
        Error::new_custom("org.freedesktop.DBus.Error.Failed", &format!("{}", t))
93
0
    }
94
}
95
96
97
impl From<MethodErr> for Error {
98
0
    fn from(t: MethodErr) -> Error {
99
0
        Error::new_custom(t.errorname(), t.description())
100
0
    }
101
}
102
103
104
0
#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
105
/// A D-Bus Method Error, containing an error name and a description.
106
///
107
/// Unlike the "Error" struct, this is a Rust native struct.
108
pub struct MethodErr(ErrorName<'static>, String);
109
110
impl MethodErr {
111
    /// Create an Invalid Args MethodErr.
112
0
    pub fn invalid_arg<T: fmt::Debug + ?Sized>(a: &T) -> MethodErr {
113
0
        ("org.freedesktop.DBus.Error.InvalidArgs", format!("Invalid argument {:?}", a)).into()
114
0
    }
115
    /// Create a MethodErr that there are not enough arguments given.
116
0
    pub fn no_arg() -> MethodErr {
117
0
        ("org.freedesktop.DBus.Error.InvalidArgs", "Not enough arguments").into()
118
0
    }
119
    /// Create a MethodErr that the method failed in the way specified.
120
0
    pub fn failed<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
121
0
        ("org.freedesktop.DBus.Error.Failed", a.to_string()).into()
122
0
    }
123
124
    /// Create a MethodErr that the Object path was unknown.
125
0
    pub fn no_path<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
126
0
        ("org.freedesktop.DBus.Error.UnknownObject", format!("Unknown object path {}", a)).into()
127
0
    }
128
129
    /// Create a MethodErr that the Interface was unknown.
130
0
    pub fn no_interface<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
131
0
        ("org.freedesktop.DBus.Error.UnknownInterface", format!("Unknown interface {}", a)).into()
132
0
    }
133
    /// Create a MethodErr that the Method was unknown.
134
0
    pub fn no_method<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
135
0
        ("org.freedesktop.DBus.Error.UnknownMethod", format!("Unknown method {}", a)).into()
136
0
    }
137
    /// Create a MethodErr that the Property was unknown.
138
0
    pub fn no_property<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
139
0
        ("org.freedesktop.DBus.Error.UnknownProperty", format!("Unknown property {}", a)).into()
140
0
    }
141
    /// Create a MethodErr that the Property was read-only.
142
0
    pub fn ro_property<T: fmt::Display + ?Sized>(a: &T) -> MethodErr {
143
0
        ("org.freedesktop.DBus.Error.PropertyReadOnly", format!("Property {} is read only", a)).into()
144
0
    }
145
146
    /// Error name accessor
147
0
    pub fn errorname(&self) -> &ErrorName<'static> { &self.0 }
148
    /// Description accessor
149
0
    pub fn description(&self) -> &str { &self.1 }
150
151
    /// Creates an error reply from a method call message.
152
    ///
153
    /// Note: You normally don't need to use this function,
154
    /// as it is called internally from Tree::handle.
155
0
    pub fn to_message(&self, msg: &Message) -> Message {
156
0
        msg.error(&self.0, &CString::new(&*self.1).unwrap())
157
0
    }
158
}
159
160
impl fmt::Display for MethodErr {
161
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162
0
        write!(f, "{}", self.description())
163
0
    }
164
}
165
166
impl stdError for MethodErr {}
167
168
impl From<TypeMismatchError> for MethodErr {
169
0
    fn from(t: TypeMismatchError) -> MethodErr { ("org.freedesktop.DBus.Error.Failed", format!("{}", t)).into() }
170
}
171
172
impl<T: Into<ErrorName<'static>>, M: Into<String>> From<(T, M)> for MethodErr {
173
0
    fn from((t, m): (T, M)) -> MethodErr { MethodErr(t.into(), m.into()) }
Unexecuted instantiation: <dbus::error::MethodErr as core::convert::From<(&str, alloc::string::String)>>::from
Unexecuted instantiation: <dbus::error::MethodErr as core::convert::From<(&str, &str)>>::from
174
}
175
176
impl From<Error> for MethodErr {
177
0
    fn from(t: Error) -> MethodErr {
178
0
        let n = t.name().unwrap_or("org.freedesktop.DBus.Error.Failed");
179
0
        let m = t.message().unwrap_or("Unknown error");
180
0
        MethodErr(String::from(n).into(), m.into())
181
0
    }
182
}