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
mod header;
mod read;
mod reader;
mod referred;
mod rules;
mod write;

pub use header::*;
pub use reader::*;
pub use referred::*;
pub use rules::*;

use crate::*;

use std::marker::PhantomData;

/// Defines a fully parsed block type.
///
/// Required for reading, writing, size computation, and vectored I/O.
pub trait BlockReferredDef<B: BlockDef>: ReadBlockFromSlice + Size + Sized + Into<B> {}

/// Defines a block that refers to slices of existing memory (zero-copy).
///
/// This trait is commonly used for fast inspection or filtering without decoding full blocks.
/// It must support reading from a slice and conversion back to the owning `BlockDef` type.
pub trait BlockDef:
    ReadBlockFrom + ReadFrom + TryReadFrom + TryReadFromBuffered + WriteTo + WriteVectoredTo + Size
{
}

/// Defines the actual inner payload object used in packets.
///
/// Includes encoding, CRC, size, hooks, and full write logic (including headers).
pub trait PayloadInnerDef:
    Sized
    + ProtocolSchema
    + PayloadEncode
    + PayloadHooks
    + PayloadEncodeReferred
    + PayloadSize
    + PayloadCrc
    + PayloadSignature
    // In code generator will be forced usage of WritePayloadWithHeaderTo
    + WriteMutTo
    // In code generator will be forced usage of WriteVectoredPayloadWithHeaderTo
    + WriteVectoredMutTo
{
}

/// Defines the outer container responsible for extracting a payload of a given `Inner` type.
pub trait PayloadDef<Inner: PayloadInnerDef>:
    ExtractPayloadFrom<Inner> + TryExtractPayloadFrom<Inner> + TryExtractPayloadFromBuffered<Inner>
{
}

/// Represents the result of a filtered packet inspection.
///
/// Used by `PacketDef::filtered()` to indicate whether a packet should be accepted,
/// denied, or postponed due to incomplete data.
pub enum LookInStatus<T> {
    /// The packet was accepted and returned, along with the number of bytes consumed.
    Accepted(usize, T),

    /// The packet was explicitly denied by the rule set.
    Denied(usize),

    /// Not enough data available to complete the operation. Indicates required amount.
    NotEnoughData(usize),
}

/// A complete parsed packet structure with block list and optional payload.
///
/// This structure is the result of reading a full `brec` packet, including:
/// - A vector of parsed blocks implementing `BlockDef`
/// - An optional payload implementing `PayloadInnerDef`
///
/// # Type Parameters
/// - `B`: Block type (fully parsed)
/// - `P`: Payload definition handler (extractor, size, etc.)
/// - `Inner`: Actual payload instance type
pub struct PacketDef<B: BlockDef, P: PayloadDef<Inner>, Inner: PayloadInnerDef> {
    /// Fully parsed blocks stored in the packet.
    pub blocks: Vec<B>,

    /// Optional decoded payload.
    pub payload: Option<Inner>,

    /// Internal marker for payload definition type.
    _pi: PhantomData<P>,
}

impl<B: BlockDef, P: PayloadDef<Inner>, Inner: PayloadInnerDef> ProtocolSchema
    for PacketDef<B, P, Inner>
{
    type Context<'a> = <Inner as ProtocolSchema>::Context<'a>;
}

impl<B: BlockDef, P: PayloadDef<Inner>, Inner: PayloadInnerDef> PacketDef<B, P, Inner> {
    /// Creates a new packet from given blocks and optional payload.
    pub fn new(blocks: Vec<B>, payload: Option<Inner>) -> Self {
        Self {
            blocks,
            payload,
            _pi: PhantomData,
        }
    }

    /// Attempts to read and filter a packet from a stream using the provided rules.
    ///
    /// This function:
    /// - Reads the `PacketHeader`
    /// - Loads all blocks into memory
    /// - Applies the prefilter rule
    /// - Optionally parses and filters the payload
    /// - Returns the final result via `LookInStatus`
    ///
    /// # Limitations
    /// - Does **not** refill the stream buffer
    /// - Will fail if the entire packet is not already in the stream
    ///
    /// # Returns
    /// - `Accepted(bytes, packet)` - if all filters passed
    /// - `Denied(bytes)` - if blocked by rules
    /// - `NotEnoughData(bytes)` - if more input is needed
    ///
    /// # Errors
    /// - Propagates all decoding and parsing errors from blocks and payload
    pub fn filtered<R, BR>(
        reader: &mut R,
        rules: &RulesDef<B, BR, P, Inner>,
        ctx: &mut <Inner as ProtocolSchema>::Context<'_>,
    ) -> Result<LookInStatus<PacketDef<B, P, Inner>>, Error>
    where
        R: std::io::Read + std::io::Seek,
        BR: BlockReferredDef<B>,
        Self: Sized,
    {
        let header = <PacketHeader as ReadFrom>::read::<_, Inner>(reader)?;
        let mut read = 0usize;
        let mut blocks = Vec::new();
        let blocks_len = header.blocks_len as usize;
        if blocks_len > 0 {
            let mut blocks_buffer = vec![0; blocks_len];
            reader.read_exact(&mut blocks_buffer)?;
            loop {
                let blk =
                    <BR as ReadBlockFromSlice>::read_from_slice(&blocks_buffer[read..], false)?;
                read += blk.size() as usize;
                blocks.push(blk);
                if read == blocks_len {
                    break;
                }
            }
        }
        let packet_size = header.size as usize;
        if !rules.prefilter(&blocks) {
            if header.payload {
                let to_skip = packet_size.saturating_sub(blocks_len);
                if to_skip > 0 {
                    reader.seek(std::io::SeekFrom::Current(to_skip as i64))?;
                }
            }
            return Ok(LookInStatus::Denied(packet_size));
        }
        let pkg = if header.payload {
            let payload_header = <PayloadHeader as ReadFrom>::read::<_, Inner>(reader)?;
            header.validate_payload(&payload_header)?;
            if rules.has_payload_filter() {
                let mut payload_buffer = vec![0; payload_header.payload_len()];
                reader.read_exact(&mut payload_buffer)?;
                if !rules.filter_payload(&payload_buffer) {
                    return Ok(LookInStatus::Denied(packet_size));
                }
                let mut payload_reader = std::io::Cursor::new(payload_buffer);
                match <P as TryExtractPayloadFromBuffered<Inner>>::try_read(
                    &mut payload_reader,
                    &payload_header,
                    ctx,
                ) {
                    Ok(ReadStatus::Success(payload)) => PacketDef::new(
                        blocks.into_iter().map(|blk| blk.into()).collect::<Vec<B>>(),
                        Some(payload),
                    ),
                    Ok(ReadStatus::NotEnoughData(needed)) => {
                        return Err(Error::NotEnoughData(needed as usize));
                    }
                    Err(err) => {
                        return Err(err);
                    }
                }
            } else {
                match <P as TryExtractPayloadFrom<Inner>>::try_read(reader, &payload_header, ctx) {
                    Ok(ReadStatus::Success(payload)) => PacketDef::new(
                        blocks.into_iter().map(|blk| blk.into()).collect::<Vec<B>>(),
                        Some(payload),
                    ),
                    Ok(ReadStatus::NotEnoughData(needed)) => {
                        return Err(Error::NotEnoughData(needed as usize));
                    }
                    Err(err) => {
                        return Err(err);
                    }
                }
            }
        } else {
            PacketDef::new(
                blocks.into_iter().map(|blk| blk.into()).collect::<Vec<B>>(),
                None,
            )
        };
        if !rules.filter_packet(&pkg) {
            // PacketDef marked as ignored
            Ok(LookInStatus::Denied(packet_size))
        } else {
            Ok(LookInStatus::Accepted(packet_size, pkg))
        }
    }
}

impl<B: BlockDef, P: PayloadDef<Inner>, Inner: PayloadInnerDef> Default for PacketDef<B, P, Inner> {
    /// Creates an empty `PacketDef` with no blocks and no payload.
    fn default() -> Self {
        Self {
            blocks: Vec::new(),
            payload: None,
            _pi: PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[derive(Clone, Copy)]
    enum DecodeOutcome {
        Success,
        NotEnough(u64),
        ErrInvalidLength,
        ErrCrcDismatch,
    }

    #[derive(Clone, Copy)]
    struct DecodeCtx {
        buffered: DecodeOutcome,
        stream: DecodeOutcome,
    }

    #[derive(Clone)]
    struct TestPayload(u8);

    impl ProtocolSchema for TestPayload {
        type Context<'a> = DecodeCtx;
    }

    impl PayloadHooks for TestPayload {}

    impl PayloadEncode for TestPayload {
        fn encode(&self, _: &mut Self::Context<'_>) -> std::io::Result<Vec<u8>> {
            Ok(vec![self.0])
        }
    }

    impl PayloadEncodeReferred for TestPayload {
        fn encode(&self, _: &mut Self::Context<'_>) -> std::io::Result<Option<&[u8]>> {
            Ok(Some(&[1_u8, 2_u8, 3_u8]))
        }
    }

    impl PayloadSignature for TestPayload {
        fn sig(&self) -> ByteBlock {
            ByteBlock::Len4(*b"TSTP")
        }
    }

    impl PayloadSize for TestPayload {}
    impl PayloadCrc for TestPayload {}

    impl WriteMutTo for TestPayload {
        fn write<T: std::io::Write>(
            &mut self,
            _: &mut T,
            _: &mut Self::Context<'_>,
        ) -> std::io::Result<usize> {
            Ok(0)
        }

        fn write_all<T: std::io::Write>(
            &mut self,
            _: &mut T,
            _: &mut Self::Context<'_>,
        ) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl WriteVectoredMutTo for TestPayload {
        fn slices(&mut self, _: &mut Self::Context<'_>) -> std::io::Result<IoSlices<'_>> {
            Ok(IoSlices::default())
        }
    }

    impl PayloadInnerDef for TestPayload {}

    impl TryExtractPayloadFromBuffered<TestPayload> for TestPayload {
        fn try_read<B: std::io::BufRead>(
            _: &mut B,
            _: &PayloadHeader,
            ctx: &mut <TestPayload as ProtocolSchema>::Context<'_>,
        ) -> Result<ReadStatus<TestPayload>, Error> {
            match ctx.buffered {
                DecodeOutcome::Success => Ok(ReadStatus::Success(TestPayload(7))),
                DecodeOutcome::NotEnough(needed) => Ok(ReadStatus::NotEnoughData(needed)),
                DecodeOutcome::ErrInvalidLength => Err(Error::InvalidLength),
                DecodeOutcome::ErrCrcDismatch => Err(Error::CrcDismatch),
            }
        }
    }

    impl TryExtractPayloadFrom<TestPayload> for TestPayload {
        fn try_read<B: std::io::Read + std::io::Seek>(
            _: &mut B,
            _: &PayloadHeader,
            ctx: &mut <TestPayload as ProtocolSchema>::Context<'_>,
        ) -> Result<ReadStatus<TestPayload>, Error> {
            match ctx.stream {
                DecodeOutcome::Success => Ok(ReadStatus::Success(TestPayload(9))),
                DecodeOutcome::NotEnough(needed) => Ok(ReadStatus::NotEnoughData(needed)),
                DecodeOutcome::ErrInvalidLength => Err(Error::InvalidLength),
                DecodeOutcome::ErrCrcDismatch => Err(Error::CrcDismatch),
            }
        }
    }

    impl ExtractPayloadFrom<TestPayload> for TestPayload {
        fn read<B: std::io::Read>(
            _: &mut B,
            _: &PayloadHeader,
            _: &mut <TestPayload as ProtocolSchema>::Context<'_>,
        ) -> Result<TestPayload, Error> {
            panic!("unexpected ExtractPayloadFrom::read call in packet::mod tests")
        }
    }

    impl PayloadDef<TestPayload> for TestPayload {}

    struct TestBlock;
    struct TestBlockRef;

    impl Size for TestBlock {
        fn size(&self) -> u64 {
            panic!("unexpected TestBlock::size call in packet::mod tests")
        }
    }

    impl WriteTo for TestBlock {
        fn write<T: std::io::Write>(&self, _: &mut T) -> std::io::Result<usize> {
            panic!("unexpected TestBlock::write call in packet::mod tests")
        }

        fn write_all<T: std::io::Write>(&self, _: &mut T) -> std::io::Result<()> {
            panic!("unexpected TestBlock::write_all call in packet::mod tests")
        }
    }

    impl WriteVectoredTo for TestBlock {
        fn slices(&self) -> std::io::Result<IoSlices<'_>> {
            panic!("unexpected TestBlock::slices call in packet::mod tests")
        }
    }

    impl TryReadFromBuffered for TestBlock {
        fn try_read<T: std::io::BufRead, S: ProtocolSchema>(
            _: &mut T,
        ) -> Result<ReadStatus<Self>, Error> {
            panic!("unexpected TestBlock::try_read(buffered) call in packet::mod tests")
        }
    }

    impl TryReadFrom for TestBlock {
        fn try_read<T: std::io::Read + std::io::Seek, S: ProtocolSchema>(
            _: &mut T,
        ) -> Result<ReadStatus<Self>, Error> {
            panic!("unexpected TestBlock::try_read(stream) call in packet::mod tests")
        }
    }

    impl ReadFrom for TestBlock {
        fn read<T: std::io::Read, S: ProtocolSchema>(_: &mut T) -> Result<Self, Error> {
            panic!("unexpected TestBlock::read call in packet::mod tests")
        }
    }

    impl ReadBlockFrom for TestBlock {
        fn read<T: std::io::Read>(_: &mut T, _: bool) -> Result<Self, Error> {
            panic!("unexpected TestBlock::read(block) call in packet::mod tests")
        }
    }

    impl ReadBlockFromSlice for TestBlock {
        fn read_from_slice<'a>(_: &'a [u8], _: bool) -> Result<Self, Error>
        where
            Self: 'a + Sized,
        {
            panic!("unexpected TestBlock::read_from_slice call in packet::mod tests")
        }
    }

    impl BlockDef for TestBlock {}

    impl Size for TestBlockRef {
        fn size(&self) -> u64 {
            panic!("unexpected TestBlockRef::size call in packet::mod tests")
        }
    }

    impl ReadBlockFromSlice for TestBlockRef {
        fn read_from_slice<'a>(_: &'a [u8], _: bool) -> Result<Self, Error>
        where
            Self: 'a + Sized,
        {
            panic!("unexpected TestBlockRef::read_from_slice call in packet::mod tests")
        }
    }

    impl From<TestBlockRef> for TestBlock {
        fn from(_: TestBlockRef) -> TestBlock {
            TestBlock
        }
    }

    impl BlockReferredDef<TestBlock> for TestBlockRef {}

    fn packet_bytes_with_payload(payload: bool) -> Vec<u8> {
        let mut out = Vec::new();
        if payload {
            let body = vec![1_u8, 2, 3];
            let mut hasher = crc32fast::Hasher::new();
            hasher.update(&body);
            let payload_header = PayloadHeader {
                sig: ByteBlock::Len4(*b"TSTP"),
                crc: ByteBlock::Len4(hasher.finalize().to_le_bytes()),
                len: body.len() as u32,
            }
            .as_vec();
            let header =
                PacketHeader::from_lengths(0, (payload_header.len() + body.len()) as u64, true);
            header.write_all(&mut out).expect("header");
            out.extend_from_slice(&payload_header);
            out.extend_from_slice(&body);
        } else {
            let header = PacketHeader::from_lengths(0, 0, false);
            header.write_all(&mut out).expect("header");
        }
        out
    }

    fn rules_with_payload_filter() -> RulesDef<TestBlock, TestBlockRef, TestPayload, TestPayload> {
        let mut rules = RulesDef::default();
        rules
            .add_rule(RuleDef::FilterPayload(RuleFnDef::Static(|_| true)))
            .expect("payload filter");
        rules
    }

    #[test]
    fn filtered_payload_buffered_success() {
        let mut reader = Cursor::new(packet_bytes_with_payload(true));
        let rules = rules_with_payload_filter();
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::Success,
            stream: DecodeOutcome::ErrInvalidLength,
        };
        let status = PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        )
        .expect("filtered");
        assert!(matches!(status, LookInStatus::Accepted(_, _)));
    }

    #[test]
    fn filtered_payload_buffered_not_enough() {
        let mut reader = Cursor::new(packet_bytes_with_payload(true));
        let rules = rules_with_payload_filter();
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::NotEnough(11),
            stream: DecodeOutcome::ErrInvalidLength,
        };
        let err = match PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        ) {
            Ok(_) => panic!("must be not enough"),
            Err(err) => err,
        };
        assert!(matches!(err, Error::NotEnoughData(11)));
    }

    #[test]
    fn filtered_payload_buffered_error() {
        let mut reader = Cursor::new(packet_bytes_with_payload(true));
        let rules = rules_with_payload_filter();
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::ErrInvalidLength,
            stream: DecodeOutcome::Success,
        };
        let err = match PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        ) {
            Ok(_) => panic!("must propagate decode error"),
            Err(err) => err,
        };
        assert!(matches!(err, Error::InvalidLength));
    }

    #[test]
    fn filtered_payload_stream_paths() {
        let mut reader = Cursor::new(packet_bytes_with_payload(true));
        let rules = RulesDef::<TestBlock, TestBlockRef, TestPayload, TestPayload>::default();
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::ErrCrcDismatch,
            stream: DecodeOutcome::Success,
        };
        let status = PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        )
        .expect("stream success");
        assert!(matches!(status, LookInStatus::Accepted(_, _)));

        let mut reader = Cursor::new(packet_bytes_with_payload(true));
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::ErrCrcDismatch,
            stream: DecodeOutcome::NotEnough(13),
        };
        let err = match PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        ) {
            Ok(_) => panic!("stream not enough"),
            Err(err) => err,
        };
        assert!(matches!(err, Error::NotEnoughData(13)));

        let mut reader = Cursor::new(packet_bytes_with_payload(true));
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::ErrCrcDismatch,
            stream: DecodeOutcome::ErrInvalidLength,
        };
        let err = match PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        ) {
            Ok(_) => panic!("stream error"),
            Err(err) => err,
        };
        assert!(matches!(err, Error::InvalidLength));
    }

    #[test]
    fn filtered_packet_filter_can_deny_packet() {
        let mut reader = Cursor::new(packet_bytes_with_payload(false));
        let mut rules = RulesDef::<TestBlock, TestBlockRef, TestPayload, TestPayload>::default();
        rules
            .add_rule(RuleDef::FilterPacket(RuleFnDef::Static(|_| false)))
            .expect("packet filter");
        let mut ctx = DecodeCtx {
            buffered: DecodeOutcome::Success,
            stream: DecodeOutcome::Success,
        };
        let status = PacketDef::<TestBlock, TestPayload, TestPayload>::filtered::<_, TestBlockRef>(
            &mut reader,
            &rules,
            &mut ctx,
        )
        .expect("filtered");
        assert!(matches!(status, LookInStatus::Denied(_)));
    }
}