brec/traits/props/mod.rs
1mod byte_block;
2
3pub use byte_block::*;
4
5use crate::payload::{PayloadEncode, PayloadEncodeReferred, PayloadHooks};
6
7/// Trait for types that provide a static 4-byte signature.
8///
9/// Used for identifying or tagging structures in a binary format.
10pub trait SignatureU32 {
11 /// Returns a reference to a static 4-byte signature.
12 fn sig() -> &'static [u8; 4];
13}
14
15/// Trait for types that can produce a CRC32 checksum.
16///
17/// This typically includes part of or all of the internal state of the struct.
18pub trait CrcU32 {
19 /// Computes a CRC32 checksum over the relevant data and returns it as 4 bytes (little-endian).
20 fn crc(&self) -> [u8; 4];
21}
22
23/// Trait for payload types that support CRC calculation.
24///
25/// This trait requires that the type implements:
26/// - `PayloadEncode`: the main payload encoding logic
27/// - `PayloadEncodeReferred`: possibly optimized or referred encoding
28/// - `PayloadHooks`: any pre/post encode hooks
29///
30/// The CRC is always returned as a `ByteBlock::Len4`.
31pub trait PayloadCrc
32where
33 Self: PayloadEncode + PayloadHooks + PayloadEncodeReferred,
34{
35 /// Computes CRC32 of the encoded payload.
36 ///
37 /// If referred encoding is available, it is used; otherwise, regular encoding is used.
38 ///
39 /// # Returns
40 /// A 4-byte `ByteBlock` containing the CRC checksum.
41 fn crc(&self) -> std::io::Result<ByteBlock> {
42 let mut hasher = crc32fast::Hasher::new();
43 if let Some(bytes) = PayloadEncodeReferred::encode(self)? {
44 hasher.update(bytes);
45 } else {
46 hasher.update(&PayloadEncode::encode(self)?);
47 }
48 Ok(ByteBlock::Len4(hasher.finalize().to_le_bytes()))
49 }
50 fn crc_size() -> usize {
51 4
52 }
53}
54
55/// Trait for types that can return a payload signature dynamically.
56///
57/// Signature is returned as a `ByteBlock`.
58pub trait PayloadSignature {
59 /// Returns the dynamic payload signature as a byte block.
60 fn sig(&self) -> ByteBlock;
61}
62
63/// Trait for types that define a static payload signature.
64///
65/// Signature is returned as a `ByteBlock` and is constant for the type.
66pub trait StaticPayloadSignature {
67 /// Returns the static signature as a byte block.
68 fn ssig() -> ByteBlock;
69}
70
71/// Trait for types with a known, constant serialized size.
72pub trait StaticSize {
73 /// Returns the fixed size (in bytes) of the type.
74 fn ssize() -> u64;
75}
76
77/// Trait for types that can report their serialized size at runtime.
78pub trait Size {
79 /// Returns the size (in bytes) of the instance.
80 fn size(&self) -> u64;
81}
82
83/// Trait for payload types that return size as a `Result`.
84///
85/// This accounts for I/O or encoding-related failures during size calculation.
86pub trait PayloadSize {
87 /// Returns the total size (in bytes) of the payload.
88 ///
89 /// # Errors
90 /// Returns an I/O error if size computation fails.
91 fn size(&self) -> std::io::Result<u64>;
92}