Debian Codegraph @

third_party/rust/dbus/src/crossroads/crossroads.rs

raw
1 use std::collections::BTreeMap;
2 use std::any::{TypeId, Any};
3 use std::ffi::{CString, CStr};
4 use std::fmt;
5 use crate::{Path as PathName, Interface as IfaceName, Member as MemberName, Signature, Message, MessageType};
6 use super::info::{IfaceInfo, MethodInfo, PropInfo, IfaceInfoBuilder};
7 use super::handlers::{Handlers, Par, ParInfo, Mut, MutCtx, MutMethods};
8 use super::stdimpl::DBusProperties;
9
10 // The key is an IfaceName, but if we have that we bump into https://github.com/rust-lang/rust/issues/59732
11 // so we use CString as a workaround.
12 #[derive(Default, Debug)]
13 struct IfaceReg<H: Handlers>(BTreeMap<CString, (TypeId, IfaceInfo<'static, H>)>);
14
15 #[derive(Default)]
16 pub struct PathData<H: Handlers>(Vec<(TypeId, H::Iface)>);
17
18 impl PathData<Par> {
19 pub fn insert_par<I: Any + 'static + Send + Sync>(&mut self, i: I) {
20 let id = TypeId::of::<I>();
21 let t = Box::new(i);
22 self.0.push((id, t));
23 }
24 }
25
26 impl PathData<Mut> {
27 pub fn insert_mut<I: Any + 'static>(&mut self, i: I) {
28 let id = TypeId::of::<I>();
29 let t = Box::new(i);
30 self.0.push((id, t));
31 }
32 }
33
34 impl<H: Handlers> fmt::Debug for PathData<H> {
35 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "...") }
36 }
37
38 impl<H: Handlers> PathData<H> {
39 fn new() -> Self { PathData(vec!()) }
40 }
41
42 #[derive(Debug)]
43 struct IfacePaths<H: Handlers>(BTreeMap<CString, PathData<H>>);
44
45 impl<H: Handlers> Default for IfacePaths<H> {
46 fn default() -> Self { IfacePaths(BTreeMap::new()) }
47 }
48
49 struct MsgHeaders<'a> {
50 m: MemberName<'a>,
51 i: IfaceName<'a>,
52 p: PathName<'a>,
53 }
54
55 fn msg_headers(msg: &Message) -> Option<MsgHeaders> {
56 if msg.msg_type() != MessageType::MethodCall { return None };
57 let p = msg.path()?;
58 let i = msg.interface()?;
59 let m = msg.member()?;
60 Some(MsgHeaders { m, i, p })
61 }
62
63 #[derive(Debug)]
64 pub (super) struct MLookup<'a, H: Handlers> {
65 pub (super) cr: &'a Crossroads<H>,
66 pub (super) data: &'a PathData<H>,
67 pub (super) iface: &'a H::Iface,
68 pub (super) iinfo: &'a IfaceInfo<'static, H>,
69 // pub (super) minfo: Option<&'a MethodInfo<'static, H>>,
70 // pub (super) pinfo: Option<&'a PropInfo<'static, H>>,
71 }
72
73 #[derive(Debug)]
74 pub struct Crossroads<H: Handlers> {
75 reg: IfaceReg<H>,
76 paths: IfacePaths<H>,
77 }
78
79 impl<H: Handlers> Crossroads<H> {
80
81 pub fn register_custom<I: 'static>(&mut self, info: IfaceInfo<'static, H>) -> Option<IfaceInfo<'static, H>> {
82 self.reg.0.insert(info.name.clone().into_cstring(), (TypeId::of::<I>(), info)).map(|x| x.1)
83 }
84 pub fn insert<N: Into<PathName<'static>>>(&mut self, name: N, data: PathData<H>) {
85 self.paths.0.insert(name.into().into_cstring(), data);
86 }
87 pub fn get_data<N: Into<PathName<'static>>>(&self, name: N) -> Option<&PathData<H>> {
88 self.paths.0.get(name.into().as_cstr())
89 }
90
91 pub fn register<'a, I: 'static, N: Into<IfaceName<'static>>>(&'a mut self, name: N) -> IfaceInfoBuilder<'a, I, H> {
92 IfaceInfoBuilder::new(Some(self), name.into())
93 }
94
95 fn reg_lookup(&self, headers: &MsgHeaders) -> Option<(MLookup<H>, &MethodInfo<'static, H>)> {
96 let (typeid, iinfo) = self.reg.0.get(headers.i.as_cstr())?;
97 let minfo = iinfo.methods.iter().find(|x| x.name() == &headers.m)?;
98 let data = self.paths.0.get(headers.p.as_cstr())?;
99 let (_, iface) = data.0.iter().find(|x| x.0 == *typeid)?;
100 Some((MLookup { cr: self, data, iface, iinfo }, minfo))
101 }
102
103 pub (super) fn reg_prop_lookup<'a>(&'a self, data: &'a PathData<H>, iname: &CStr, propname: &CStr) ->
104 Option<(MLookup<'a, H>, &PropInfo<'static, H>)> {
105 let (typeid, iinfo) = self.reg.0.get(iname)?;
106 let pinfo = iinfo.props.iter().find(|x| x.name.as_cstr() == propname)?;
107 let (_, iface) = data.0.iter().find(|x| x.0 == *typeid)?;
108 Some((MLookup { cr: self, data, iface, iinfo}, pinfo))
109 }
110 }
111
112 impl Crossroads<Par> {
113 pub fn dispatch_par(&self, msg: &Message) -> Option<Vec<Message>> {
114 let headers = msg_headers(msg)?;
115 let (lookup, minfo) = self.reg_lookup(&headers)?;
116 let handler = minfo.handler();
117 let iface = &**lookup.iface;
118 let mut info = ParInfo::new(msg, lookup);
119 let r = (handler)(iface, &mut info);
120 Some(r.into_iter().collect())
121 }
122
123 pub fn new_par() -> Self {
124 let mut cr = Crossroads {
125 reg: IfaceReg(BTreeMap::new()),
126 paths: IfacePaths(BTreeMap::new()),
127 };
128 DBusProperties::register(&mut cr);
129 cr
130 }
131 }
132
133 impl Crossroads<Mut> {
134 pub fn dispatch_mut(&mut self, msg: &Message) -> Option<Vec<Message>> {
135 let headers = msg_headers(msg)?;
136 let (typeid, iinfo) = self.reg.0.get_mut(headers.i.as_cstr())?;
137 let minfo = iinfo.methods.iter_mut().find(|x| x.name() == &headers.m)?;
138 let ctx = MutCtx::new(msg);
139 let r = match minfo.handler_mut().0 {
140 MutMethods::MutIface(ref mut f) => {
141 let data = self.paths.0.get_mut(headers.p.as_cstr())?;
142 let (_, iface) = data.0.iter_mut().find(|x| x.0 == *typeid)?;
143 let iface = &mut **iface;
144 f(iface, &ctx)
145 }
146 };
147 Some(r.into_iter().collect())
148 }
149
150 pub fn new_mut() -> Self {
151 let cr = Crossroads {
152 reg: IfaceReg(BTreeMap::new()),
153 paths: IfacePaths(BTreeMap::new()),
154 };
155 // DBusProperties::register(&mut cr);
156 cr
157 }
158 }
159
160
161 #[cfg(test)]
162 mod test {
163 use super::*;
164
165 #[test]
166 fn test_send_sync() {
167 fn is_send<T: Send>(_: &T) {}
168 fn is_sync<T: Sync>(_: &T) {}
169 let c = Crossroads::new_par();
170 dbg!(&c);
171 is_send(&c);
172 is_sync(&c);
173 }
174
175 #[test]
176 fn cr_mut() {
177 let mut cr = Crossroads::new_mut();
178
179 struct Score(u16);
180
181 let mut call_times = 0u32;
182 cr.register::<Score,_>("com.example.dbusrs.crossroads.score")
183 .method_iface("UpdateScore", ("change",), ("new_score", "call_times"), move |score, _, (change,): (u16,)| {
184 score.0 += change;
185 call_times += 1;
186 Ok((score.0, call_times))
187 });
188
189 let mut pdata = PathData::new();
190 pdata.insert_mut(Score(7u16));
191 cr.insert("/", pdata);
192
193 let msg = Message::new_method_call("com.example.dbusrs.crossroads.score", "/", "com.example.dbusrs.crossroads.score", "UpdateScore").unwrap();
194 let mut msg = msg.append1(5u16);
195 crate::message::message_set_serial(&mut msg, 57);
196 let mut r = cr.dispatch_mut(&msg).unwrap();
197 assert_eq!(r.len(), 1);
198 r[0].as_result().unwrap();
199 let (new_score, call_times): (u16, u32) = r[0].read2().unwrap();
200 assert_eq!(new_score, 12);
201 assert_eq!(call_times, 1);
202 }
203
204
205 #[test]
206 fn cr_par() {
207 let mut cr = Crossroads::new_par();
208
209 struct Score(u16);
210
211 cr.register::<Score,_>("com.example.dbusrs.crossroads.score")
212 .method("Hello", ("sender",), ("reply",), |score, _, (sender,): (String,)| {
213 assert_eq!(score.0, 7u16);
214 Ok((format!("Hello {}, my score is {}!", sender, score.0),))
215 })
216 .prop_ro("Score", |score, _| {
217 assert_eq!(score.0, 7u16);
218 Ok(score.0)
219 })
220 .signal::<(u16,),_>("ScoreChanged", ("NewScore",));
221
222 let mut pdata = PathData::new();
223 pdata.insert_par(Score(7u16));
224 pdata.insert_par(DBusProperties);
225 cr.insert("/", pdata);
226
227 let msg = Message::new_method_call("com.example.dbusrs.crossroads.score", "/", "com.example.dbusrs.crossroads.score", "Hello").unwrap();
228 let mut msg = msg.append1("example");
229 crate::message::message_set_serial(&mut msg, 57);
230 let mut r = cr.dispatch_par(&msg).unwrap();
231 assert_eq!(r.len(), 1);
232 r[0].as_result().unwrap();
233 let rr: String = r[0].read1().unwrap();
234 assert_eq!(&rr, "Hello example, my score is 7!");
235
236 let msg = Message::new_method_call("com.example.dbusrs.crossroads.score", "/", "org.freedesktop.DBus.Properties", "Get").unwrap();
237 let mut msg = msg.append2("com.example.dbusrs.crossroads.score", "Score");
238 crate::message::message_set_serial(&mut msg, 57);
239 let mut r = cr.dispatch_par(&msg).unwrap();
240 assert_eq!(r.len(), 1);
241 r[0].as_result().unwrap();
242 let z: u16 = r[0].read1().unwrap();
243 assert_eq!(z, 7u16);
244 }
245 }