Skip to content

Commit 127805f

Browse files
swsnrbilelmoussaoui
authored andcommitted
Add convenience function to return a result
1 parent 4e8e08a commit 127805f

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

examples/gio_dbus_register_object/main.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,16 @@ fn on_startup(app: &gio::Application, tx: &Sender<gio::RegistrationId>) {
2828
move |_, _, _, _, method, params, invocation| {
2929
match method {
3030
"Hello" => {
31-
if let Some((name,)) = <(String,)>::from_variant(&params) {
32-
let greet = format!("Hello {name}!");
33-
println!("{greet}");
34-
invocation.return_value(Some(&(greet,).to_variant()));
35-
} else {
36-
invocation.return_error(gio::IOErrorEnum::Failed, "Invalid parameters");
37-
}
31+
let result = <(String,)>::from_variant(&params)
32+
.ok_or_else(|| {
33+
glib::Error::new(gio::IOErrorEnum::Failed, "Invalid parameters")
34+
})
35+
.map(|(name,)| {
36+
let greet = format!("Hello {name}!");
37+
println!("{greet}");
38+
Some(greet.to_variant())
39+
});
40+
invocation.return_result(result);
3841
}
3942
_ => unreachable!(),
4043
}

gio/src/dbus_method_invocation.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Take a look at the license at the top of the repository in the LICENSE file.
22

3-
use glib::{prelude::*, translate::*};
3+
use glib::{prelude::*, translate::*, VariantTy};
44

55
use crate::{ffi, DBusMethodInvocation};
66

@@ -26,4 +26,23 @@ impl DBusMethodInvocation {
2626
);
2727
}
2828
}
29+
30+
// rustdoc-stripper-ignore-next
31+
/// Return a result for this invocation.
32+
///
33+
/// If `Ok` return the contained value with [`return_value`]. If the return
34+
/// value is not a tuple, automatically convert it to a one-element tuple, as
35+
/// DBus return values must be tuples.
36+
///
37+
/// If `Err` return the contained error with [`return_gerror`].
38+
pub fn return_result(self, result: Result<Option<glib::Variant>, glib::Error>) {
39+
match result {
40+
Ok(Some(value)) if !value.is_type(VariantTy::TUPLE) => {
41+
let tupled = glib::Variant::tuple_from_iter(std::iter::once(value));
42+
self.return_value(Some(&tupled));
43+
}
44+
Ok(value) => self.return_value(value.as_ref()),
45+
Err(error) => self.return_gerror(error),
46+
}
47+
}
2948
}

0 commit comments

Comments
 (0)