Skip to content

Commit d0c8c47

Browse files
swsnrbilelmoussaoui
authored andcommitted
Streamline call dispatching in example
1 parent 127805f commit d0c8c47

File tree

1 file changed

+28
-15
lines changed
  • examples/gio_dbus_register_object

1 file changed

+28
-15
lines changed

examples/gio_dbus_register_object/main.rs

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use gio::prelude::*;
1+
use gio::{prelude::*, IOErrorEnum};
22
use std::sync::mpsc::{channel, Receiver, Sender};
33

44
const EXAMPLE_XML: &str = r#"
@@ -12,6 +12,26 @@ const EXAMPLE_XML: &str = r#"
1212
</node>
1313
"#;
1414

15+
#[derive(Debug, glib::Variant)]
16+
struct Hello {
17+
name: String,
18+
}
19+
20+
#[derive(Debug)]
21+
enum Call {
22+
Hello(Hello),
23+
}
24+
25+
impl Call {
26+
pub fn parse(method: &str, parameters: glib::Variant) -> Result<Call, glib::Error> {
27+
match method {
28+
"Hello" => Ok(parameters.get::<Hello>().map(Call::Hello)),
29+
_ => Err(glib::Error::new(IOErrorEnum::Failed, "No such method")),
30+
}
31+
.and_then(|p| p.ok_or_else(|| glib::Error::new(IOErrorEnum::Failed, "Invalid parameters")))
32+
}
33+
}
34+
1535
fn on_startup(app: &gio::Application, tx: &Sender<gio::RegistrationId>) {
1636
let connection = app.dbus_connection().expect("connection");
1737

@@ -26,21 +46,14 @@ fn on_startup(app: &gio::Application, tx: &Sender<gio::RegistrationId>) {
2646
#[strong]
2747
app,
2848
move |_, _, _, _, method, params, invocation| {
29-
match method {
30-
"Hello" => {
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);
49+
let result = Call::parse(method, params).map(|call| match call {
50+
Call::Hello(Hello { name }) => {
51+
let greet = format!("Hello {name}!");
52+
println!("{greet}");
53+
Some(greet.to_variant())
4154
}
42-
_ => unreachable!(),
43-
}
55+
});
56+
invocation.return_result(result);
4457
app.quit();
4558
}
4659
))

0 commit comments

Comments
 (0)