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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Extensions for route rules FIDL.

use std::fmt::Debug;
use std::ops::RangeInclusive;

use async_utils::{fold, stream};
use fidl::endpoints::{DiscoverableProtocolMarker, ProtocolMarker, Proxy as _};
use fidl_fuchsia_net_ext::{IntoExt as _, TryIntoExt as _};
use futures::future::Either;
use futures::{Stream, TryStreamExt as _};
use net_types::ip::{GenericOverIp, Ip, Ipv4, Ipv6, Subnet};
use thiserror::Error;
use {
    fidl_fuchsia_net as fnet, fidl_fuchsia_net_routes as fnet_routes,
    fidl_fuchsia_net_routes_admin as fnet_routes_admin,
};

use crate::{impl_responder, FidlRouteIpExt, Responder, SliceResponder, WatcherCreationError};

/// Observation extension for the rules part of `fuchsia.net.routes` FIDL API.
pub trait FidlRuleIpExt: Ip {
    /// The "rules watcher" protocol to use for this IP version.
    type RuleWatcherMarker: ProtocolMarker<RequestStream = Self::RuleWatcherRequestStream>;
    /// The "rules watcher" request stream.
    type RuleWatcherRequestStream: fidl::endpoints::RequestStream<Ok: Send, ControlHandle: Send>;
    /// The rule event to be watched.
    type RuleEvent: From<RuleEvent<Self>>
        + TryInto<RuleEvent<Self>, Error = RuleFidlConversionError>
        + Unpin;
    /// The responder to the watch request.
    type RuleWatcherWatchResponder: SliceResponder<Self::RuleEvent>;

    /// Turns a FIDL rule watcher request into the extension type.
    fn into_rule_watcher_request(
        request: fidl::endpoints::Request<Self::RuleWatcherMarker>,
    ) -> RuleWatcherRequest<Self>;
}

impl_responder!(fnet_routes::RuleWatcherV4WatchResponder, &[fnet_routes::RuleEventV4]);
impl_responder!(fnet_routes::RuleWatcherV6WatchResponder, &[fnet_routes::RuleEventV6]);

impl FidlRuleIpExt for Ipv4 {
    type RuleWatcherMarker = fnet_routes::RuleWatcherV4Marker;
    type RuleWatcherRequestStream = fnet_routes::RuleWatcherV4RequestStream;
    type RuleEvent = fnet_routes::RuleEventV4;
    type RuleWatcherWatchResponder = fnet_routes::RuleWatcherV4WatchResponder;

    fn into_rule_watcher_request(
        request: fidl::endpoints::Request<Self::RuleWatcherMarker>,
    ) -> RuleWatcherRequest<Self> {
        RuleWatcherRequest::from(request)
    }
}

impl FidlRuleIpExt for Ipv6 {
    type RuleWatcherMarker = fnet_routes::RuleWatcherV6Marker;
    type RuleWatcherRequestStream = fnet_routes::RuleWatcherV6RequestStream;
    type RuleEvent = fnet_routes::RuleEventV6;
    type RuleWatcherWatchResponder = fnet_routes::RuleWatcherV6WatchResponder;

    fn into_rule_watcher_request(
        request: fidl::endpoints::Request<Self::RuleWatcherMarker>,
    ) -> RuleWatcherRequest<Self> {
        RuleWatcherRequest::from(request)
    }
}

/// The request for the rules watchers.
pub enum RuleWatcherRequest<I: FidlRuleIpExt> {
    /// Hanging-Get style API for observing routing rule changes.
    Watch {
        /// Responder for the events.
        responder: I::RuleWatcherWatchResponder,
    },
}

impl From<fnet_routes::RuleWatcherV4Request> for RuleWatcherRequest<Ipv4> {
    fn from(req: fnet_routes::RuleWatcherV4Request) -> Self {
        match req {
            fnet_routes::RuleWatcherV4Request::Watch { responder } => {
                RuleWatcherRequest::Watch { responder }
            }
        }
    }
}

impl From<fnet_routes::RuleWatcherV6Request> for RuleWatcherRequest<Ipv6> {
    fn from(req: fnet_routes::RuleWatcherV6Request) -> Self {
        match req {
            fnet_routes::RuleWatcherV6Request::Watch { responder } => {
                RuleWatcherRequest::Watch { responder }
            }
        }
    }
}

/// An installed IPv4 routing rule.
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct InstalledRule<I: Ip> {
    /// Rule sets are ordered by the rule set priority, rule sets are disjoint
    /// and don’t have interleaving rules among them.
    pub priority: RuleSetPriority,
    /// Rules within a rule set are locally ordered, together with the rule set
    /// priority, this defines a global order for all installed rules.
    pub index: RuleIndex,
    /// The matcher part of the rule, the rule is a no-op if the matcher does
    /// not match the packet.
    pub matcher: RuleMatcher<I>,
    /// The action part of the rule that describes what to do if the matcher
    /// matches the packet.
    pub action: RuleAction,
}

impl TryFrom<fnet_routes::InstalledRuleV4> for InstalledRule<Ipv4> {
    type Error = RuleFidlConversionError;
    fn try_from(
        fnet_routes::InstalledRuleV4 {
        rule_set_priority,
        rule_index,
        matcher,
        action,
    }: fnet_routes::InstalledRuleV4,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            priority: rule_set_priority.into(),
            index: rule_index.into(),
            matcher: matcher.try_into()?,
            action: action.into(),
        })
    }
}

impl TryFrom<fnet_routes::InstalledRuleV6> for InstalledRule<Ipv6> {
    type Error = RuleFidlConversionError;
    fn try_from(
        fnet_routes::InstalledRuleV6 {
        rule_set_priority,
        rule_index,
        matcher,
        action,
    }: fnet_routes::InstalledRuleV6,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            priority: rule_set_priority.into(),
            index: rule_index.into(),
            matcher: matcher.try_into()?,
            action: action.into(),
        })
    }
}

impl From<InstalledRule<Ipv4>> for fnet_routes::InstalledRuleV4 {
    fn from(InstalledRule { priority, index, matcher, action }: InstalledRule<Ipv4>) -> Self {
        Self {
            rule_set_priority: priority.into(),
            rule_index: index.into(),
            matcher: matcher.into(),
            action: action.into(),
        }
    }
}

impl From<InstalledRule<Ipv6>> for fnet_routes::InstalledRuleV6 {
    fn from(InstalledRule { priority, index, matcher, action }: InstalledRule<Ipv6>) -> Self {
        Self {
            rule_set_priority: priority.into(),
            rule_index: index.into(),
            matcher: matcher.into(),
            action: action.into(),
        }
    }
}

/// A rules watcher event.
#[derive(Debug, Clone)]
pub enum RuleEvent<I: Ip> {
    /// A rule that already existed when watching started.
    Existing(InstalledRule<I>),
    /// Sentinel value indicating no more `existing` events will be
    /// received.
    Idle,
    /// A rule that was added while watching.
    Added(InstalledRule<I>),
    /// A rule that was removed while watching.
    Removed(InstalledRule<I>),
}

impl TryFrom<fnet_routes::RuleEventV4> for RuleEvent<Ipv4> {
    type Error = RuleFidlConversionError;
    fn try_from(event: fnet_routes::RuleEventV4) -> Result<Self, Self::Error> {
        match event {
            fnet_routes::RuleEventV4::Existing(rule) => Ok(RuleEvent::Existing(rule.try_into()?)),
            fnet_routes::RuleEventV4::Idle(fnet_routes::Empty) => Ok(RuleEvent::Idle),
            fnet_routes::RuleEventV4::Added(rule) => Ok(RuleEvent::Added(rule.try_into()?)),
            fnet_routes::RuleEventV4::Removed(rule) => Ok(RuleEvent::Removed(rule.try_into()?)),
            fnet_routes::RuleEventV4::__SourceBreaking { unknown_ordinal } => {
                Err(RuleFidlConversionError::UnknownOrdinal {
                    name: "RuleEventV4",
                    unknown_ordinal,
                })
            }
        }
    }
}

impl TryFrom<fnet_routes::RuleEventV6> for RuleEvent<Ipv6> {
    type Error = RuleFidlConversionError;
    fn try_from(event: fnet_routes::RuleEventV6) -> Result<Self, Self::Error> {
        match event {
            fnet_routes::RuleEventV6::Existing(rule) => Ok(RuleEvent::Existing(rule.try_into()?)),
            fnet_routes::RuleEventV6::Idle(fnet_routes::Empty) => Ok(RuleEvent::Idle),
            fnet_routes::RuleEventV6::Added(rule) => Ok(RuleEvent::Added(rule.try_into()?)),
            fnet_routes::RuleEventV6::Removed(rule) => Ok(RuleEvent::Removed(rule.try_into()?)),
            fnet_routes::RuleEventV6::__SourceBreaking { unknown_ordinal } => {
                Err(RuleFidlConversionError::UnknownOrdinal {
                    name: "RuleEventV6",
                    unknown_ordinal,
                })
            }
        }
    }
}

impl From<RuleEvent<Ipv4>> for fnet_routes::RuleEventV4 {
    fn from(event: RuleEvent<Ipv4>) -> Self {
        match event {
            RuleEvent::Existing(r) => Self::Existing(r.into()),
            RuleEvent::Idle => Self::Idle(fnet_routes::Empty),
            RuleEvent::Added(r) => Self::Added(r.into()),
            RuleEvent::Removed(r) => Self::Removed(r.into()),
        }
    }
}

impl From<RuleEvent<Ipv6>> for fnet_routes::RuleEventV6 {
    fn from(event: RuleEvent<Ipv6>) -> Self {
        match event {
            RuleEvent::Existing(r) => Self::Existing(r.into()),
            RuleEvent::Idle => Self::Idle(fnet_routes::Empty),
            RuleEvent::Added(r) => Self::Added(r.into()),
            RuleEvent::Removed(r) => Self::Removed(r.into()),
        }
    }
}

/// Admin extension for the rules part of `fuchsia.net.routes.admin` FIDL API.
pub trait FidlRuleAdminIpExt: Ip {
    /// The "rule table" protocol to use for this IP version.
    type RuleTableMarker: DiscoverableProtocolMarker<RequestStream = Self::RuleTableRequestStream>;
    /// The "rule set" protocol to use for this IP Version.
    type RuleSetMarker: ProtocolMarker<RequestStream = Self::RuleSetRequestStream>;
    /// The request stream for the rule table protocol.
    type RuleTableRequestStream: fidl::endpoints::RequestStream<Ok: Send, ControlHandle: Send>;
    /// The request stream for the rule set protocol.
    type RuleSetRequestStream: fidl::endpoints::RequestStream<Ok: Send, ControlHandle: Send>;
    /// The responder for AddRule requests.
    type RuleSetAddRuleResponder: Responder<
        Payload = Result<(), fnet_routes_admin::RuleSetError>,
        ControlHandle = Self::RuleSetControlHandle,
    >;
    /// The responder for RemoveRule requests.
    type RuleSetRemoveRuleResponder: Responder<
        Payload = Result<(), fnet_routes_admin::RuleSetError>,
        ControlHandle = Self::RuleSetControlHandle,
    >;
    /// The responder for AuthenticateForRouteTable requests.
    type RuleSetAuthenticateForRouteTableResponder: Responder<
        Payload = Result<(), fnet_routes_admin::AuthenticateForRouteTableError>,
        ControlHandle = Self::RuleSetControlHandle,
    >;
    /// The control handle for RuleTable protocols.
    type RuleTableControlHandle: fidl::endpoints::ControlHandle + Send + Clone;
    /// The control handle for RuleSet protocols.
    type RuleSetControlHandle: fidl::endpoints::ControlHandle + Send + Clone;

    /// Turns a FIDL rule set request into the extension type.
    fn into_rule_set_request(
        request: fidl::endpoints::Request<Self::RuleSetMarker>,
    ) -> RuleSetRequest<Self>;

    /// Turns a FIDL rule table request into the extension type.
    fn into_rule_table_request(
        request: fidl::endpoints::Request<Self::RuleTableMarker>,
    ) -> RuleTableRequest<Self>;
}

impl FidlRuleAdminIpExt for Ipv4 {
    type RuleTableMarker = fnet_routes_admin::RuleTableV4Marker;
    type RuleSetMarker = fnet_routes_admin::RuleSetV4Marker;
    type RuleTableRequestStream = fnet_routes_admin::RuleTableV4RequestStream;
    type RuleSetRequestStream = fnet_routes_admin::RuleSetV4RequestStream;
    type RuleSetAddRuleResponder = fnet_routes_admin::RuleSetV4AddRuleResponder;
    type RuleSetRemoveRuleResponder = fnet_routes_admin::RuleSetV4RemoveRuleResponder;
    type RuleSetAuthenticateForRouteTableResponder =
        fnet_routes_admin::RuleSetV4AuthenticateForRouteTableResponder;
    type RuleTableControlHandle = fnet_routes_admin::RuleTableV4ControlHandle;
    type RuleSetControlHandle = fnet_routes_admin::RuleSetV4ControlHandle;

    fn into_rule_set_request(
        request: fidl::endpoints::Request<Self::RuleSetMarker>,
    ) -> RuleSetRequest<Self> {
        RuleSetRequest::from(request)
    }

    fn into_rule_table_request(
        request: fidl::endpoints::Request<Self::RuleTableMarker>,
    ) -> RuleTableRequest<Self> {
        RuleTableRequest::from(request)
    }
}

impl FidlRuleAdminIpExt for Ipv6 {
    type RuleTableMarker = fnet_routes_admin::RuleTableV6Marker;
    type RuleSetMarker = fnet_routes_admin::RuleSetV6Marker;
    type RuleTableRequestStream = fnet_routes_admin::RuleTableV6RequestStream;
    type RuleSetRequestStream = fnet_routes_admin::RuleSetV6RequestStream;
    type RuleSetAddRuleResponder = fnet_routes_admin::RuleSetV6AddRuleResponder;
    type RuleSetRemoveRuleResponder = fnet_routes_admin::RuleSetV6RemoveRuleResponder;
    type RuleSetAuthenticateForRouteTableResponder =
        fnet_routes_admin::RuleSetV6AuthenticateForRouteTableResponder;
    type RuleTableControlHandle = fnet_routes_admin::RuleTableV6ControlHandle;
    type RuleSetControlHandle = fnet_routes_admin::RuleSetV6ControlHandle;

    fn into_rule_set_request(
        request: fidl::endpoints::Request<Self::RuleSetMarker>,
    ) -> RuleSetRequest<Self> {
        RuleSetRequest::from(request)
    }

    fn into_rule_table_request(
        request: fidl::endpoints::Request<Self::RuleTableMarker>,
    ) -> RuleTableRequest<Self> {
        RuleTableRequest::from(request)
    }
}

impl_responder!(
    fnet_routes_admin::RuleSetV4AddRuleResponder,
    Result<(), fnet_routes_admin::RuleSetError>,
);
impl_responder!(
    fnet_routes_admin::RuleSetV4RemoveRuleResponder,
    Result<(), fnet_routes_admin::RuleSetError>,
);
impl_responder!(
    fnet_routes_admin::RuleSetV4AuthenticateForRouteTableResponder,
    Result<(), fnet_routes_admin::AuthenticateForRouteTableError>,
);
impl_responder!(
    fnet_routes_admin::RuleSetV6AddRuleResponder,
    Result<(), fnet_routes_admin::RuleSetError>,
);
impl_responder!(
    fnet_routes_admin::RuleSetV6RemoveRuleResponder,
    Result<(), fnet_routes_admin::RuleSetError>,
);
impl_responder!(
    fnet_routes_admin::RuleSetV6AuthenticateForRouteTableResponder,
    Result<(), fnet_routes_admin::AuthenticateForRouteTableError>,
);

/// Conversion error for rule elements.
#[derive(Debug, Error, Clone, Copy, PartialEq)]
pub enum RuleFidlConversionError {
    /// A required field was unset. The provided string is the human-readable
    /// name of the unset field.
    #[error("BaseMatcher is missing from the RuleMatcher")]
    BaseMatcherMissing,
    /// Destination Subnet conversion failed.
    #[error("failed to convert `destination` to net_types subnet: {0:?}")]
    DestinationSubnet(net_types::ip::SubnetError),
    /// Unknown union variant.
    #[error("unexpected union variant for {name}, got ordinal = ({unknown_ordinal})")]
    #[allow(missing_docs)]
    UnknownOrdinal { name: &'static str, unknown_ordinal: u64 },
}

/// The priority of the rule set, all rule sets are linearized based on this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleSetPriority(u32);

/// The priority for the default rule set, where the default rule that points
/// to the main table lives.
pub const DEFAULT_RULE_SET_PRIORITY: RuleSetPriority =
    RuleSetPriority(fnet_routes::DEFAULT_RULE_SET_PRIORITY);

/// The index of a rule within a provided rule set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleIndex(u32);

impl RuleIndex {
    /// Create a new rule index from a scalar.
    pub const fn new(x: u32) -> Self {
        Self(x)
    }
}

impl From<RuleSetPriority> for u32 {
    fn from(RuleSetPriority(x): RuleSetPriority) -> Self {
        x
    }
}

impl From<u32> for RuleSetPriority {
    fn from(x: u32) -> Self {
        Self(x)
    }
}

impl From<RuleIndex> for u32 {
    fn from(RuleIndex(x): RuleIndex) -> Self {
        x
    }
}

impl From<u32> for RuleIndex {
    fn from(x: u32) -> Self {
        Self(x)
    }
}

/// How the interface of a packet should be matched against a rule.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InterfaceMatcher {
    /// Match on the name of the device.
    DeviceName(String),
}

impl TryFrom<fnet_routes::InterfaceMatcher> for InterfaceMatcher {
    type Error = RuleFidlConversionError;
    fn try_from(matcher: fnet_routes::InterfaceMatcher) -> Result<Self, Self::Error> {
        match matcher {
            fnet_routes::InterfaceMatcher::DeviceName(name) => Ok(Self::DeviceName(name)),
            fnet_routes::InterfaceMatcher::__SourceBreaking { unknown_ordinal } => {
                Err(RuleFidlConversionError::UnknownOrdinal {
                    name: "InterfaceMatcher",
                    unknown_ordinal,
                })
            }
        }
    }
}

impl From<InterfaceMatcher> for fnet_routes::InterfaceMatcher {
    fn from(matcher: InterfaceMatcher) -> Self {
        match matcher {
            InterfaceMatcher::DeviceName(name) => fnet_routes::InterfaceMatcher::DeviceName(name),
        }
    }
}

/// The matcher part of the rule that is used to match packets.
///
/// The default matcher is the one that matches every packets, i.e., all the
/// fields are none.
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq)]
pub struct RuleMatcher<I: Ip> {
    /// Matches whether the source address of the packet is from the subnet.
    pub from: Option<Subnet<I::Addr>>,
    /// Matches the packet iff the packet was locally generated.
    pub locally_generated: Option<bool>,
    /// Matches the packet iff the socket that was bound to the device using
    /// `SO_BINDTODEVICE`.
    pub bound_device: Option<InterfaceMatcher>,
    /// The matcher for the MARK_1 domain.
    pub mark_1: Option<MarkMatcher>,
    /// The matcher for the MARK_2 domain.
    pub mark_2: Option<MarkMatcher>,
}

impl TryFrom<fnet_routes::RuleMatcherV4> for RuleMatcher<Ipv4> {
    type Error = RuleFidlConversionError;
    fn try_from(
        fnet_routes::RuleMatcherV4 {
            from,
            base,
            __source_breaking: fidl::marker::SourceBreaking,
        }: fnet_routes::RuleMatcherV4,
    ) -> Result<Self, Self::Error> {
        let fnet_routes::BaseMatcher {
            locally_generated,
            bound_device,
            mark_1,
            mark_2,
            __source_breaking: fidl::marker::SourceBreaking,
        } = base.ok_or(RuleFidlConversionError::BaseMatcherMissing)?;
        Ok(Self {
            from: from
                .map(|from| from.try_into_ext().map_err(RuleFidlConversionError::DestinationSubnet))
                .transpose()?,
            locally_generated,
            bound_device: bound_device.map(InterfaceMatcher::try_from).transpose()?,
            mark_1: mark_1.map(MarkMatcher::try_from).transpose()?,
            mark_2: mark_2.map(MarkMatcher::try_from).transpose()?,
        })
    }
}

impl From<RuleMatcher<Ipv4>> for fnet_routes::RuleMatcherV4 {
    fn from(
        RuleMatcher { from, locally_generated, bound_device, mark_1, mark_2 }: RuleMatcher<Ipv4>,
    ) -> Self {
        fnet_routes::RuleMatcherV4 {
            from: from.map(|from| fnet::Ipv4AddressWithPrefix {
                addr: from.network().into_ext(),
                prefix_len: from.prefix(),
            }),
            base: Some(fnet_routes::BaseMatcher {
                locally_generated,
                bound_device: bound_device.map(fnet_routes::InterfaceMatcher::from),
                mark_1: mark_1.map(Into::into),
                mark_2: mark_2.map(Into::into),
                __source_breaking: fidl::marker::SourceBreaking,
            }),
            __source_breaking: fidl::marker::SourceBreaking,
        }
    }
}

impl TryFrom<fnet_routes::RuleMatcherV6> for RuleMatcher<Ipv6> {
    type Error = RuleFidlConversionError;
    fn try_from(
        fnet_routes::RuleMatcherV6 {
            from,
            base,
            __source_breaking: fidl::marker::SourceBreaking,
        }: fnet_routes::RuleMatcherV6,
    ) -> Result<Self, Self::Error> {
        let fnet_routes::BaseMatcher {
            locally_generated,
            bound_device,
            mark_1,
            mark_2,
            __source_breaking: fidl::marker::SourceBreaking,
        } = base.ok_or(RuleFidlConversionError::BaseMatcherMissing)?;
        Ok(Self {
            from: from
                .map(|from| from.try_into_ext().map_err(RuleFidlConversionError::DestinationSubnet))
                .transpose()?,
            locally_generated,
            bound_device: bound_device.map(InterfaceMatcher::try_from).transpose()?,
            mark_1: mark_1.map(MarkMatcher::try_from).transpose()?,
            mark_2: mark_2.map(MarkMatcher::try_from).transpose()?,
        })
    }
}

impl From<RuleMatcher<Ipv6>> for fnet_routes::RuleMatcherV6 {
    fn from(
        RuleMatcher { from, locally_generated, bound_device, mark_1, mark_2 }: RuleMatcher<Ipv6>,
    ) -> Self {
        fnet_routes::RuleMatcherV6 {
            from: from.map(|from| fnet::Ipv6AddressWithPrefix {
                addr: from.network().into_ext(),
                prefix_len: from.prefix(),
            }),
            base: Some(fnet_routes::BaseMatcher {
                locally_generated,
                bound_device: bound_device.map(fnet_routes::InterfaceMatcher::from),
                mark_1: mark_1.map(Into::into),
                mark_2: mark_2.map(Into::into),
                __source_breaking: fidl::marker::SourceBreaking,
            }),
            __source_breaking: fidl::marker::SourceBreaking,
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
/// A matcher to be used against the mark value.
pub enum MarkMatcher {
    /// This mark domain does not have a mark.
    Unmarked,
    /// This mark domain has a mark.
    Marked {
        /// Mask to apply before comparing to the range in `between`.
        mask: u32,
        /// The mark is between the given range.
        between: RangeInclusive<u32>,
    },
}

impl TryFrom<fnet_routes::MarkMatcher> for MarkMatcher {
    type Error = RuleFidlConversionError;

    fn try_from(sel: fnet_routes::MarkMatcher) -> Result<Self, Self::Error> {
        match sel {
            fnet_routes::MarkMatcher::Unmarked(fnet_routes::Unmarked) => Ok(MarkMatcher::Unmarked),
            fnet_routes::MarkMatcher::Marked(fnet_routes::Marked {
                mask,
                between: fnet_routes::Between { start, end },
            }) => Ok(MarkMatcher::Marked { mask, between: RangeInclusive::new(start, end) }),
            fnet_routes::MarkMatcher::__SourceBreaking { unknown_ordinal } => {
                Err(RuleFidlConversionError::UnknownOrdinal {
                    name: "MarkMatcher",
                    unknown_ordinal,
                })
            }
        }
    }
}

impl From<MarkMatcher> for fnet_routes::MarkMatcher {
    fn from(sel: MarkMatcher) -> Self {
        match sel {
            MarkMatcher::Unmarked => fnet_routes::MarkMatcher::Unmarked(fnet_routes::Unmarked),
            MarkMatcher::Marked { mask, between } => {
                let (start, end) = between.into_inner();
                fnet_routes::MarkMatcher::Marked(fnet_routes::Marked {
                    mask,
                    between: fnet_routes::Between { start, end },
                })
            }
        }
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
/// Actions of a rule if the matcher matches.
pub enum RuleAction {
    /// Return network is unreachable.
    Unreachable,
    /// Look for a route in the indicated route table. If there is no matching
    /// route in the target table, the lookup will continue to consider the
    /// next rule.
    Lookup(u32),
}

impl From<fnet_routes::RuleAction> for RuleAction {
    fn from(action: fnet_routes::RuleAction) -> Self {
        match action {
            fnet_routes::RuleAction::Lookup(table_id) => RuleAction::Lookup(table_id),
            fnet_routes::RuleAction::Unreachable(fnet_routes::Unreachable) => {
                RuleAction::Unreachable
            }
            fnet_routes::RuleAction::__SourceBreaking { unknown_ordinal } => {
                panic!("unexpected mark matcher variant, unknown ordinal: {unknown_ordinal}")
            }
        }
    }
}

impl From<RuleAction> for fnet_routes::RuleAction {
    fn from(action: RuleAction) -> Self {
        match action {
            RuleAction::Unreachable => {
                fnet_routes::RuleAction::Unreachable(fnet_routes::Unreachable)
            }
            RuleAction::Lookup(table_id) => fnet_routes::RuleAction::Lookup(table_id),
        }
    }
}

/// GenericOverIp version of RouteTableV{4, 6}Request.
#[derive(GenericOverIp, Debug)]
#[generic_over_ip(I, Ip)]
pub enum RuleTableRequest<I: FidlRuleAdminIpExt> {
    /// Creates a new rule set for the global rule table.
    NewRuleSet {
        /// The priority of the the rule set.
        priority: RuleSetPriority,
        /// The server end of the rule set protocol.
        rule_set: fidl::endpoints::ServerEnd<I::RuleSetMarker>,
        /// Control handle to the protocol.
        control_handle: I::RuleTableControlHandle,
    },
}

impl From<fnet_routes_admin::RuleTableV4Request> for RuleTableRequest<Ipv4> {
    fn from(value: fnet_routes_admin::RuleTableV4Request) -> Self {
        match value {
            fnet_routes_admin::RuleTableV4Request::NewRuleSet {
                priority,
                rule_set,
                control_handle,
            } => Self::NewRuleSet { priority: RuleSetPriority(priority), rule_set, control_handle },
        }
    }
}

impl From<fnet_routes_admin::RuleTableV6Request> for RuleTableRequest<Ipv6> {
    fn from(value: fnet_routes_admin::RuleTableV6Request) -> Self {
        match value {
            fnet_routes_admin::RuleTableV6Request::NewRuleSet {
                priority,
                rule_set,
                control_handle,
            } => Self::NewRuleSet { priority: RuleSetPriority(priority), rule_set, control_handle },
        }
    }
}

/// GenericOverIp version of RuleSetV{4, 6}Request.
#[derive(GenericOverIp, Debug)]
#[generic_over_ip(I, Ip)]
pub enum RuleSetRequest<I: FidlRuleAdminIpExt> {
    /// Adds a rule to the rule set.
    AddRule {
        /// The index of the rule to be added.
        index: RuleIndex,
        /// The matcher of the rule.
        matcher: Result<RuleMatcher<I>, RuleFidlConversionError>,
        /// The action of the rule.
        action: RuleAction,
        /// The responder for this request.
        responder: I::RuleSetAddRuleResponder,
    },
    /// Removes a rule from the rule set.
    RemoveRule {
        /// The index of the rule to be removed.
        index: RuleIndex,
        /// The responder for this request.
        responder: I::RuleSetRemoveRuleResponder,
    },
    /// Authenticates the rule set for managing routes on a route table.
    AuthenticateForRouteTable {
        /// The table id of the table being authenticated for.
        table: u32,
        /// The credential proving authorization for this route table.
        token: fidl::Event,
        /// The responder for this request.
        responder: I::RuleSetAuthenticateForRouteTableResponder,
    },
    /// Closes the rule set
    Close {
        /// The control handle to rule set protocol.
        control_handle: I::RuleSetControlHandle,
    },
}

impl From<fnet_routes_admin::RuleSetV4Request> for RuleSetRequest<Ipv4> {
    fn from(value: fnet_routes_admin::RuleSetV4Request) -> Self {
        match value {
            fnet_routes_admin::RuleSetV4Request::AddRule { index, matcher, action, responder } => {
                RuleSetRequest::AddRule {
                    index: RuleIndex(index),
                    matcher: matcher.try_into(),
                    action: action.into(),
                    responder,
                }
            }
            fnet_routes_admin::RuleSetV4Request::RemoveRule { index, responder } => {
                RuleSetRequest::RemoveRule { index: RuleIndex(index), responder }
            }
            fnet_routes_admin::RuleSetV4Request::AuthenticateForRouteTable {
                table,
                token,
                responder,
            } => RuleSetRequest::AuthenticateForRouteTable { table, token, responder },
            fnet_routes_admin::RuleSetV4Request::Close { control_handle } => {
                RuleSetRequest::Close { control_handle }
            }
        }
    }
}
impl From<fnet_routes_admin::RuleSetV6Request> for RuleSetRequest<Ipv6> {
    fn from(value: fnet_routes_admin::RuleSetV6Request) -> Self {
        match value {
            fnet_routes_admin::RuleSetV6Request::AddRule { index, matcher, action, responder } => {
                RuleSetRequest::AddRule {
                    index: RuleIndex(index),
                    matcher: matcher.try_into(),
                    action: action.into(),
                    responder,
                }
            }
            fnet_routes_admin::RuleSetV6Request::RemoveRule { index, responder } => {
                RuleSetRequest::RemoveRule { index: RuleIndex(index), responder }
            }
            fnet_routes_admin::RuleSetV6Request::AuthenticateForRouteTable {
                table,
                token,
                responder,
            } => RuleSetRequest::AuthenticateForRouteTable { table, token, responder },
            fnet_routes_admin::RuleSetV6Request::Close { control_handle } => {
                RuleSetRequest::Close { control_handle }
            }
        }
    }
}

/// Rule set creation errors.
#[derive(Clone, Debug, Error)]
pub enum RuleSetCreationError {
    /// Proxy creation failed.
    #[error("failed to create proxy: {0}")]
    CreateProxy(fidl::Error),
    /// Rule set creation failed.
    #[error("failed to create route set: {0}")]
    RuleSet(fidl::Error),
}

/// Creates a new rule set for the rule table.
pub fn new_rule_set<I: Ip + FidlRuleAdminIpExt>(
    rule_table_proxy: &<I::RuleTableMarker as ProtocolMarker>::Proxy,
    priority: RuleSetPriority,
) -> Result<<I::RuleSetMarker as ProtocolMarker>::Proxy, RuleSetCreationError> {
    let (rule_set_proxy, rule_set_server_end) = fidl::endpoints::create_proxy::<I::RuleSetMarker>()
        .map_err(RuleSetCreationError::CreateProxy)?;

    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct NewRuleSetInput<'a, I: FidlRuleAdminIpExt> {
        rule_set_server_end: fidl::endpoints::ServerEnd<I::RuleSetMarker>,
        rule_table_proxy: &'a <I::RuleTableMarker as ProtocolMarker>::Proxy,
    }
    let result = I::map_ip_in(
        NewRuleSetInput::<'_, I> { rule_set_server_end, rule_table_proxy },
        |NewRuleSetInput { rule_set_server_end, rule_table_proxy }| {
            rule_table_proxy.new_rule_set(priority.into(), rule_set_server_end)
        },
        |NewRuleSetInput { rule_set_server_end, rule_table_proxy }| {
            rule_table_proxy.new_rule_set(priority.into(), rule_set_server_end)
        },
    );

    result.map_err(RuleSetCreationError::RuleSet)?;
    Ok(rule_set_proxy)
}

/// Dispatches `authenticate_for_route_table` on either the `RuleSetV4` or
/// `RuleSetV6` proxy.
pub async fn authenticate_for_route_table<I: Ip + FidlRuleAdminIpExt>(
    rule_set: &<I::RuleSetMarker as ProtocolMarker>::Proxy,
    table_id: u32,
    token: fidl::Event,
) -> Result<Result<(), fnet_routes_admin::AuthenticateForRouteTableError>, fidl::Error> {
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct AuthenticateForRouteTableInput<'a, I: FidlRuleAdminIpExt> {
        rule_set: &'a <I::RuleSetMarker as ProtocolMarker>::Proxy,
        table_id: u32,
        token: fidl::Event,
    }

    I::map_ip_in(
        AuthenticateForRouteTableInput { rule_set, table_id, token },
        |AuthenticateForRouteTableInput { rule_set, table_id, token }| {
            Either::Left(rule_set.authenticate_for_route_table(table_id, token))
        },
        |AuthenticateForRouteTableInput { rule_set, table_id, token }| {
            Either::Right(rule_set.authenticate_for_route_table(table_id, token))
        },
    )
    .await
}

/// Dispatches `add_rule` on either the `RuleSetV4` or `RuleSetV6` proxy.
pub async fn add_rule<I: Ip + FidlRuleAdminIpExt>(
    rule_set: &<I::RuleSetMarker as ProtocolMarker>::Proxy,
    index: RuleIndex,
    matcher: RuleMatcher<I>,
    action: RuleAction,
) -> Result<Result<(), fnet_routes_admin::RuleSetError>, fidl::Error> {
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct AddRuleInput<'a, I: FidlRuleAdminIpExt> {
        rule_set: &'a <I::RuleSetMarker as ProtocolMarker>::Proxy,
        index: RuleIndex,
        matcher: RuleMatcher<I>,
        action: RuleAction,
    }

    I::map_ip_in(
        AddRuleInput { rule_set, index, matcher, action },
        |AddRuleInput { rule_set, index, matcher, action }| {
            Either::Left(rule_set.add_rule(index.into(), &matcher.into(), &action.into()))
        },
        |AddRuleInput { rule_set, index, matcher, action }| {
            Either::Right(rule_set.add_rule(index.into(), &matcher.into(), &action.into()))
        },
    )
    .await
}

/// Dispatches `remove_rule` on either the `RuleSetV4` or `RuleSetV6` proxy.
pub async fn remove_rule<I: Ip + FidlRuleAdminIpExt>(
    rule_set: &<I::RuleSetMarker as ProtocolMarker>::Proxy,
    index: RuleIndex,
) -> Result<Result<(), fnet_routes_admin::RuleSetError>, fidl::Error> {
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct RemoveRuleInput<'a, I: FidlRuleAdminIpExt> {
        rule_set: &'a <I::RuleSetMarker as ProtocolMarker>::Proxy,
        index: RuleIndex,
    }

    I::map_ip_in(
        RemoveRuleInput { rule_set, index },
        |RemoveRuleInput { rule_set, index }| Either::Left(rule_set.remove_rule(index.into())),
        |RemoveRuleInput { rule_set, index }| Either::Right(rule_set.remove_rule(index.into())),
    )
    .await
}

/// Dispatches `close` on either the `RuleSetV4` or `RuleSetV6` proxy.
///
/// Waits until the channel is closed before returning.
pub async fn close_rule_set<I: Ip + FidlRuleAdminIpExt>(
    rule_set: <I::RuleSetMarker as ProtocolMarker>::Proxy,
) -> Result<(), fidl::Error> {
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct CloseInput<'a, I: FidlRuleAdminIpExt> {
        rule_set: &'a <I::RuleSetMarker as ProtocolMarker>::Proxy,
    }

    let result = I::map_ip_in(
        CloseInput { rule_set: &rule_set },
        |CloseInput { rule_set }| rule_set.close(),
        |CloseInput { rule_set }| rule_set.close(),
    );

    assert!(rule_set
        .on_closed()
        .await
        .expect("failed to wait for signals")
        .contains(fidl::Signals::CHANNEL_PEER_CLOSED));

    result
}

/// Dispatches either `GetRuleWatcherV4` or `GetRuleWatcherV6` on the state proxy.
pub fn get_rule_watcher<I: FidlRuleIpExt + FidlRouteIpExt>(
    state_proxy: &<I::StateMarker as fidl::endpoints::ProtocolMarker>::Proxy,
) -> Result<<I::RuleWatcherMarker as fidl::endpoints::ProtocolMarker>::Proxy, WatcherCreationError>
{
    let (watcher_proxy, watcher_server_end) =
        fidl::endpoints::create_proxy::<I::RuleWatcherMarker>()
            .map_err(WatcherCreationError::CreateProxy)?;

    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct GetWatcherInputs<'a, I: FidlRuleIpExt + FidlRouteIpExt> {
        watcher_server_end: fidl::endpoints::ServerEnd<I::RuleWatcherMarker>,
        state_proxy: &'a <I::StateMarker as fidl::endpoints::ProtocolMarker>::Proxy,
    }
    let result = I::map_ip_in(
        GetWatcherInputs::<'_, I> { watcher_server_end, state_proxy },
        |GetWatcherInputs { watcher_server_end, state_proxy }| {
            state_proxy.get_rule_watcher_v4(
                watcher_server_end,
                &fnet_routes::RuleWatcherOptionsV4::default(),
            )
        },
        |GetWatcherInputs { watcher_server_end, state_proxy }| {
            state_proxy.get_rule_watcher_v6(
                watcher_server_end,
                &fnet_routes::RuleWatcherOptionsV6::default(),
            )
        },
    );

    result.map_err(WatcherCreationError::GetWatcher)?;
    Ok(watcher_proxy)
}

/// Calls `Watch()` on the provided `RuleWatcherV4` or `RuleWatcherV6` proxy.
pub async fn watch<'a, I: FidlRuleIpExt>(
    watcher_proxy: &'a <I::RuleWatcherMarker as fidl::endpoints::ProtocolMarker>::Proxy,
) -> Result<Vec<I::RuleEvent>, fidl::Error> {
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct WatchInputs<'a, I: FidlRuleIpExt> {
        watcher_proxy: &'a <I::RuleWatcherMarker as fidl::endpoints::ProtocolMarker>::Proxy,
    }
    #[derive(GenericOverIp)]
    #[generic_over_ip(I, Ip)]
    struct WatchOutputs<I: FidlRuleIpExt> {
        watch_fut: fidl::client::QueryResponseFut<Vec<I::RuleEvent>>,
    }
    let WatchOutputs { watch_fut } = net_types::map_ip_twice!(
        I,
        WatchInputs { watcher_proxy },
        |WatchInputs { watcher_proxy }| { WatchOutputs { watch_fut: watcher_proxy.watch() } }
    );
    watch_fut.await
}

/// Route watcher `Watch` errors.
#[derive(Clone, Debug, Error)]
pub enum RuleWatchError {
    /// The call to `Watch` returned a FIDL error.
    #[error("the call to `Watch()` failed: {0}")]
    Fidl(fidl::Error),
    /// The event returned by `Watch` encountered a conversion error.
    #[error("failed to convert event returned by `Watch()`: {0}")]
    Conversion(RuleFidlConversionError),
    /// The server returned an empty batch of events.
    #[error("the call to `Watch()` returned an empty batch of events")]
    EmptyEventBatch,
}

/// Creates a rules event stream from the state proxy.
pub fn rule_event_stream_from_state<I: FidlRuleIpExt + FidlRouteIpExt>(
    state: &<I::StateMarker as fidl::endpoints::ProtocolMarker>::Proxy,
) -> Result<impl Stream<Item = Result<RuleEvent<I>, RuleWatchError>>, WatcherCreationError> {
    let watcher = get_rule_watcher::<I>(state)?;
    rule_event_stream_from_watcher(watcher)
}

/// Turns the provided watcher client into a [`RuleEvent`] stream by applying
/// Hanging-Get watch.
///
/// Each call to `Watch` returns a batch of events, which are flattened into a
/// single stream. If an error is encountered while calling `Watch` or while
/// converting the event, the stream is immediately terminated.
pub fn rule_event_stream_from_watcher<I: FidlRuleIpExt>(
    watcher: <I::RuleWatcherMarker as fidl::endpoints::ProtocolMarker>::Proxy,
) -> Result<impl Stream<Item = Result<RuleEvent<I>, RuleWatchError>>, WatcherCreationError> {
    Ok(stream::ShortCircuit::new(
        futures::stream::try_unfold(watcher, |watcher| async {
            let events_batch = watch::<I>(&watcher).await.map_err(RuleWatchError::Fidl)?;
            if events_batch.is_empty() {
                return Err(RuleWatchError::EmptyEventBatch);
            }
            let events_batch = events_batch
                .into_iter()
                .map(|event| event.try_into().map_err(RuleWatchError::Conversion));
            let event_stream = futures::stream::iter(events_batch);
            Ok(Some((event_stream, watcher)))
        })
        // Flatten the stream of event streams into a single event stream.
        .try_flatten(),
    ))
}

/// Errors returned by [`collect_rules_until_idle`].
#[derive(Clone, Debug, Error)]
pub enum CollectRulesUntilIdleError<I: FidlRuleIpExt> {
    /// There was an error in the event stream.
    #[error("there was an error in the event stream: {0}")]
    ErrorInStream(RuleWatchError),
    /// There was an unexpected event in the event stream. Only `existing` or
    /// `idle` events are expected.
    #[error("there was an unexpected event in the event stream: {0:?}")]
    UnexpectedEvent(RuleEvent<I>),
    /// The event stream unexpectedly ended.
    #[error("the event stream unexpectedly ended")]
    StreamEnded,
}

/// Collects all `existing` events from the stream, stopping once the `idle`
/// event is observed.
pub async fn collect_rules_until_idle<I: FidlRuleIpExt, C: Extend<InstalledRule<I>> + Default>(
    event_stream: impl futures::Stream<Item = Result<RuleEvent<I>, RuleWatchError>> + Unpin,
) -> Result<C, CollectRulesUntilIdleError<I>> {
    fold::fold_while(
        event_stream,
        Ok(C::default()),
        |existing_rules: Result<C, CollectRulesUntilIdleError<I>>, event| {
            futures::future::ready(match existing_rules {
                Err(_) => {
                    unreachable!("`existing_rules` must be `Ok`, because we stop folding on err")
                }
                Ok(mut existing_rules) => match event {
                    Err(e) => {
                        fold::FoldWhile::Done(Err(CollectRulesUntilIdleError::ErrorInStream(e)))
                    }
                    Ok(e) => match e {
                        RuleEvent::Existing(e) => {
                            existing_rules.extend([e]);
                            fold::FoldWhile::Continue(Ok(existing_rules))
                        }
                        RuleEvent::Idle => fold::FoldWhile::Done(Ok(existing_rules)),
                        e @ RuleEvent::Added(_) | e @ RuleEvent::Removed(_) => {
                            fold::FoldWhile::Done(Err(CollectRulesUntilIdleError::UnexpectedEvent(
                                e,
                            )))
                        }
                    },
                },
            })
        },
    )
    .await
    .short_circuited()
    .map_err(|_accumulated_thus_far: Result<C, CollectRulesUntilIdleError<I>>| {
        CollectRulesUntilIdleError::StreamEnded
    })?
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use fnet_routes::BaseMatcher;

    use super::*;

    #[test]
    fn missing_base_matcher_v4() {
        let fidl_matcher = fidl_fuchsia_net_routes::RuleMatcherV4 {
            from: None,
            base: None,
            __source_breaking: fidl::marker::SourceBreaking,
        };
        assert_matches!(
            RuleMatcher::try_from(fidl_matcher),
            Err(RuleFidlConversionError::BaseMatcherMissing)
        );
    }

    #[test]
    fn missing_base_matcher_v6() {
        let fidl_matcher = fidl_fuchsia_net_routes::RuleMatcherV6 {
            from: None,
            base: None,
            __source_breaking: fidl::marker::SourceBreaking,
        };
        assert_matches!(
            RuleMatcher::try_from(fidl_matcher),
            Err(RuleFidlConversionError::BaseMatcherMissing)
        );
    }

    #[test]
    fn invalid_destination_subnet_v4() {
        let fidl_matcher = fidl_fuchsia_net_routes::RuleMatcherV4 {
            // Invalid, because subnets should not have the "host bits" set.
            from: Some(net_declare::fidl_ip_v4_with_prefix!("192.168.0.1/24")),
            base: Some(BaseMatcher::default()),
            __source_breaking: fidl::marker::SourceBreaking,
        };
        assert_matches!(
            RuleMatcher::try_from(fidl_matcher),
            Err(RuleFidlConversionError::DestinationSubnet(_))
        );
    }

    #[test]
    fn invalid_destination_subnet_v6() {
        let fidl_matcher = fidl_fuchsia_net_routes::RuleMatcherV6 {
            // Invalid, because subnets should not have the "host bits" set.
            from: Some(net_declare::fidl_ip_v6_with_prefix!("fe80::1/64")),
            base: Some(BaseMatcher::default()),
            __source_breaking: fidl::marker::SourceBreaking,
        };
        assert_matches!(
            RuleMatcher::try_from(fidl_matcher),
            Err(RuleFidlConversionError::DestinationSubnet(_))
        );
    }

    #[test]
    fn all_unspecified_matcher_v4() {
        let fidl_matcher = fidl_fuchsia_net_routes::RuleMatcherV4 {
            from: None,
            base: Some(BaseMatcher {
                locally_generated: None,
                bound_device: None,
                mark_1: None,
                mark_2: None,
                __source_breaking: fidl::marker::SourceBreaking,
            }),
            __source_breaking: fidl::marker::SourceBreaking,
        };
        assert_matches!(
            RuleMatcher::try_from(fidl_matcher),
            Ok(RuleMatcher {
                from: None,
                locally_generated: None,
                bound_device: None,
                mark_1: None,
                mark_2: None,
            })
        );
    }

    #[test]
    fn all_unspecified_matcher_v6() {
        let fidl_matcher = fidl_fuchsia_net_routes::RuleMatcherV6 {
            from: None,
            base: Some(BaseMatcher {
                locally_generated: None,
                bound_device: None,
                mark_1: None,
                mark_2: None,
                __source_breaking: fidl::marker::SourceBreaking,
            }),
            __source_breaking: fidl::marker::SourceBreaking,
        };
        assert_matches!(
            RuleMatcher::try_from(fidl_matcher),
            Ok(RuleMatcher {
                from: None,
                locally_generated: None,
                bound_device: None,
                mark_1: None,
                mark_2: None,
            })
        );
    }
}