zbus 6.2.0

API for D-Bus communication and its wire format
Documentation
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
use crate::{
    Error, MatchRule, ObjectPath, Result, Str,
    match_rule::PathSpec,
    message::Type,
    names::{BusName, InterfaceName, MemberName, UniqueName},
};

const MAX_ARGS: u8 = 64;

/// Builder for [`MatchRule`].
///
/// This is created by [`MatchRule::builder`]. Each setter takes the value it is given, whether
/// that's an already parsed name or a string that still needs parsing, and converts it right
/// away, but it never fails: the first error a setter hits is recorded — a later call doesn't
/// clear it — and reported by [`Builder::build`], so a chain of setters never needs a `?` in
/// between.
#[derive(Debug)]
#[must_use]
pub struct Builder<'m> {
    rule: MatchRule<'m>,
    error: Option<Error>,
}

impl<'m> Builder<'m> {
    /// Build the `MatchRule`.
    ///
    /// # Errors
    ///
    /// The first error recorded by a setter.
    pub fn build(self) -> Result<MatchRule<'m>> {
        match self.error {
            Some(error) => Err(error),
            None => Ok(self.rule),
        }
    }

    /// Set the sender.
    ///
    /// An invalid sender is reported by [`Builder::build`].
    pub fn sender<B>(mut self, sender: B) -> Self
    where
        B: TryInto<BusName<'m>>,
        B::Error: Into<Error>,
    {
        match sender.try_into() {
            Ok(sender) => self.rule.sender = Some(sender),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Set the message type.
    pub fn msg_type(mut self, msg_type: Type) -> Self {
        self.rule.msg_type = Some(msg_type);

        self
    }

    /// Set the interface.
    ///
    /// An invalid interface name is reported by [`Builder::build`].
    pub fn interface<I>(mut self, interface: I) -> Self
    where
        I: TryInto<InterfaceName<'m>>,
        I::Error: Into<Error>,
    {
        match interface.try_into() {
            Ok(interface) => self.rule.interface = Some(interface),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Set the member.
    ///
    /// An invalid member name is reported by [`Builder::build`].
    pub fn member<M>(mut self, member: M) -> Self
    where
        M: TryInto<MemberName<'m>>,
        M::Error: Into<Error>,
    {
        match member.try_into() {
            Ok(member) => self.rule.member = Some(member),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Set the path.
    ///
    /// Note: Since both a path and a path namespace are not allowed to appear in a match rule at
    /// the same time, this overrides any path namespace previously set.
    ///
    /// An invalid path is reported by [`Builder::build`].
    pub fn path<P>(mut self, path: P) -> Self
    where
        P: TryInto<ObjectPath<'m>>,
        P::Error: Into<Error>,
    {
        match path.try_into() {
            Ok(path) => self.rule.path_spec = Some(PathSpec::Path(path)),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Set the path namespace.
    ///
    /// Note: Since both a path and a path namespace are not allowed to appear in a match rule at
    /// the same time, this overrides any path previously set.
    ///
    /// An invalid path namespace is reported by [`Builder::build`].
    pub fn path_namespace<P>(mut self, path_namespace: P) -> Self
    where
        P: TryInto<ObjectPath<'m>>,
        P::Error: Into<Error>,
    {
        match path_namespace.try_into() {
            Ok(namespace) => self.rule.path_spec = Some(PathSpec::PathNamespace(namespace)),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Set the destination.
    ///
    /// An invalid destination is reported by [`Builder::build`].
    pub fn destination<B>(mut self, destination: B) -> Self
    where
        B: TryInto<UniqueName<'m>>,
        B::Error: Into<Error>,
    {
        match destination.try_into() {
            Ok(destination) => self.rule.destination = Some(destination),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Append an argument.
    ///
    /// Use this in instead of [`Builder::arg`] if you want to sequentially add args.
    ///
    /// An attempt to add the 65th argument is reported by [`Builder::build`].
    pub fn add_arg<S>(self, arg: S) -> Self
    where
        S: Into<Str<'m>>,
    {
        let idx = self.rule.args.len() as u8;

        self.arg(idx, arg)
    }

    /// Add an argument of a specified index.
    ///
    /// This replaces any argument previously added at `idx`.
    ///
    /// An `idx` of 64 or greater is reported by [`Builder::build`].
    pub fn arg<S>(mut self, idx: u8, arg: S) -> Self
    where
        S: Into<Str<'m>>,
    {
        if idx >= MAX_ARGS {
            self.record(Error::InvalidMatchRule);

            return self;
        }
        insert_indexed(&mut self.rule.args, idx, arg.into());

        self
    }

    /// Append a path argument.
    ///
    /// Use this in instead of [`Builder::arg_path`] if you want to sequentially add args.
    ///
    /// An invalid path, or an attempt to add the 65th path argument, is reported by
    /// [`Builder::build`].
    pub fn add_arg_path<P>(self, arg_path: P) -> Self
    where
        P: TryInto<ObjectPath<'m>>,
        P::Error: Into<Error>,
    {
        let idx = self.rule.arg_paths.len() as u8;

        self.arg_path(idx, arg_path)
    }

    /// Add a path argument of a specified index.
    ///
    /// This replaces any path argument previously added at `idx`.
    ///
    /// An invalid path, or an `idx` of 64 or greater, is reported by [`Builder::build`].
    pub fn arg_path<P>(mut self, idx: u8, arg_path: P) -> Self
    where
        P: TryInto<ObjectPath<'m>>,
        P::Error: Into<Error>,
    {
        if idx >= MAX_ARGS {
            self.record(Error::InvalidMatchRule);

            return self;
        }
        match arg_path.try_into() {
            Ok(arg_path) => insert_indexed(&mut self.rule.arg_paths, idx, arg_path),
            Err(e) => self.record(e.into()),
        }

        self
    }

    /// Set 0th argument's namespace.
    ///
    /// The namespace must be a valid bus name or a valid element of a bus name. For more
    /// information, see [the spec](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus).
    ///
    /// An invalid namespace is reported by [`Builder::build`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use zbus::MatchRule;
    /// // Valid namespaces
    /// MatchRule::builder().arg0ns("org.mpris.MediaPlayer2").build().unwrap();
    /// MatchRule::builder().arg0ns("org").build().unwrap();
    /// MatchRule::builder().arg0ns(":org").build().unwrap();
    /// MatchRule::builder().arg0ns(":1org").build().unwrap();
    ///
    /// // Invalid namespaces
    /// MatchRule::builder().arg0ns("org.").build().unwrap_err();
    /// MatchRule::builder().arg0ns(".org").build().unwrap_err();
    /// MatchRule::builder().arg0ns("1org").build().unwrap_err();
    /// MatchRule::builder().arg0ns(".").build().unwrap_err();
    /// MatchRule::builder().arg0ns("org..freedesktop").build().unwrap_err();
    /// ````
    pub fn arg0ns<S>(mut self, namespace: S) -> Self
    where
        S: Into<Str<'m>>,
    {
        match validate_arg0ns(namespace.into()) {
            Ok(namespace) => self.rule.arg0ns = Some(namespace),
            Err(e) => self.record(e),
        }

        self
    }

    /// Set whether the rule has `eavesdrop='true'`, which it doesn't by default.
    ///
    /// See [`MatchRule::eavesdrop`] for what that means.
    pub fn eavesdrop(mut self, eavesdrop: bool) -> Self {
        self.rule.eavesdrop = eavesdrop;

        self
    }

    /// Create a builder for `MatchRule`.
    pub(crate) fn new() -> Self {
        Self {
            rule: MatchRule {
                msg_type: None,
                sender: None,
                interface: None,
                member: None,
                path_spec: None,
                destination: None,
                args: Vec::with_capacity(MAX_ARGS as usize),
                arg_paths: Vec::with_capacity(MAX_ARGS as usize),
                arg0ns: None,
                eavesdrop: false,
            },
            error: None,
        }
    }

    /// Record `error`, unless an earlier setter already recorded one.
    fn record(&mut self, error: Error) {
        if self.error.is_none() {
            self.error = Some(error);
        }
    }
}

/// Add `value` at `idx`, replacing the value already recorded at that index, if any.
fn insert_indexed<T>(entries: &mut Vec<(u8, T)>, idx: u8, value: T) {
    match entries.binary_search_by(|(i, _)| i.cmp(&idx)) {
        Ok(i) => entries[i] = (idx, value),
        Err(i) => entries.insert(i, (idx, value)),
    }
}

/// Check that `namespace` is a valid bus name or a valid element of a bus name.
pub(crate) fn validate_arg0ns(namespace: Str<'_>) -> Result<Str<'_>> {
    // Rules: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus
    // minus the requirement to have more than one element.

    if namespace.is_empty() || namespace.len() > 255 {
        return Err(Error::InvalidMatchRule);
    }

    let (is_unique, namespace_str) = match namespace.strip_prefix(':') {
        Some(s) => (true, s),
        None => (false, namespace.as_str()),
    };

    let valid_first_char = |s: &str| match s.chars().next() {
        None | Some('.') => false,
        Some('0'..='9') if !is_unique => false,
        _ => true,
    };

    if !valid_first_char(namespace_str)
        || !namespace_str.split('.').all(valid_first_char)
        || !namespace_str
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
    {
        return Err(Error::InvalidMatchRule);
    }

    Ok(namespace)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Message, OwnedMatchRule, names::OwnedBusName};
    use test_log::test;

    #[test]
    fn strings_are_converted() {
        let rule = MatchRule::builder()
            .msg_type(Type::Signal)
            .sender("org.freedesktop.DBus")
            .interface("org.freedesktop.DBus.Properties")
            .member("PropertiesChanged")
            .path("/org/zbus")
            .destination(":1.11")
            .add_arg("org.zbus")
            .add_arg_path("/org/zbus/Arg")
            .arg0ns("org.zbus")
            .build()
            .unwrap();

        assert_eq!(
            rule.to_string(),
            "type='signal',\
             sender='org.freedesktop.DBus',\
             interface='org.freedesktop.DBus.Properties',\
             member='PropertiesChanged',\
             destination=':1.11',\
             path='/org/zbus',\
             arg0='org.zbus',\
             arg0path='/org/zbus/Arg',\
             arg0namespace='org.zbus'",
        );
    }

    #[test]
    fn invalid_string_is_reported_by_build() {
        let err = MatchRule::builder()
            .sender("not a bus name")
            .member("Whatever")
            .build()
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            BusName::try_from("not a bus name").unwrap_err().to_string(),
        );
    }

    #[test]
    fn typed_values_need_no_error_handling() {
        let sender = BusName::try_from("org.zbus.Sender").unwrap();
        let path = ObjectPath::try_from("/org/zbus").unwrap();
        let rule = MatchRule::builder()
            .sender(&sender)
            .path(path.clone())
            .build()
            .unwrap();

        assert_eq!(rule.sender(), Some(&sender));
        assert_eq!(rule.path_spec(), Some(&PathSpec::Path(path)));

        let rule = MatchRule::builder()
            .sender(OwnedBusName::from(sender.clone()))
            .build()
            .unwrap();

        assert_eq!(rule.sender(), Some(&sender));
    }

    #[test]
    fn a_later_valid_call_keeps_the_first_error() {
        // Setting the field again, even to a valid value, doesn't clear the error it recorded.
        let err = MatchRule::builder()
            .path("bad")
            .path("/good")
            .build()
            .unwrap_err();

        assert_eq!(err, ObjectPath::try_from("bad").unwrap_err());

        let mut builder = MatchRule::builder();
        for i in 0..MAX_ARGS {
            builder = builder.add_arg(i.to_string());
        }

        // The 65th argument doesn't fit and the later valid argument doesn't undo that.
        let err = builder
            .add_arg("one too many")
            .arg(0, "replaced")
            .build()
            .unwrap_err();

        assert_eq!(err, Error::InvalidMatchRule);
    }

    #[test]
    fn rule_string_rejects_an_invalid_namespace_even_if_repeated() {
        // The parser validates each component itself, so a later valid `arg0namespace` must not
        // hide an earlier invalid one.
        let err = MatchRule::try_from("arg0namespace='org.',arg0namespace='org'").unwrap_err();

        assert_eq!(err, Error::InvalidMatchRule);
        MatchRule::try_from("arg0namespace='org'").unwrap();
    }

    #[test]
    fn rule_string_follows_the_quoting_of_the_specification() {
        // The two examples of the specification, which have the same arguments.
        for rule in [
            r"arg0=''\''',arg1='\',arg2=',',arg3='\\'",
            r"arg0=\',arg1=\,arg2=',',arg3=\\",
        ] {
            let parsed = MatchRule::try_from(rule).unwrap();

            assert_eq!(
                args(&parsed),
                [(0, "'"), (1, "\\"), (2, ","), (3, "\\\\")],
                "{rule}"
            );
        }
    }

    #[test]
    fn rule_string_values_need_no_quotes() {
        assert_eq!(
            MatchRule::try_from("type=signal").unwrap(),
            MatchRule::try_from("type='signal'").unwrap(),
        );

        let unquoted =
            MatchRule::try_from("type=signal,sender=org.zbus,member=Foo,arg0=bar,arg1=").unwrap();
        let quoted =
            MatchRule::try_from("type='signal',sender='org.zbus',member='Foo',arg0='bar',arg1=''")
                .unwrap();

        assert_eq!(unquoted, quoted);
        assert_eq!(unquoted.msg_type(), Some(Type::Signal));
        assert_eq!(args(&unquoted), [(0, "bar"), (1, "")]);
    }

    #[test]
    fn rule_string_keeps_a_quoted_comma_in_the_value() {
        let rule =
            MatchRule::try_from("type='signal',arg0='a,b',arg1=c,arg2=',',arg3='a=b,c'").unwrap();

        assert_eq!(rule.msg_type(), Some(Type::Signal));
        assert_eq!(args(&rule), [(0, "a,b"), (1, "c"), (2, ","), (3, "a=b,c")]);
    }

    #[test]
    fn rule_string_concatenates_quoted_and_unquoted_text() {
        // The quotes can start and end anywhere in a value, and a value can have several of them.
        let rule = MatchRule::try_from("arg0=a'b,c'd,arg1='a'b'c',arg2=''x'',arg3=a''b").unwrap();

        assert_eq!(args(&rule), [(0, "ab,cd"), (1, "abc"), (2, "x"), (3, "ab")]);
    }

    #[test]
    fn rule_string_escapes_an_apostrophe_outside_quotes() {
        let rule = MatchRule::try_from(r"arg0=\',arg1=a\'b,arg2=\'\',arg3='a'\''b'").unwrap();

        assert_eq!(args(&rule), [(0, "'"), (1, "a'b"), (2, "''"), (3, "a'b")]);
    }

    #[test]
    fn rule_string_backslash_escapes_only_an_apostrophe_outside_quotes() {
        // Outside quotes, a backslash stands for itself unless an apostrophe follows it. So it
        // doesn't escape a comma, nor another backslash, and it can end the string.
        let rule = MatchRule::try_from(r"arg0=a\b,arg1=\,arg2=\\',arg3=c\").unwrap();

        assert_eq!(
            args(&rule),
            [(0, "a\\b"), (1, "\\"), (2, "\\'"), (3, "c\\")]
        );

        // Within quotes, it always does.
        let rule = MatchRule::try_from(r"arg0='\',arg1='a\b\\'").unwrap();

        assert_eq!(args(&rule), [(0, "\\"), (1, "a\\b\\\\")]);
    }

    #[test]
    fn rule_string_rejects_an_unterminated_quote() {
        for rule in [
            "arg0='foo",
            "arg0='",
            "arg0='foo,arg1=bar",
            "arg0=foo'",
            "arg0='a'b'",
            r"arg0='\''",
        ] {
            assert_invalid(rule);
        }
    }

    #[test]
    fn rule_string_skips_whitespace_around_keys_but_not_in_values() {
        let rule = MatchRule::try_from(" type =signal,\targ0\n=a b ,  arg1 =' c', ").unwrap();

        assert_eq!(rule.msg_type(), Some(Type::Signal));
        assert_eq!(args(&rule), [(0, "a b "), (1, " c")]);

        for rule in [
            "type= signal",
            "type=signal ",
            "type='signal' ",
            "type=signal ,member=Foo",
        ] {
            assert_invalid(rule);
        }
    }

    #[test]
    fn rule_string_accepts_an_empty_value() {
        for rule in ["arg0=''", "arg0=", "arg0=,", "arg0='',", "arg0=''''"] {
            let rule = MatchRule::try_from(rule).unwrap();

            assert_eq!(args(&rule), [(0, "")]);
        }

        let rule = MatchRule::try_from("arg0=,arg1=b").unwrap();

        assert_eq!(args(&rule), [(0, ""), (1, "b")]);

        // A name is never empty, though.
        MatchRule::try_from("member=").unwrap_err();
        MatchRule::try_from("member=''").unwrap_err();
    }

    #[test]
    fn rule_string_accepts_a_trailing_comma_only() {
        let expected = MatchRule::try_from("type=signal").unwrap();

        assert_eq!(MatchRule::try_from("type=signal,").unwrap(), expected);
        assert_eq!(MatchRule::try_from("type=signal, ").unwrap(), expected);

        for rule in [
            ",",
            ",type=signal",
            "type=signal,,member=Foo",
            "type=signal,,",
        ] {
            assert_invalid(rule);
        }
    }

    #[test]
    fn rule_string_can_be_empty() {
        let rule = MatchRule::builder().build().unwrap();

        assert_eq!(rule.to_string(), "");
        assert_eq!(MatchRule::try_from("").unwrap(), rule);
        assert_eq!(MatchRule::try_from(" \t\r\n").unwrap(), rule);
    }

    #[test]
    fn rule_string_rejects_a_pair_without_a_key_or_a_value() {
        for rule in [
            "type",
            "type,member=Foo",
            "type=signal,member",
            "type=signal,member,",
            "=signal",
            "='signal'",
            "unknown=signal",
            // A comma before the `=` ends a pair without a value, even when the key would take the
            // next pair in.
            "arg0path,path='/foo'",
            "arg0path,,path='/foo'",
        ] {
            assert_invalid(rule);
        }
    }

    #[test]
    fn rule_string_reports_the_component_at_fault() {
        // The error is the same, whether the value is borrowed from the rule string or a copy.
        let expected = MemberName::try_from("not a member")
            .unwrap_err()
            .to_string();
        for rule in [
            "member=not a member",
            "member='not a member'",
            "member='not'' a member'",
        ] {
            let err = MatchRule::try_from(rule).unwrap_err();

            assert_eq!(err.to_string(), expected, "{rule}");
        }

        assert_invalid("type=bogus");
    }

    #[test]
    fn rule_string_values_are_borrowed_unless_they_need_unquoting() {
        let text = "sender=org.zbus,path='/org/zbus',arg0=foo,arg1='bar',arg2=''baz'',\
                    arg3=a'b'c,arg4=d\\'e";
        let in_text = |s: &str| text.as_bytes().as_ptr_range().contains(&s.as_ptr());
        let rule = MatchRule::try_from(text).unwrap();

        assert!(in_text(rule.sender().unwrap().as_str()));
        let Some(PathSpec::Path(path)) = rule.path_spec() else {
            panic!("expected a path, got {:?}", rule.path_spec());
        };
        assert!(in_text(path.as_str()));
        let values = args(&rule);
        assert_eq!(values.len(), 5);
        // Neither quotes around the whole value nor empty quoted text next to it need a copy.
        assert!(in_text(values[0].1) && in_text(values[1].1) && in_text(values[2].1));
        // Concatenating text, or escaping an apostrophe in it, does.
        assert_eq!(values[3], (3, "abc"));
        assert_eq!(values[4], (4, "d'e"));
        assert!(!in_text(values[3].1) && !in_text(values[4].1));
    }

    #[test]
    fn display_escapes_apostrophes() {
        let rule = MatchRule::builder()
            .add_arg("it's")
            .add_arg("'")
            .add_arg("''")
            .add_arg("no apostrophe")
            .build()
            .unwrap();

        assert_eq!(
            rule.to_string(),
            r"arg0='it'\''s',arg1=''\''',arg2=''\'''\''',arg3='no apostrophe'",
        );
    }

    #[test]
    fn display_round_trips() {
        let values = [
            "",
            "'",
            "''",
            "'a'",
            "it's",
            "a,b",
            ",",
            "\\",
            "\\\\",
            "\\'",
            "'\\",
            "a\\'b",
            "\\,'",
            " a ",
            "a=b,c=d",
            "\"quoted\"",
            "é'日本",
            "x'y,z\\w'",
        ];

        // Each value on its own, next to other components.
        for value in values {
            let rule = MatchRule::builder()
                .msg_type(Type::Signal)
                .sender("org.zbus.Sender")
                .add_arg(value)
                .arg_path(1, "/org/zbus")
                .build()
                .unwrap();
            let text = rule.to_string();
            let parsed = MatchRule::try_from(text.as_str()).unwrap();

            assert_eq!(parsed, rule, "{value:?}");
        }

        // All of them in one rule, along with every other kind of component.
        let mut builder = MatchRule::builder()
            .msg_type(Type::Signal)
            .sender("org.freedesktop.DBus")
            .interface("org.freedesktop.DBus.Properties")
            .member("PropertiesChanged")
            .path_namespace("/org/zbus")
            .destination(":1.11")
            .arg_path(2, "/org/zbus/Arg")
            .arg0ns("org.zbus");
        for value in values {
            builder = builder.add_arg(value);
        }
        let rule = builder.build().unwrap();
        let text = rule.to_string();
        let parsed = MatchRule::try_from(text.as_str()).unwrap();

        assert_eq!(parsed, rule);
    }

    #[test]
    fn eavesdrop_is_part_of_the_rule() {
        let without = MatchRule::builder().msg_type(Type::Signal).build().unwrap();
        let with = MatchRule::builder()
            .msg_type(Type::Signal)
            .eavesdrop(true)
            .build()
            .unwrap();

        assert!(!without.eavesdrop());
        assert!(with.eavesdrop());
        assert_ne!(with, without);
        assert!(with.to_owned().eavesdrop());
        assert!(with.clone().into_owned().eavesdrop());
        assert!(OwnedMatchRule::from(with).eavesdrop());
    }

    #[test]
    fn rule_string_parses_eavesdrop() {
        for (rule, eavesdrop) in [
            ("eavesdrop=true", true),
            ("eavesdrop='true'", true),
            ("eavesdrop=false", false),
            ("type=signal", false),
            // A repeated key keeps its last value, so a user can override the one a tool added.
            ("eavesdrop=true,type=signal,eavesdrop=false", false),
        ] {
            let parsed = MatchRule::try_from(rule).unwrap();

            assert_eq!(parsed.eavesdrop(), eavesdrop, "{rule}");
        }

        for rule in [
            "eavesdrop=maybe",
            "eavesdrop=",
            "eavesdrop=TRUE",
            "eavesdrop=true ",
        ] {
            assert_invalid(rule);
        }
    }

    #[test]
    fn display_writes_eavesdrop_only_if_set() {
        let rule = |eavesdrop| {
            MatchRule::builder()
                .msg_type(Type::Signal)
                .add_arg("a")
                .eavesdrop(eavesdrop)
                .build()
                .unwrap()
        };

        assert_eq!(
            rule(true).to_string(),
            "type='signal',arg0='a',eavesdrop='true'"
        );
        assert_eq!(rule(false).to_string(), "type='signal',arg0='a'");
        for eavesdrop in [true, false] {
            let text = rule(eavesdrop).to_string();

            assert_eq!(MatchRule::try_from(text.as_str()).unwrap(), rule(eavesdrop));
        }
    }

    #[test]
    fn matches_ignores_eavesdrop() {
        let rule = |eavesdrop| {
            MatchRule::builder()
                .msg_type(Type::Signal)
                .member("Event")
                .eavesdrop(eavesdrop)
                .build()
                .unwrap()
        };
        let signal = |member| Message::signal("/org/zbus", "org.zbus.Interface", member);
        let broadcast = signal("Event").sender(":1.42").build(&()).unwrap();
        // Whether a connection gets a message for another one is for the bus to decide.
        let unicast = signal("Event")
            .sender(":1.42")
            .destination(":1.43")
            .build(&())
            .unwrap();
        let other = signal("Other").sender(":1.42").build(&()).unwrap();

        for (msg, matched) in [(&broadcast, true), (&unicast, true), (&other, false)] {
            for eavesdrop in [true, false] {
                assert_eq!(rule(eavesdrop).matches(msg).unwrap(), matched, "{msg}");
            }
        }
    }

    #[test]
    fn owned_rule_deserializes_from_a_rule_string() {
        use crate::wire::{LE, serialized::Context, to_bytes};

        let ctxt = Context::new(LE, 0);
        let rule = r"type='signal',arg0='it'\''s'";
        let encoded = to_bytes(ctxt, &rule).unwrap();
        let owned: OwnedMatchRule = encoded.deserialize().unwrap().0;

        assert_eq!(owned, MatchRule::try_from(rule).unwrap());

        let encoded = to_bytes(ctxt, &"type='bogus'").unwrap();
        encoded.deserialize::<OwnedMatchRule>().unwrap_err();
    }

    /// Assert that `rule` is not a valid rule string, whatever the reason.
    fn assert_invalid(rule: &str) {
        assert_eq!(
            MatchRule::try_from(rule).unwrap_err(),
            Error::InvalidMatchRule,
            "{rule}",
        );
    }

    /// The arguments of `rule`, along with their indices.
    fn args<'a>(rule: &'a MatchRule<'_>) -> Vec<(u8, &'a str)> {
        rule.args()
            .iter()
            .map(|(idx, arg)| (*idx, arg.as_str()))
            .collect()
    }
}