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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
use crate::params::message;
use crate::signature::SignatureIter;
use crate::wire::marshal::traits::{Marshal, SignatureBuffer};
use crate::wire::marshal::MarshalContext;
use crate::wire::unmarshal::UnmarshalContext;
use crate::wire::validate_raw;
use crate::wire::UnixFd;
use crate::ByteOrder;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum MessageType {
Signal,
Error,
Call,
Reply,
Invalid,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum HeaderFlags {
NoReplyExpected,
NoAutoStart,
AllowInteractiveAuthorization,
}
impl HeaderFlags {
pub fn into_raw(self) -> u8 {
match self {
HeaderFlags::NoReplyExpected => 1,
HeaderFlags::NoAutoStart => 2,
HeaderFlags::AllowInteractiveAuthorization => 4,
}
}
pub fn is_set(self, flags: u8) -> bool {
flags & self.into_raw() == 1
}
pub fn set(self, flags: &mut u8) {
*flags |= self.into_raw()
}
pub fn unset(self, flags: &mut u8) {
*flags &= 0xFF - self.into_raw()
}
pub fn toggle(self, flags: &mut u8) {
if self.is_set(*flags) {
self.unset(flags)
} else {
self.set(flags)
}
}
}
#[derive(Debug, Clone, Default)]
pub struct DynamicHeader {
pub interface: Option<String>,
pub member: Option<String>,
pub object: Option<String>,
pub destination: Option<String>,
pub serial: Option<u32>,
pub sender: Option<String>,
pub signature: Option<String>,
pub error_name: Option<String>,
pub response_serial: Option<u32>,
pub num_fds: Option<u32>,
}
impl DynamicHeader {
pub fn make_error_response<S: Into<String>>(
&self,
error_name: S,
error_msg: Option<String>,
) -> crate::message_builder::MarshalledMessage {
let mut err_resp = crate::message_builder::MarshalledMessage {
typ: MessageType::Reply,
dynheader: DynamicHeader {
interface: None,
member: None,
object: None,
destination: self.sender.clone(),
serial: None,
num_fds: None,
sender: None,
signature: None,
response_serial: self.serial,
error_name: Some(error_name.into()),
},
flags: 0,
body: crate::message_builder::MarshalledMessageBody::new(),
};
if let Some(text) = error_msg {
err_resp.body.push_param(text).unwrap();
}
err_resp
}
pub fn make_response(&self) -> crate::message_builder::MarshalledMessage {
crate::message_builder::MarshalledMessage {
typ: MessageType::Reply,
dynheader: DynamicHeader {
interface: None,
member: None,
object: None,
destination: self.sender.clone(),
serial: None,
num_fds: None,
sender: None,
signature: None,
response_serial: self.serial,
error_name: None,
},
flags: 0,
body: crate::message_builder::MarshalledMessageBody::new(),
}
}
}
#[derive(Default)]
pub struct MessageBuilder {
msg: MarshalledMessage,
}
pub struct CallBuilder {
msg: MarshalledMessage,
}
pub struct SignalBuilder {
msg: MarshalledMessage,
}
impl MessageBuilder {
pub fn new() -> MessageBuilder {
MessageBuilder {
msg: MarshalledMessage::new(),
}
}
pub fn with_byteorder(b: ByteOrder) -> MessageBuilder {
MessageBuilder {
msg: MarshalledMessage::with_byteorder(b),
}
}
pub fn call<S: Into<String>>(mut self, member: S) -> CallBuilder {
self.msg.typ = MessageType::Call;
self.msg.dynheader.member = Some(member.into());
CallBuilder { msg: self.msg }
}
pub fn signal<S1, S2, S3>(mut self, interface: S1, member: S2, object: S3) -> SignalBuilder
where
S1: Into<String>,
S2: Into<String>,
S3: Into<String>,
{
self.msg.typ = MessageType::Signal;
self.msg.dynheader.member = Some(member.into());
self.msg.dynheader.interface = Some(interface.into());
self.msg.dynheader.object = Some(object.into());
SignalBuilder { msg: self.msg }
}
}
impl CallBuilder {
pub fn on<S: Into<String>>(mut self, object_path: S) -> Self {
self.msg.dynheader.object = Some(object_path.into());
self
}
pub fn with_interface<S: Into<String>>(mut self, interface: S) -> Self {
self.msg.dynheader.interface = Some(interface.into());
self
}
pub fn at<S: Into<String>>(mut self, destination: S) -> Self {
self.msg.dynheader.destination = Some(destination.into());
self
}
pub fn build(self) -> MarshalledMessage {
self.msg
}
}
impl SignalBuilder {
pub fn to<S: Into<String>>(mut self, destination: S) -> Self {
self.msg.dynheader.destination = Some(destination.into());
self
}
pub fn build(self) -> MarshalledMessage {
self.msg
}
}
#[derive(Debug)]
pub struct MarshalledMessage {
pub body: MarshalledMessageBody,
pub dynheader: DynamicHeader,
pub typ: MessageType,
pub flags: u8,
}
impl Default for MarshalledMessage {
fn default() -> Self {
Self::new()
}
}
impl MarshalledMessage {
pub fn get_buf(&self) -> &[u8] {
&self.body.buf
}
pub fn get_sig(&self) -> &str {
&self.body.sig
}
pub fn new() -> Self {
MarshalledMessage {
typ: MessageType::Invalid,
dynheader: DynamicHeader::default(),
flags: 0,
body: MarshalledMessageBody::new(),
}
}
pub fn with_byteorder(b: ByteOrder) -> Self {
MarshalledMessage {
typ: MessageType::Invalid,
dynheader: DynamicHeader::default(),
flags: 0,
body: MarshalledMessageBody::with_byteorder(b),
}
}
pub fn reserve(&mut self, additional: usize) {
self.body.reserve(additional)
}
pub fn unmarshall_all<'a, 'e>(self) -> Result<message::Message<'a, 'e>, crate::Error> {
let params = if self.body.sig.is_empty() {
vec![]
} else {
let sigs: Vec<_> = crate::signature::Type::parse_description(&self.body.sig)?;
let (_, params) = crate::wire::unmarshal::unmarshal_body(
self.body.byteorder,
&sigs,
&self.body.buf,
&self.body.raw_fds,
0,
)?;
params
};
Ok(message::Message {
dynheader: self.dynheader,
params,
typ: self.typ,
flags: self.flags,
raw_fds: self.body.raw_fds,
})
}
}
#[derive(Debug)]
pub struct MarshalledMessageBody {
pub(crate) buf: Vec<u8>,
pub(crate) raw_fds: Vec<crate::wire::UnixFd>,
sig: SignatureBuffer,
pub(crate) byteorder: ByteOrder,
}
impl Default for MarshalledMessageBody {
fn default() -> Self {
Self::new()
}
}
pub fn marshal_as_variant<P: Marshal>(
p: P,
byteorder: ByteOrder,
buf: &mut Vec<u8>,
fds: &mut Vec<crate::wire::UnixFd>,
) -> Result<(), crate::Error> {
let mut ctx = MarshalContext {
fds,
buf,
byteorder,
};
let ctx = &mut ctx;
let mut sig_str = SignatureBuffer::new();
P::sig_str(&mut sig_str);
let sig = crate::wire::SignatureWrapper::new(sig_str)?;
sig.marshal(ctx)?;
p.marshal(ctx)?;
Ok(())
}
impl MarshalledMessageBody {
pub fn new() -> Self {
MarshalledMessageBody {
buf: Vec::new(),
raw_fds: Vec::new(),
sig: SignatureBuffer::new(),
byteorder: ByteOrder::LittleEndian,
}
}
pub fn with_byteorder(b: ByteOrder) -> Self {
MarshalledMessageBody {
buf: Vec::new(),
raw_fds: Vec::new(),
sig: SignatureBuffer::new(),
byteorder: b,
}
}
pub fn from_parts(
buf: Vec<u8>,
raw_fds: Vec<crate::wire::UnixFd>,
sig: String,
byteorder: ByteOrder,
) -> Self {
let sig = SignatureBuffer::from_string(sig);
Self {
buf,
raw_fds,
sig,
byteorder,
}
}
pub fn get_fds(&self) -> Vec<UnixFd> {
self.raw_fds.clone()
}
pub fn reset(&mut self) {
self.sig.clear();
self.buf.clear();
}
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(additional)
}
pub fn push_old_param(&mut self, p: &crate::params::Param) -> Result<(), crate::Error> {
let mut ctx = MarshalContext {
buf: &mut self.buf,
fds: &mut self.raw_fds,
byteorder: self.byteorder,
};
let ctx = &mut ctx;
crate::wire::marshal::container::marshal_param(p, ctx)?;
p.sig().to_str(self.sig.to_string_mut());
Ok(())
}
pub fn push_old_params(&mut self, ps: &[crate::params::Param]) -> Result<(), crate::Error> {
for p in ps {
self.push_old_param(p)?;
}
Ok(())
}
fn create_ctx(&mut self) -> MarshalContext {
MarshalContext {
buf: &mut self.buf,
fds: &mut self.raw_fds,
byteorder: self.byteorder,
}
}
pub fn push_param<P: Marshal>(&mut self, p: P) -> Result<(), crate::Error> {
let mut ctx = self.create_ctx();
p.marshal(&mut ctx)?;
P::sig_str(&mut self.sig);
Ok(())
}
fn push_mult_helper<F>(&mut self, push_calls: F) -> Result<(), crate::Error>
where
F: FnOnce(&mut MarshalledMessageBody) -> Result<(), crate::Error>,
{
let sig_len = self.sig.len();
let buf_len = self.buf.len();
let fds_len = self.raw_fds.len();
match push_calls(self) {
Ok(ret) => Ok(ret),
Err(e) => {
self.sig.truncate(sig_len)?;
self.buf.truncate(buf_len);
self.raw_fds.truncate(fds_len);
Err(e)
}
}
}
pub fn push_param2<P1: Marshal, P2: Marshal>(
&mut self,
p1: P1,
p2: P2,
) -> Result<(), crate::Error> {
self.push_mult_helper(move |msg: &mut Self| {
msg.push_param(p1)?;
msg.push_param(p2)
})
}
pub fn push_param3<P1: Marshal, P2: Marshal, P3: Marshal>(
&mut self,
p1: P1,
p2: P2,
p3: P3,
) -> Result<(), crate::Error> {
self.push_mult_helper(move |msg: &mut Self| {
msg.push_param(p1)?;
msg.push_param(p2)?;
msg.push_param(p3)
})
}
pub fn push_param4<P1: Marshal, P2: Marshal, P3: Marshal, P4: Marshal>(
&mut self,
p1: P1,
p2: P2,
p3: P3,
p4: P4,
) -> Result<(), crate::Error> {
self.push_mult_helper(move |msg: &mut Self| {
msg.push_param(p1)?;
msg.push_param(p2)?;
msg.push_param(p3)?;
msg.push_param(p4)
})
}
pub fn push_param5<P1: Marshal, P2: Marshal, P3: Marshal, P4: Marshal, P5: Marshal>(
&mut self,
p1: P1,
p2: P2,
p3: P3,
p4: P4,
p5: P5,
) -> Result<(), crate::Error> {
self.push_mult_helper(move |msg: &mut Self| {
msg.push_param(p1)?;
msg.push_param(p2)?;
msg.push_param(p3)?;
msg.push_param(p4)?;
msg.push_param(p5)
})
}
pub fn push_params<P: Marshal>(&mut self, params: &[P]) -> Result<(), crate::Error> {
for p in params {
self.push_param(p)?;
}
Ok(())
}
pub fn push_variant<P: Marshal>(&mut self, p: P) -> Result<(), crate::Error> {
self.sig.push_static("v");
let mut ctx = self.create_ctx();
p.marshal_as_variant(&mut ctx)
}
pub fn validate(&self) -> Result<(), crate::wire::unmarshal::Error> {
if self.sig.is_empty() && self.buf.is_empty() {
return Ok(());
}
let types = crate::signature::Type::parse_description(&self.sig)?;
let mut used = 0;
for typ in types {
used += validate_raw::validate_marshalled(self.byteorder, used, &self.buf, &typ)
.map_err(|(_, e)| e)?;
}
if used == self.buf.len() {
Ok(())
} else {
Err(crate::wire::unmarshal::Error::NotAllBytesUsed)
}
}
#[inline]
pub fn parser(&self) -> MessageBodyParser {
MessageBodyParser::new(&self)
}
}
#[test]
fn test_marshal_trait() {
let mut body = MarshalledMessageBody::new();
let bytes: &[&[_]] = &[&[4u64]];
body.push_param(bytes).unwrap();
assert_eq!(
vec![12, 0, 0, 0, 8, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0],
body.buf
);
assert_eq!(body.sig.as_str(), "aat");
let mut body = MarshalledMessageBody::new();
let mut map = std::collections::HashMap::new();
map.insert("a", 4u32);
body.push_param(&map).unwrap();
assert_eq!(
vec![12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, b'a', 0, 0, 0, 4, 0, 0, 0,],
body.buf
);
assert_eq!(body.sig.as_str(), "a{su}");
let mut body = MarshalledMessageBody::new();
body.push_param((11u64, "str", true)).unwrap();
assert_eq!(body.sig.as_str(), "(tsb)");
assert_eq!(
vec![11, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, b's', b't', b'r', 0, 1, 0, 0, 0,],
body.buf
);
struct MyStruct {
x: u64,
y: String,
}
use crate::wire::marshal::traits::Signature;
use crate::wire::marshal::MarshalContext;
impl Signature for &MyStruct {
fn signature() -> crate::signature::Type {
crate::signature::Type::Container(crate::signature::Container::Struct(
crate::signature::StructTypes::new(vec![u64::signature(), String::signature()])
.unwrap(),
))
}
fn alignment() -> usize {
8
}
#[inline]
fn sig_str(s_buf: &mut crate::wire::marshal::traits::SignatureBuffer) {
s_buf.push_static("(ts)")
}
fn has_sig(sig: &str) -> bool {
sig == "(ts)"
}
}
impl Marshal for &MyStruct {
fn marshal(&self, ctx: &mut MarshalContext) -> Result<(), crate::Error> {
ctx.align_to(8);
self.x.marshal(ctx)?;
self.y.marshal(ctx)?;
Ok(())
}
}
let mut body = MarshalledMessageBody::new();
body.push_param(&MyStruct {
x: 100,
y: "A".to_owned(),
})
.unwrap();
assert_eq!(body.sig.as_str(), "(ts)");
assert_eq!(
vec![100, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, b'A', 0,],
body.buf
);
let mut body = MarshalledMessageBody::new();
let emptymap: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();
let mut map = std::collections::HashMap::new();
let mut map2 = std::collections::HashMap::new();
map.insert("a", 4u32);
map2.insert("a", &map);
body.push_param(&map2).unwrap();
body.push_param(&emptymap).unwrap();
assert_eq!(body.sig.as_str(), "a{sa{su}}a{su}");
assert_eq!(
vec![
28, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, b'a', 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, b'a', 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0
],
body.buf
);
let mut body_iter = MessageBodyParser::new(&body);
type WrongNestedDict =
std::collections::HashMap<String, std::collections::HashMap<String, u64>>;
assert_eq!(
body_iter.get::<WrongNestedDict>().err().unwrap(),
crate::wire::unmarshal::Error::WrongSignature
);
type WrongStruct = (u64, i32, String);
assert_eq!(
body_iter.get::<WrongStruct>().err().unwrap(),
crate::wire::unmarshal::Error::WrongSignature
);
type NestedDict = std::collections::HashMap<String, std::collections::HashMap<String, u32>>;
let newmap2: NestedDict = body_iter.get().unwrap();
assert_eq!(newmap2.len(), 1);
assert_eq!(newmap2.get("a").unwrap().len(), 1);
assert_eq!(*newmap2.get("a").unwrap().get("a").unwrap(), 4);
assert_eq!(
body_iter.get::<WrongNestedDict>().err().unwrap(),
crate::wire::unmarshal::Error::WrongSignature
);
assert_eq!(
body_iter.get::<WrongStruct>().err().unwrap(),
crate::wire::unmarshal::Error::WrongSignature
);
let newemptymap: std::collections::HashMap<&str, u32> = body_iter.get().unwrap();
assert_eq!(newemptymap.len(), 0);
let mut body_iter = body.parser();
assert_eq!(
body_iter.get2::<NestedDict, u16>().unwrap_err(),
crate::wire::unmarshal::Error::WrongSignature
);
assert_eq!(
body_iter
.get3::<NestedDict, std::collections::HashMap<&str, u32>, u32>()
.unwrap_err(),
crate::wire::unmarshal::Error::EndOfMessage
);
let (newmap2, newemptymap): (NestedDict, std::collections::HashMap<&str, u32>) =
body_iter.get2().unwrap();
assert_eq!(newmap2.len(), 1);
assert_eq!(newmap2.get("a").unwrap().len(), 1);
assert_eq!(*newmap2.get("a").unwrap().get("a").unwrap(), 4);
assert_eq!(newemptymap.len(), 0);
assert_eq!(
body_iter.get::<u16>().unwrap_err(),
crate::wire::unmarshal::Error::EndOfMessage
);
let mut body_iter = body.parser();
let newmap2: NestedDict = body_iter.get().unwrap();
let newemptymap = body_iter.get_param().unwrap();
assert_eq!(newmap2.len(), 1);
assert_eq!(newmap2.get("a").unwrap().len(), 1);
assert_eq!(*newmap2.get("a").unwrap().get("a").unwrap(), 4);
use crate::params::Container;
use crate::params::Param;
match newemptymap {
Param::Container(Container::Dict(dict)) => {
assert_eq!(dict.map.len(), 0);
assert_eq!(dict.key_sig, crate::signature::Base::String);
assert_eq!(
dict.value_sig,
crate::signature::Type::Base(crate::signature::Base::Uint32)
);
}
_ => panic!("Expected to get a dict"),
}
assert_eq!(
body_iter.get::<u16>().unwrap_err(),
crate::wire::unmarshal::Error::EndOfMessage
);
}
use crate::wire::unmarshal::traits::Unmarshal;
#[derive(Debug)]
pub struct MessageBodyParser<'body> {
buf_idx: usize,
sig_idx: usize,
body: &'body MarshalledMessageBody,
}
impl<'fds, 'body: 'fds> MessageBodyParser<'body> {
pub fn new(body: &'body MarshalledMessageBody) -> Self {
Self {
buf_idx: 0,
sig_idx: 0,
body,
}
}
#[inline(always)]
fn sig_iter(&self) -> SignatureIter<'body> {
SignatureIter::new_at_idx(self.body.sig.as_str(), self.sig_idx)
}
#[inline(always)]
pub fn get_next_sig(&self) -> Option<&'body str> {
self.sig_iter().next()
}
#[inline(always)]
pub fn sigs_left(&self) -> usize {
self.sig_iter().count()
}
pub fn get<T: Unmarshal<'body, 'fds>>(&mut self) -> Result<T, crate::wire::unmarshal::Error> {
if let Some(expected_sig) = self.get_next_sig() {
if !T::has_sig(expected_sig) {
return Err(crate::wire::unmarshal::Error::WrongSignature);
}
let mut ctx = UnmarshalContext {
byteorder: self.body.byteorder,
buf: &self.body.buf,
offset: self.buf_idx,
fds: &self.body.raw_fds,
};
match T::unmarshal(&mut ctx) {
Ok((bytes, res)) => {
self.buf_idx += bytes;
self.sig_idx += expected_sig.len();
Ok(res)
}
Err(e) => Err(e),
}
} else {
Err(crate::wire::unmarshal::Error::EndOfMessage)
}
}
fn get_mult_helper<T, F>(
&mut self,
count: usize,
get_calls: F,
) -> Result<T, crate::wire::unmarshal::Error>
where
F: FnOnce(&mut Self) -> Result<T, crate::wire::unmarshal::Error>,
{
if count > self.sigs_left() {
return Err(crate::wire::unmarshal::Error::EndOfMessage);
}
let start_sig_idx = self.sig_idx;
let start_buf_idx = self.buf_idx;
match get_calls(self) {
Ok(ret) => Ok(ret),
Err(err) => {
self.sig_idx = start_sig_idx;
self.buf_idx = start_buf_idx;
Err(err)
}
}
}
pub fn get2<T1, T2>(&mut self) -> Result<(T1, T2), crate::wire::unmarshal::Error>
where
T1: Unmarshal<'body, 'fds>,
T2: Unmarshal<'body, 'fds>,
{
let get_calls = |parser: &mut Self| {
let ret1 = parser.get()?;
let ret2 = parser.get()?;
Ok((ret1, ret2))
};
self.get_mult_helper(2, get_calls)
}
pub fn get3<T1, T2, T3>(&mut self) -> Result<(T1, T2, T3), crate::wire::unmarshal::Error>
where
T1: Unmarshal<'body, 'fds>,
T2: Unmarshal<'body, 'fds>,
T3: Unmarshal<'body, 'fds>,
{
let get_calls = |parser: &mut Self| {
let ret1 = parser.get()?;
let ret2 = parser.get()?;
let ret3 = parser.get()?;
Ok((ret1, ret2, ret3))
};
self.get_mult_helper(3, get_calls)
}
pub fn get4<T1, T2, T3, T4>(
&mut self,
) -> Result<(T1, T2, T3, T4), crate::wire::unmarshal::Error>
where
T1: Unmarshal<'body, 'fds>,
T2: Unmarshal<'body, 'fds>,
T3: Unmarshal<'body, 'fds>,
T4: Unmarshal<'body, 'fds>,
{
let get_calls = |parser: &mut Self| {
let ret1 = parser.get()?;
let ret2 = parser.get()?;
let ret3 = parser.get()?;
let ret4 = parser.get()?;
Ok((ret1, ret2, ret3, ret4))
};
self.get_mult_helper(4, get_calls)
}
pub fn get5<T1, T2, T3, T4, T5>(
&mut self,
) -> Result<(T1, T2, T3, T4, T5), crate::wire::unmarshal::Error>
where
T1: Unmarshal<'body, 'fds>,
T2: Unmarshal<'body, 'fds>,
T3: Unmarshal<'body, 'fds>,
T4: Unmarshal<'body, 'fds>,
T5: Unmarshal<'body, 'fds>,
{
let get_calls = |parser: &mut Self| {
let ret1 = parser.get()?;
let ret2 = parser.get()?;
let ret3 = parser.get()?;
let ret4 = parser.get()?;
let ret5 = parser.get()?;
Ok((ret1, ret2, ret3, ret4, ret5))
};
self.get_mult_helper(5, get_calls)
}
pub fn get_param(&mut self) -> Result<crate::params::Param, crate::wire::unmarshal::Error> {
if let Some(sig_str) = self.get_next_sig() {
let mut ctx = UnmarshalContext {
byteorder: self.body.byteorder,
buf: &self.body.buf,
offset: self.buf_idx,
fds: &self.body.raw_fds,
};
let sig = &crate::signature::Type::parse_description(sig_str).unwrap()[0];
match crate::wire::unmarshal::container::unmarshal_with_sig(sig, &mut ctx) {
Ok((bytes, res)) => {
self.buf_idx += bytes;
self.sig_idx += sig_str.len();
Ok(res)
}
Err(e) => Err(e),
}
} else {
Err(crate::wire::unmarshal::Error::EndOfMessage)
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn parser_get() {
let mut sig = super::MessageBuilder::new()
.signal("io.killingspark", "Signal", "/io/killingspark/Signaler")
.build();
sig.body.push_param3(100u32, 200i32, "ABCDEFGH").unwrap();
let mut parser = sig.body.parser();
assert_eq!(parser.get(), Ok(100u32));
assert_eq!(parser.get(), Ok(200i32));
assert_eq!(parser.get(), Ok("ABCDEFGH"));
assert_eq!(
parser.get::<String>(),
Err(crate::wire::unmarshal::Error::EndOfMessage)
);
let mut parser = sig.body.parser();
assert_eq!(parser.get2(), Ok((100u32, 200i32)));
assert_eq!(parser.get(), Ok("ABCDEFGH"));
assert_eq!(
parser.get::<String>(),
Err(crate::wire::unmarshal::Error::EndOfMessage)
);
let mut parser = sig.body.parser();
assert_eq!(parser.get3(), Ok((100u32, 200i32, "ABCDEFGH")));
assert_eq!(
parser.get::<String>(),
Err(crate::wire::unmarshal::Error::EndOfMessage)
);
let mut sig = super::MessageBuilder::new()
.signal("io.killingspark", "Signal", "/io/killingspark/Signaler")
.build();
sig.body.push_param((100u32, 200i32, "ABCDEFGH")).unwrap();
sig.body.push_param((100u32, 200i32, "ABCDEFGH")).unwrap();
sig.body.push_param((100u32, 200i32, "ABCDEFGH")).unwrap();
let mut parser = sig.body.parser();
assert!(parser.get::<(u32, i32, &str)>().is_ok());
assert!(parser.get2::<(u32, i32, &str), (u32, i32, &str)>().is_ok());
}
}