brec 0.6.0

A flexible binary format for storing and streaming structured data as packets with CRC protection and recoverability from corruption. Built for extensibility and robustness.
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
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
use crate::*;

/// Represents a rule callback, which can be either a dynamic closure or a static function.
///
/// This abstraction allows users to define flexible behaviors (e.g., `FnMut` closures),
/// while also supporting simple static functions for performance or clarity.
///
/// # Type Parameters
/// - `D`: Dynamic callback type (e.g., boxed `FnMut` or `Fn`)
/// - `S`: Static function type
pub enum RuleFnDef<D, S> {
    /// A dynamic, possibly stateful closure.
    Dynamic(D),

    /// A static function pointer.
    Static(S),
}

/// Callback used when `PacketBufReaderDef` encounters unrecognized data.
pub type IgnoredCallback = RuleFnDef<Box<dyn FnMut(&[u8]) + Send + 'static>, fn(&[u8])>;

/// Action returned by controlled ignored-data callbacks.
///
/// Use this with `RuleDef::IgnoredControl` to decide whether the reader should
/// continue scanning after unrecognized bytes or abort with `Error::IgnoredDataRejected`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IgnoredAction {
    /// Continue scanning the stream for the next packet.
    Continue,
    /// Stop reading and return `Error::IgnoredDataRejected`.
    Stop,
}

/// Callback used when `PacketBufReaderDef` encounters unrecognized data and the
/// caller wants to update workflow context or decide whether scanning should continue.
pub type ControlledIgnoredCallback<WorkflowCtx> = RuleFnDef<
    Box<dyn FnMut(&[u8], &mut WorkflowCtx) -> Result<IgnoredAction, Error> + Send + 'static>,
    fn(&[u8], &mut WorkflowCtx) -> Result<IgnoredAction, Error>,
>;

/// Callback used to handle and write unrecognized data to a separate writer.
pub type WriteIgnoredCallback<W> = RuleFnDef<
    Box<dyn FnMut(&mut std::io::BufWriter<W>, &[u8]) -> std::io::Result<()> + Send + 'static>,
    fn(&mut std::io::BufWriter<W>, &[u8]) -> std::io::Result<()>,
>;

/// Lightweight view over blocks parsed in zero-copy mode during prefiltering.
pub struct PeekedBlocksDef<'a, BR> {
    inner: &'a [BR],
}

/// Generated bridge between a concrete user block type and a referred block enum variant.
///
/// This trait is implemented by `brec::generate!()` for each user-defined block, allowing
/// typed access like `blocks.get::<MyBlock>()` without matching on `BlockReferred` manually.
pub trait PeekAs<'a, T> {
    /// Concrete block type exposed when the cast succeeds.
    type Peeked: 'a;

    /// Attempts to view the current referred block as a specific concrete block type.
    fn peek_as(&'a self) -> Option<&'a Self::Peeked>;
}

impl<'a, BR> PeekedBlocksDef<'a, BR> {
    /// Creates a lightweight borrowed view over a sequence of referred blocks.
    pub fn new(inner: &'a [BR]) -> Self {
        Self { inner }
    }

    /// Returns the number of referred blocks in the view.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` when the view contains no blocks.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the block at the given position as a `PeekedBlockDef`.
    pub fn nth(&self, index: usize) -> Option<PeekedBlockDef<'a, BR>> {
        self.inner.get(index).map(PeekedBlockDef::new)
    }

    /// Returns the first block in the view, if any.
    pub fn first(&self) -> Option<PeekedBlockDef<'a, BR>> {
        self.nth(0)
    }

    /// Returns `true` when at least one block can be viewed as the requested type.
    pub fn has<T>(&self) -> bool
    where
        BR: PeekAs<'a, T>,
    {
        self.inner.iter().any(|block| block.peek_as().is_some())
    }

    /// Returns the first block of the requested concrete type.
    pub fn get_as<T>(&self) -> Option<&'a <BR as PeekAs<'a, T>>::Peeked>
    where
        BR: PeekAs<'a, T>,
    {
        self.inner.iter().find_map(|block| block.peek_as())
    }

    /// Returns the first block of the requested concrete type.
    pub fn get<T>(&self) -> Option<&'a <BR as PeekAs<'a, T>>::Peeked>
    where
        BR: PeekAs<'a, T>,
    {
        self.get_as::<T>()
    }

    /// Finds the first block of the requested type that matches the predicate.
    pub fn find<T, F>(&self, mut predicate: F) -> Option<&'a <BR as PeekAs<'a, T>>::Peeked>
    where
        BR: PeekAs<'a, T>,
        F: FnMut(&<BR as PeekAs<'a, T>>::Peeked) -> bool,
    {
        self.inner
            .iter()
            .filter_map(|block| block.peek_as())
            .find(|block| predicate(block))
    }

    /// Iterates only over blocks of the requested concrete type.
    pub fn iter_as<T>(&self) -> impl Iterator<Item = &'a <BR as PeekAs<'a, T>>::Peeked> + 'a
    where
        BR: PeekAs<'a, T>,
    {
        self.inner.iter().filter_map(|block| block.peek_as())
    }

    /// Iterates over all blocks in their referred representation.
    pub fn iter(&self) -> impl Iterator<Item = PeekedBlockDef<'a, BR>> + 'a {
        self.inner.iter().map(PeekedBlockDef::new)
    }

    /// Advanced escape hatch for direct access to the underlying referred blocks.
    pub fn as_slice(&self) -> &'a [BR] {
        self.inner
    }
}

/// Borrowed view over a single referred block exposed during prefiltering.
pub struct PeekedBlockDef<'a, BR> {
    inner: &'a BR,
}

impl<'a, BR> PeekedBlockDef<'a, BR> {
    /// Wraps a referred block into a `PeekedBlockDef`.
    pub fn new(inner: &'a BR) -> Self {
        Self { inner }
    }

    /// Advanced escape hatch for direct access to the underlying referred block.
    pub fn as_referred(&self) -> &'a BR {
        self.inner
    }

    /// Attempts to view the current block as the requested concrete block type.
    pub fn as_type<T>(&self) -> Option<&'a <BR as PeekAs<'a, T>>::Peeked>
    where
        BR: PeekAs<'a, T>,
    {
        self.inner.peek_as()
    }
}

impl<'a, BR> std::ops::Deref for PeekedBlockDef<'a, BR> {
    type Target = BR;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}

impl<'a, BR> IntoIterator for PeekedBlocksDef<'a, BR> {
    type Item = PeekedBlockDef<'a, BR>;
    type IntoIter = std::iter::Map<std::slice::Iter<'a, BR>, fn(&'a BR) -> PeekedBlockDef<'a, BR>>;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.iter().map(PeekedBlockDef::new)
    }
}

/// Callback to prefilter packets early by inspecting block metadata before full parsing.
pub type PrefilterCallback<BR> = RuleFnDef<
    Box<dyn Fn(PeekedBlocksDef<'_, BR>) -> bool + Send + 'static>,
    fn(PeekedBlocksDef<'_, BR>) -> bool,
>;

/// Callback to filter packets by payload content.
pub type PayloadFilterCallback =
    RuleFnDef<Box<dyn Fn(&[u8]) -> bool + Send + 'static>, fn(&[u8]) -> bool>;

/// Callback to filter fully parsed packets.
pub type FilterCallback<B, P, Inner> = RuleFnDef<
    Box<dyn Fn(&PacketDef<B, P, Inner>) -> bool + Send + 'static>,
    fn(&PacketDef<B, P, Inner>) -> bool,
>;

/// Callback invoked before `PacketBufReaderDef` returns a non-error `NextPacket` result.
pub type NextPacketCallback<B, P, Inner, WorkflowCtx> = RuleFnDef<
    Box<
        dyn FnMut(&NextPacket<B, P, Inner>, &mut WorkflowCtx) -> Result<(), Error> + Send + 'static,
    >,
    fn(&NextPacket<B, P, Inner>, &mut WorkflowCtx) -> Result<(), Error>,
>;

/// Defines processing rules used by `PacketBufReaderDef`.
///
/// These rules serve as lightweight hooks, allowing the user to handle non-`brec` binary data,
/// selectively parse packets, or filter by content without modifying the reader itself.
///
/// Rules are additive and modular. Only one rule of each type can be active at a time.
/// Discrete rule kinds supported by `RulesDef`.
///
/// `enum_ids` also generates helper identifier types for this enum. Those
/// generated items do not carry through variant docs cleanly, so
/// `missing_docs` is suppressed locally for this declaration.
#[allow(missing_docs)]
#[enum_ids::enum_ids(display)]
pub enum RuleDef<
    B: BlockDef,
    BR: BlockReferredDef<B>,
    P: PayloadDef<Inner>,
    Inner: PayloadInnerDef,
    WorkflowCtx = (),
> {
    /// Triggered when unknown or malformed data is encountered.
    Ignored(IgnoredCallback),

    /// Triggered when unknown or malformed data is encountered.
    ///
    /// This rule receives the reader workflow context and can stop scanning by
    /// returning `IgnoredAction::Stop`.
    IgnoredControl(ControlledIgnoredCallback<WorkflowCtx>),

    /// Triggered immediately before a non-error `NextPacket` result is returned to the caller.
    NextPacket(NextPacketCallback<B, P, Inner, WorkflowCtx>),

    /// Cheap prefilter during partial block parsing.
    ///
    /// This rule receives a lightweight block view and can reject packets before full parsing,
    /// avoiding unnecessary payload decoding and full block materialization.
    Prefilter(PrefilterCallback<BR>),

    /// Filters packets by inspecting the raw payload buffer (before decoding).
    FilterPayload(PayloadFilterCallback),

    /// Filters fully parsed packets.
    FilterPacket(FilterCallback<B, P, Inner>),
}

/// Internal container for rule management used by `PacketBufReaderDef`.
///
/// Stores registered rules and provides runtime dispatch based on rule type.
///
/// Users do not interact with `RulesDef` directly - it's driven by `PacketBufReaderDef`.
pub struct RulesDef<
    B: BlockDef,
    BR: BlockReferredDef<B>,
    P: PayloadDef<Inner>,
    Inner: PayloadInnerDef,
    WorkflowCtx = (),
> {
    /// Raw list of installed rules in evaluation order.
    pub rules: Vec<RuleDef<B, BR, P, Inner, WorkflowCtx>>,
}

impl<
    B: BlockDef,
    BR: BlockReferredDef<B>,
    P: PayloadDef<Inner>,
    Inner: PayloadInnerDef,
    WorkflowCtx,
> Default for RulesDef<B, BR, P, Inner, WorkflowCtx>
{
    /// Initializes an empty rule set.
    fn default() -> Self {
        Self { rules: Vec::new() }
    }
}
impl<
    B: BlockDef,
    BR: BlockReferredDef<B>,
    P: PayloadDef<Inner>,
    Inner: PayloadInnerDef,
    WorkflowCtx,
> RulesDef<B, BR, P, Inner, WorkflowCtx>
{
    /// Adds a new rule to the rule set.
    ///
    /// Only one rule of each type is allowed at any time. Adding a duplicate
    /// will result in `Error::RuleDuplicate`.
    pub fn add_rule(&mut self, rule: RuleDef<B, BR, P, Inner, WorkflowCtx>) -> Result<(), Error> {
        match &rule {
            RuleDef::Prefilter(..) => {
                if self
                    .rules
                    .iter()
                    .any(|r| matches!(r, RuleDef::Prefilter(..)))
                {
                    return Err(Error::RuleDuplicate);
                }
            }
            RuleDef::FilterPayload(..) => {
                if self
                    .rules
                    .iter()
                    .any(|r| matches!(r, RuleDef::FilterPayload(..)))
                {
                    return Err(Error::RuleDuplicate);
                }
            }
            RuleDef::FilterPacket(..) => {
                if self
                    .rules
                    .iter()
                    .any(|r| matches!(r, RuleDef::FilterPacket(..)))
                {
                    return Err(Error::RuleDuplicate);
                }
            }
            RuleDef::Ignored(..) => {
                if self.rules.iter().any(|r| matches!(r, RuleDef::Ignored(..))) {
                    return Err(Error::RuleDuplicate);
                }
            }
            RuleDef::IgnoredControl(..) => {
                if self
                    .rules
                    .iter()
                    .any(|r| matches!(r, RuleDef::IgnoredControl(..)))
                {
                    return Err(Error::RuleDuplicate);
                }
            }
            RuleDef::NextPacket(..) => {
                if self
                    .rules
                    .iter()
                    .any(|r| matches!(r, RuleDef::NextPacket(..)))
                {
                    return Err(Error::RuleDuplicate);
                }
            }
        };
        self.rules.push(rule);
        Ok(())
    }

    /// Removes a rule by its identifier (`RuleDefId`).
    pub fn remove_rule(&mut self, rule: RuleDefId) {
        self.rules
            .retain(|r| r.id().to_string() != rule.to_string());
    }

    /// Executes ignored-data rules (if defined) with the provided data.
    pub fn ignore(&mut self, buffer: &[u8], ctx: &mut WorkflowCtx) -> Result<(), Error> {
        for rule in self.rules.iter_mut() {
            match rule {
                RuleDef::Ignored(cb) => match cb {
                    RuleFnDef::Static(cb) => cb(buffer),
                    RuleFnDef::Dynamic(cb) => cb(buffer),
                },
                RuleDef::IgnoredControl(cb) => {
                    let action = match cb {
                        RuleFnDef::Static(cb) => cb(buffer, ctx)?,
                        RuleFnDef::Dynamic(cb) => cb(buffer, ctx)?,
                    };
                    if action == IgnoredAction::Stop {
                        return Err(Error::IgnoredDataRejected);
                    }
                }
                _ignored => {}
            }
        }
        Ok(())
    }

    /// Executes the `NextPacket` rule (if defined) before returning a reader result.
    pub fn next_packet(
        &mut self,
        next: &NextPacket<B, P, Inner>,
        ctx: &mut WorkflowCtx,
    ) -> Result<(), Error> {
        for rule in self.rules.iter_mut() {
            if let RuleDef::NextPacket(cb) = rule {
                match cb {
                    RuleFnDef::Static(cb) => cb(next, ctx)?,
                    RuleFnDef::Dynamic(cb) => cb(next, ctx)?,
                }
            }
        }
        Ok(())
    }

    /// Runs the prefilter rule (if defined) and returns whether to continue parsing.
    pub fn prefilter(&self, blocks: &[BR]) -> bool {
        let Some(cb) = self.rules.iter().find_map(|r| {
            if let RuleDef::Prefilter(cb) = r {
                Some(cb)
            } else {
                None
            }
        }) else {
            return true;
        };
        match cb {
            RuleFnDef::Static(cb) => cb(PeekedBlocksDef::new(blocks)),
            RuleFnDef::Dynamic(cb) => cb(PeekedBlocksDef::new(blocks)),
        }
    }

    /// Runs the payload filter rule (if defined) and returns whether to keep the packet.
    pub fn filter_payload(&self, buffer: &[u8]) -> bool {
        let Some(cb) = self.rules.iter().find_map(|r| {
            if let RuleDef::FilterPayload(cb) = r {
                Some(cb)
            } else {
                None
            }
        }) else {
            return true;
        };
        match cb {
            RuleFnDef::Static(cb) => cb(buffer),
            RuleFnDef::Dynamic(cb) => cb(buffer),
        }
    }

    /// Returns `true` when a raw-payload filter rule is configured.
    pub fn has_payload_filter(&self) -> bool {
        self.rules
            .iter()
            .any(|rule| matches!(rule, RuleDef::FilterPayload(..)))
    }

    /// Runs the full packet filter rule on a parsed packet.
    pub fn filter_packet(&self, packet: &PacketDef<B, P, Inner>) -> bool {
        let Some(cb) = self.rules.iter().find_map(|r| {
            if let RuleDef::FilterPacket(cb) = r {
                Some(cb)
            } else {
                None
            }
        }) else {
            return true;
        };
        match cb {
            RuleFnDef::Static(cb) => cb(packet),
            RuleFnDef::Dynamic(cb) => cb(packet),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        ByteBlock, DefaultProtocolContext, Error, ExtractPayloadFrom, IgnoredAction, IoSlices,
        NextPacket, PacketDef, PayloadDef, PayloadHeader, ProtocolSchema, ReadBlockFrom,
        ReadBlockFromSlice, ReadFrom, ReadStatus, RuleDef, RuleDefId, RuleFnDef, RulesDef,
        TryExtractPayloadFrom, TryExtractPayloadFromBuffered, TryReadFrom, TryReadFromBuffered,
        WriteMutTo, WriteTo, WriteVectoredMutTo, WriteVectoredTo, packet::rules::PeekAs,
    };
    use std::io::Cursor;
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    #[derive(Clone)]
    struct RuleBlock {
        field: u8,
    }

    impl RuleBlock {
        fn new(field: u8) -> Self {
            Self { field }
        }
    }

    impl crate::Size for RuleBlock {
        fn size(&self) -> u64 {
            self.field as u64
        }
    }

    impl WriteTo for RuleBlock {
        fn write<T: std::io::Write>(&self, _: &mut T) -> std::io::Result<usize> {
            Err(std::io::Error::other("rules test block write stub"))
        }

        fn write_all<T: std::io::Write>(&self, _: &mut T) -> std::io::Result<()> {
            Err(std::io::Error::other("rules test block write_all stub"))
        }
    }

    impl WriteVectoredTo for RuleBlock {
        fn slices(&self) -> std::io::Result<IoSlices<'_>> {
            Err(std::io::Error::other("rules test block slices stub"))
        }
    }

    // These methods are required by `BlockDef` bounds in packet/rules tests.
    // They are explicit stubs and are covered by a dedicated test below.
    impl TryReadFromBuffered for RuleBlock {
        fn try_read<T: std::io::BufRead, S: ProtocolSchema>(
            _: &mut T,
        ) -> Result<ReadStatus<Self>, Error> {
            Err(Error::Test)
        }
    }

    impl TryReadFrom for RuleBlock {
        fn try_read<T: std::io::Read + std::io::Seek, S: ProtocolSchema>(
            _: &mut T,
        ) -> Result<ReadStatus<Self>, Error> {
            Err(Error::Test)
        }
    }

    impl ReadFrom for RuleBlock {
        fn read<T: std::io::Read, S: ProtocolSchema>(_: &mut T) -> Result<Self, Error> {
            Err(Error::Test)
        }
    }

    impl ReadBlockFrom for RuleBlock {
        fn read<T: std::io::Read>(_: &mut T, _: bool) -> Result<Self, Error> {
            Err(Error::Test)
        }
    }

    impl ReadBlockFromSlice for RuleBlock {
        fn read_from_slice<'a>(_: &'a [u8], _: bool) -> Result<Self, Error>
        where
            Self: 'a + Sized,
        {
            Err(Error::Test)
        }
    }

    impl crate::BlockDef for RuleBlock {}
    impl crate::BlockReferredDef<RuleBlock> for RuleBlock {}

    #[derive(Clone)]
    struct RulePayload {
        _field: u8,
    }

    impl RulePayload {
        fn new(field: u8) -> Self {
            Self { _field: field }
        }
    }

    impl ProtocolSchema for RulePayload {
        type Context<'a> = DefaultProtocolContext;
    }

    impl WriteVectoredMutTo for RulePayload {
        fn slices(&mut self, _: &mut Self::Context<'_>) -> std::io::Result<IoSlices<'_>> {
            Err(std::io::Error::other("rules test payload slices stub"))
        }
    }

    impl WriteMutTo for RulePayload {
        fn write<T: std::io::Write>(
            &mut self,
            _: &mut T,
            _: &mut Self::Context<'_>,
        ) -> std::io::Result<usize> {
            Err(std::io::Error::other("rules test payload write stub"))
        }

        fn write_all<T: std::io::Write>(
            &mut self,
            _: &mut T,
            _: &mut Self::Context<'_>,
        ) -> std::io::Result<()> {
            Err(std::io::Error::other("rules test payload write_all stub"))
        }
    }

    impl crate::PayloadSignature for RulePayload {
        fn sig(&self) -> ByteBlock {
            ByteBlock::Len4(*b"RULS")
        }
    }

    impl crate::PayloadEncodeReferred for RulePayload {
        fn encode(&self, _ctx: &mut Self::Context<'_>) -> std::io::Result<Option<&[u8]>> {
            Err(std::io::Error::other(
                "rules test payload encode_referred stub",
            ))
        }
    }

    impl crate::PayloadHooks for RulePayload {
        fn after_decode(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other(
                "rules test payload after_decode stub",
            ))
        }

        fn before_encode(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other(
                "rules test payload before_encode stub",
            ))
        }
    }

    impl crate::PayloadEncode for RulePayload {
        fn encode(&self, _ctx: &mut Self::Context<'_>) -> std::io::Result<Vec<u8>> {
            Err(std::io::Error::other("rules test payload encode stub"))
        }
    }

    impl crate::PayloadCrc for RulePayload {
        fn crc(&self, _: &mut Self::Context<'_>) -> std::io::Result<ByteBlock> {
            Err(std::io::Error::other("rules test payload crc stub"))
        }

        fn crc_size() -> usize {
            0
        }
    }

    impl crate::PayloadSize for RulePayload {
        fn size(&self, _: &mut Self::Context<'_>) -> std::io::Result<u64> {
            Err(std::io::Error::other("rules test payload size stub"))
        }
    }

    impl crate::PayloadInnerDef for RulePayload {}

    impl TryExtractPayloadFromBuffered<RulePayload> for RulePayload {
        fn try_read<B: std::io::BufRead>(
            _: &mut B,
            _: &PayloadHeader,
            _: &mut <RulePayload as ProtocolSchema>::Context<'_>,
        ) -> Result<ReadStatus<RulePayload>, Error> {
            Err(Error::Test)
        }
    }

    impl TryExtractPayloadFrom<RulePayload> for RulePayload {
        fn try_read<B: std::io::Read + std::io::Seek>(
            _: &mut B,
            _: &PayloadHeader,
            _: &mut <RulePayload as ProtocolSchema>::Context<'_>,
        ) -> Result<ReadStatus<RulePayload>, Error> {
            Err(Error::Test)
        }
    }

    impl ExtractPayloadFrom<RulePayload> for RulePayload {
        fn read<B: std::io::Read>(
            _: &mut B,
            _: &PayloadHeader,
            _: &mut <RulePayload as ProtocolSchema>::Context<'_>,
        ) -> Result<RulePayload, Error> {
            Err(Error::Test)
        }
    }

    impl PayloadDef<RulePayload> for RulePayload {}

    struct BrA;
    struct BrB;

    enum Referred {
        A(BrA),
        B(BrB),
    }

    impl PeekAs<'_, BrA> for Referred {
        type Peeked = BrA;
        fn peek_as(&self) -> Option<&Self::Peeked> {
            match self {
                Referred::A(v) => Some(v),
                Referred::B(_) => None,
            }
        }
    }
    impl PeekAs<'_, BrB> for Referred {
        type Peeked = BrB;
        fn peek_as(&self) -> Option<&Self::Peeked> {
            match self {
                Referred::A(_) => None,
                Referred::B(v) => Some(v),
            }
        }
    }

    #[test]
    fn peeked_blocks_helpers_work() {
        let arr = vec![Referred::A(BrA), Referred::B(BrB)];
        let peeked = crate::PeekedBlocksDef::new(&arr);

        assert_eq!(peeked.len(), 2);
        assert!(!peeked.is_empty());
        assert!(peeked.has::<BrA>());
        assert!(peeked.has::<BrB>());
        assert!(peeked.get::<BrA>().is_some());
        assert!(peeked.get::<BrB>().is_some());
        assert!(peeked.find::<BrB, _>(|_| true).is_some());
        assert_eq!(peeked.iter_as::<BrA>().count(), 1);
        assert_eq!(peeked.iter_as::<BrB>().count(), 1);
        assert_eq!(peeked.iter().count(), 2);
        assert_eq!(peeked.as_slice().len(), 2);

        let first = peeked.first().expect("first");
        assert!(first.as_type::<BrA>().is_some());
        assert!(first.as_type::<BrB>().is_none());
    }

    #[test]
    fn peeked_block_accessors_and_into_iter_work() {
        let arr = vec![Referred::A(BrA), Referred::B(BrB)];
        let peeked = crate::PeekedBlocksDef::new(&arr);
        let first = peeked.first().expect("first");

        assert!(std::ptr::eq(first.as_referred(), &*first));

        let collected = peeked.into_iter().count();
        assert_eq!(collected, 2);
    }

    #[test]
    fn rules_add_duplicate_and_remove_behaviour() {
        let mut rules = RulesDef::<RuleBlock, RuleBlock, RulePayload, RulePayload>::default();

        rules
            .add_rule(RuleDef::Ignored(RuleFnDef::Static(|_| {})))
            .expect("first ignored");
        assert!(matches!(
            rules.add_rule(RuleDef::Ignored(RuleFnDef::Static(|_| {}))),
            Err(Error::RuleDuplicate)
        ));

        rules
            .add_rule(RuleDef::IgnoredControl(RuleFnDef::Static(|_, _| {
                Ok(IgnoredAction::Continue)
            })))
            .expect("first ignored control");
        assert!(matches!(
            rules.add_rule(RuleDef::IgnoredControl(RuleFnDef::Static(|_, _| {
                Ok(IgnoredAction::Continue)
            }))),
            Err(Error::RuleDuplicate)
        ));

        rules
            .add_rule(RuleDef::NextPacket(RuleFnDef::Static(|_, _| Ok(()))))
            .expect("first next packet");
        assert!(matches!(
            rules.add_rule(RuleDef::NextPacket(RuleFnDef::Static(|_, _| Ok(())))),
            Err(Error::RuleDuplicate)
        ));

        rules
            .add_rule(RuleDef::Prefilter(RuleFnDef::Static(|_| true)))
            .expect("first prefilter");
        assert!(matches!(
            rules.add_rule(RuleDef::Prefilter(RuleFnDef::Static(|_| true))),
            Err(Error::RuleDuplicate)
        ));

        rules.remove_rule(RuleDefId::Ignored);
        rules
            .add_rule(RuleDef::Ignored(RuleFnDef::Static(|_| {})))
            .expect("ignored can be added again after remove");

        rules.remove_rule(RuleDefId::IgnoredControl);
        rules
            .add_rule(RuleDef::IgnoredControl(RuleFnDef::Static(|_, _| {
                Ok(IgnoredAction::Continue)
            })))
            .expect("ignored control can be added again after remove");

        rules.remove_rule(RuleDefId::NextPacket);
        rules
            .add_rule(RuleDef::NextPacket(RuleFnDef::Static(|_, _| Ok(()))))
            .expect("next packet can be added again after remove");

        rules
            .add_rule(RuleDef::FilterPayload(RuleFnDef::Static(|_| true)))
            .expect("first payload filter");
        assert!(matches!(
            rules.add_rule(RuleDef::FilterPayload(RuleFnDef::Static(|_| true))),
            Err(Error::RuleDuplicate)
        ));

        rules
            .add_rule(RuleDef::FilterPacket(RuleFnDef::Static(|_| true)))
            .expect("first packet filter");
        assert!(matches!(
            rules.add_rule(RuleDef::FilterPacket(RuleFnDef::Static(|_| true))),
            Err(Error::RuleDuplicate)
        ));
    }

    #[test]
    fn rules_callbacks_filter_and_ignore_paths() {
        let mut rules = RulesDef::<RuleBlock, RuleBlock, RulePayload, RulePayload>::default();

        let ignored_calls = Arc::new(AtomicUsize::new(0));
        let ignored_calls_c = ignored_calls.clone();
        rules
            .add_rule(RuleDef::Ignored(RuleFnDef::Dynamic(Box::new(move |_| {
                ignored_calls_c.fetch_add(1, Ordering::SeqCst);
            }))))
            .expect("ignored rule");

        rules
            .add_rule(RuleDef::Prefilter(RuleFnDef::Static(|blocks| {
                blocks.len() == 1
            })))
            .expect("prefilter rule");
        rules
            .add_rule(RuleDef::FilterPayload(RuleFnDef::Static(|payload| {
                payload == [1, 2, 3]
            })))
            .expect("payload rule");
        rules
            .add_rule(RuleDef::FilterPacket(RuleFnDef::Static(|packet| {
                packet.payload.is_none()
            })))
            .expect("packet rule");

        rules.ignore(&[9, 9], &mut ()).expect("ignore callback");
        assert_eq!(ignored_calls.load(Ordering::SeqCst), 1);

        let blocks_a = vec![RuleBlock::new(1)];
        assert!(rules.prefilter(&blocks_a));
        assert!(!rules.prefilter(&[]));

        assert!(rules.has_payload_filter());
        assert!(rules.filter_payload(&[1, 2, 3]));
        assert!(!rules.filter_payload(&[7, 8]));

        let packet_no_payload = PacketDef::<RuleBlock, RulePayload, RulePayload>::default();
        let packet_with_payload = PacketDef::<RuleBlock, RulePayload, RulePayload>::new(
            vec![],
            Some(RulePayload::new(1)),
        );
        assert!(rules.filter_packet(&packet_no_payload));
        assert!(!rules.filter_packet(&packet_with_payload));
    }

    #[test]
    fn rules_ignore_static_callback_path_is_called() {
        static IGNORED_STATIC_CALLS: AtomicUsize = AtomicUsize::new(0);
        fn ignored_static_cb(_: &[u8]) {
            IGNORED_STATIC_CALLS.fetch_add(1, Ordering::SeqCst);
        }

        IGNORED_STATIC_CALLS.store(0, Ordering::SeqCst);
        let mut rules = RulesDef::<RuleBlock, RuleBlock, RulePayload, RulePayload>::default();
        rules
            .add_rule(RuleDef::Ignored(RuleFnDef::Static(ignored_static_cb)))
            .expect("ignored static rule");

        rules
            .ignore(&[1, 2, 3], &mut ())
            .expect("ignore static callback");
        assert_eq!(IGNORED_STATIC_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn rules_ignored_control_can_continue_or_stop_with_context() {
        struct IgnoreCtx {
            total: usize,
            limit: usize,
            next_results: usize,
        }

        struct ControlledPayload;

        impl ProtocolSchema for ControlledPayload {
            type Context<'a> = IgnoreCtx;
        }

        impl WriteVectoredMutTo for ControlledPayload {
            fn slices(&mut self, _: &mut Self::Context<'_>) -> std::io::Result<IoSlices<'_>> {
                Err(std::io::Error::other("controlled payload slices test stub"))
            }
        }

        impl WriteMutTo for ControlledPayload {
            fn write<T: std::io::Write>(
                &mut self,
                _: &mut T,
                _: &mut Self::Context<'_>,
            ) -> std::io::Result<usize> {
                Err(std::io::Error::other("controlled payload write test stub"))
            }

            fn write_all<T: std::io::Write>(
                &mut self,
                _: &mut T,
                _: &mut Self::Context<'_>,
            ) -> std::io::Result<()> {
                Err(std::io::Error::other(
                    "controlled payload write_all test stub",
                ))
            }
        }

        impl crate::PayloadSignature for ControlledPayload {
            fn sig(&self) -> ByteBlock {
                ByteBlock::Len4(*b"CTRL")
            }
        }

        impl crate::PayloadEncodeReferred for ControlledPayload {
            fn encode(&self, _: &mut Self::Context<'_>) -> std::io::Result<Option<&[u8]>> {
                Err(std::io::Error::other(
                    "controlled payload encode_referred test stub",
                ))
            }
        }

        impl crate::PayloadHooks for ControlledPayload {}

        impl crate::PayloadEncode for ControlledPayload {
            fn encode(&self, _: &mut Self::Context<'_>) -> std::io::Result<Vec<u8>> {
                Err(std::io::Error::other("controlled payload encode test stub"))
            }
        }

        impl crate::PayloadCrc for ControlledPayload {
            fn crc(&self, _: &mut Self::Context<'_>) -> std::io::Result<ByteBlock> {
                Err(std::io::Error::other("controlled payload crc test stub"))
            }

            fn crc_size() -> usize {
                0
            }
        }

        impl crate::PayloadSize for ControlledPayload {
            fn size(&self, _: &mut Self::Context<'_>) -> std::io::Result<u64> {
                Err(std::io::Error::other("controlled payload size test stub"))
            }
        }

        impl crate::PayloadInnerDef for ControlledPayload {}

        impl TryExtractPayloadFromBuffered<ControlledPayload> for ControlledPayload {
            fn try_read<B: std::io::BufRead>(
                _: &mut B,
                _: &PayloadHeader,
                _: &mut <ControlledPayload as ProtocolSchema>::Context<'_>,
            ) -> Result<ReadStatus<ControlledPayload>, Error> {
                Err(Error::Test)
            }
        }

        impl TryExtractPayloadFrom<ControlledPayload> for ControlledPayload {
            fn try_read<B: std::io::Read + std::io::Seek>(
                _: &mut B,
                _: &PayloadHeader,
                _: &mut <ControlledPayload as ProtocolSchema>::Context<'_>,
            ) -> Result<ReadStatus<ControlledPayload>, Error> {
                Err(Error::Test)
            }
        }

        impl ExtractPayloadFrom<ControlledPayload> for ControlledPayload {
            fn read<B: std::io::Read>(
                _: &mut B,
                _: &PayloadHeader,
                _: &mut <ControlledPayload as ProtocolSchema>::Context<'_>,
            ) -> Result<ControlledPayload, Error> {
                Err(Error::Test)
            }
        }

        impl PayloadDef<ControlledPayload> for ControlledPayload {}

        let mut rules = RulesDef::<
            RuleBlock,
            RuleBlock,
            ControlledPayload,
            ControlledPayload,
            IgnoreCtx,
        >::default();
        rules
            .add_rule(RuleDef::IgnoredControl(RuleFnDef::Static(|bytes, ctx| {
                ctx.total += bytes.len();
                if ctx.total > ctx.limit {
                    Ok(IgnoredAction::Stop)
                } else {
                    Ok(IgnoredAction::Continue)
                }
            })))
            .expect("ignored control rule");
        rules
            .add_rule(RuleDef::NextPacket(RuleFnDef::Static(|_, ctx| {
                ctx.next_results += 1;
                Ok(())
            })))
            .expect("next packet rule");

        let mut ctx = IgnoreCtx {
            total: 0,
            limit: 4,
            next_results: 0,
        };
        rules.ignore(&[1, 2], &mut ctx).expect("first chunk");
        assert_eq!(ctx.total, 2);
        assert!(matches!(
            rules.ignore(&[3, 4, 5], &mut ctx),
            Err(Error::IgnoredDataRejected)
        ));
        assert_eq!(ctx.total, 5);
        rules
            .next_packet(&NextPacket::NotFound, &mut ctx)
            .expect("next packet callback");
        assert_eq!(ctx.next_results, 1);
    }

    #[test]
    fn trait_required_stub_methods_return_explicit_errors() {
        let mut buffered = Cursor::new(Vec::<u8>::new());
        let mut stream = Cursor::new(Vec::<u8>::new());
        let payload_header = PayloadHeader {
            sig: ByteBlock::Len4([0, 0, 0, 0]),
            crc: ByteBlock::Len4([0, 0, 0, 0]),
            len: 0,
        };

        let block = RuleBlock::new(1);
        assert_eq!(<RuleBlock as crate::Size>::size(&block), 1);
        assert!(block.write(&mut Vec::new()).is_err());
        assert!(block.write_all(&mut Vec::new()).is_err());
        assert!(block.slices().is_err());
        assert!(matches!(
            <RuleBlock as TryReadFromBuffered>::try_read::<_, ()>(&mut buffered),
            Err(Error::Test)
        ));
        assert!(matches!(
            <RuleBlock as TryReadFrom>::try_read::<_, ()>(&mut stream),
            Err(Error::Test)
        ));
        assert!(matches!(
            <RuleBlock as ReadFrom>::read::<_, ()>(&mut buffered),
            Err(Error::Test)
        ));
        assert!(matches!(
            <RuleBlock as ReadBlockFrom>::read(&mut buffered, false),
            Err(Error::Test)
        ));
        assert!(matches!(
            <RuleBlock as ReadBlockFromSlice>::read_from_slice(&[], false),
            Err(Error::Test)
        ));

        let mut payload = RulePayload::new(1);
        assert_eq!(
            <RulePayload as crate::PayloadSignature>::sig(&payload).as_slice(),
            b"RULS"
        );
        assert!(<RulePayload as crate::PayloadHooks>::before_encode(&mut payload).is_err());
        assert!(<RulePayload as crate::PayloadHooks>::after_decode(&mut payload).is_err());
        assert!(<RulePayload as crate::PayloadEncode>::encode(&payload, &mut ()).is_err());
        assert!(<RulePayload as crate::PayloadEncodeReferred>::encode(&payload, &mut ()).is_err());
        assert!(<RulePayload as crate::PayloadCrc>::crc(&payload, &mut ()).is_err());
        assert!(<RulePayload as crate::PayloadSize>::size(&payload, &mut ()).is_err());
        assert!(payload.write(&mut Vec::new(), &mut ()).is_err());
        assert!(payload.write_all(&mut Vec::new(), &mut ()).is_err());
        assert!(payload.slices(&mut ()).is_err());
        assert!(matches!(
            <RulePayload as TryExtractPayloadFromBuffered<RulePayload>>::try_read(
                &mut buffered,
                &payload_header,
                &mut ()
            ),
            Err(Error::Test)
        ));
        assert!(matches!(
            <RulePayload as TryExtractPayloadFrom<RulePayload>>::try_read(
                &mut stream,
                &payload_header,
                &mut ()
            ),
            Err(Error::Test)
        ));
        assert!(matches!(
            <RulePayload as ExtractPayloadFrom<RulePayload>>::read(
                &mut buffered,
                &payload_header,
                &mut ()
            ),
            Err(Error::Test)
        ));
    }
}