Skip to main content

fennec_modbus/protocol/function/
size_argument.rs

1//! Data model size specifiers.
2
3use crate::protocol::codec::BitSize;
4
5/// Specifies data model alignment requirements for size validation.
6pub trait SizeArgument {
7    /// Required byte alignment: 1 for bits, 2 for words (registers).
8    const BYTE_ALIGNMENT: u8;
9
10    /// The quantity count to write on the wire for a value of type `V`.
11    fn quantity_for<V: BitSize>() -> u16;
12
13    /// Assert that the number of bytes in the payload is valid.
14    ///
15    /// If the value type is too big, the assertion would fire at compile time.
16    fn assert_valid_size<V: BitSize, const N_MAX_BYTES: u8>() {
17        const {
18            assert!(V::N_BYTES >= 1, "value type must be non-empty");
19            assert!(V::N_BYTES <= N_MAX_BYTES, "value is too large");
20            assert!(
21                V::N_BYTES.is_multiple_of(Self::BYTE_ALIGNMENT),
22                "value size must be word-aligned for register operations",
23            );
24        };
25    }
26}
27
28/// Encode number of bits (coils or discrete inputs).
29pub struct Bits;
30
31impl SizeArgument for Bits {
32    const BYTE_ALIGNMENT: u8 = 1;
33
34    fn quantity_for<V: BitSize>() -> u16 {
35        V::N_BITS
36    }
37}
38
39/// Encode number of words (registers).
40pub struct Words;
41
42impl SizeArgument for Words {
43    const BYTE_ALIGNMENT: u8 = 2;
44
45    fn quantity_for<V: BitSize>() -> u16 {
46        V::N_WORDS
47    }
48}