Skip to main content

layline_core/
field.rs

1//! Field tables for layouts.
2use crate::Extent;
3use crate::row::row;
4
5row! {
6    /// One field of a layout.
7    FieldDef<'a> {
8        /// The field's name.
9        name: &'a str,
10        /// The field's position and width.
11        extent: Extent,
12    }
13}
14
15row! {
16    /// A field's Rust type, joined to its [`FieldDef`] by name.
17    TypeDef<'a> {
18        /// The field's name.
19        field: &'a str,
20        /// The type as written in the source.
21        ty: &'a str,
22    }
23}
24
25row! {
26    /// A parameter of a [`Message`](crate::Message) whose `Ctx` is not `()`.
27    ParamDef<'a> {
28        /// The name. Rows refer to it as they would to a field.
29        name: &'a str,
30        /// The type as written in the source.
31        ty: &'a str,
32    }
33}
34
35/// The unit of a [`StatedDef`].
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum StatedUnit {
39    /// `#[at(bit = N)]`.
40    Bit,
41    /// `#[at(byte = N)]`.
42    Byte,
43}
44
45impl StatedUnit {
46    /// Bits per unit.
47    #[must_use]
48    pub const fn bits(self) -> u64 {
49        match self {
50            StatedUnit::Bit => 1,
51            StatedUnit::Byte => 8,
52        }
53    }
54
55    /// The unit's name in `#[at(..)]`.
56    #[must_use]
57    pub const fn name(self) -> &'static str {
58        match self {
59            StatedUnit::Bit => "bit",
60            StatedUnit::Byte => "byte",
61        }
62    }
63}
64
65row! {
66    /// A field position from `#[at(..)]`, as a standard numbers it.
67    ///
68    /// Counted from the container's first bit after `order = msb` mirroring, so it matches
69    /// [`FieldDef`]. Stored in the declared unit if the position divides evenly, and in bits otherwise.
70    StatedDef<'a> {
71        /// The field's name.
72        field: &'a str,
73        /// The unit of [`pos`](Self::pos).
74        unit: StatedUnit,
75        /// The position, in [`unit`](Self::unit)s.
76        pos: u64,
77    }
78}
79
80row! {
81    /// A `#[magic(..)]` field and its constant.
82    ConstDef<'a> {
83        /// The field's name.
84        field: &'a str,
85        /// The constant's bytes, in wire order.
86        bytes: &'a [u8],
87    }
88}
89
90row! {
91    /// The values a `#[range(..)]` field allows.
92    RangeDef<'a> {
93        /// The field's name.
94        field: &'a str,
95        /// The lowest allowed value.
96        lo: i64,
97        /// The highest allowed value.
98        hi: i64,
99    }
100}
101
102impl StatedDef<'_> {
103    /// The position in bits.
104    #[must_use]
105    pub const fn bits(self) -> u64 {
106        self.pos * self.unit.bits()
107    }
108}
109
110/// Why a field table does not exactly cover its container.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112#[non_exhaustive]
113pub enum LayoutError {
114    /// A field does not start where the previous one ended.
115    Gap {
116        /// Index of the field.
117        field: usize,
118        /// Where the previous field ended.
119        expected_start: u64,
120        /// Where this field starts.
121        actual_start: u64,
122    },
123    /// The fields do not end at the container's last bit.
124    Short {
125        /// Where the fields end.
126        end: u64,
127        /// The container's width in bits.
128        total_bits: u64,
129    },
130}
131
132impl core::fmt::Display for LayoutError {
133    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
134        match self {
135            Self::Gap { field, expected_start, actual_start } => write!(
136                f,
137                "field {field} starts at bit {actual_start}, but the previous field ends at bit \
138                 {expected_start}"
139            ),
140            Self::Short { end, total_bits } => {
141                write!(f, "the fields end at bit {end} of a {total_bits}-bit container")
142            }
143        }
144    }
145}
146
147impl core::error::Error for LayoutError {}
148
149/// Check that `fields`, in order, cover exactly `total` bits.
150///
151/// # Errors
152///
153/// [`LayoutError::Gap`] at the first field that does not start where the previous one ended.
154/// [`LayoutError::Short`] if the fields do not end at `total`.
155pub const fn check_layout(fields: &[FieldDef<'_>], total: u64) -> Result<(), LayoutError> {
156    let mut at = 0u64;
157    let mut i = 0;
158    while i < fields.len() {
159        let extent = fields[i].extent;
160        if extent.start() != at {
161            return Err(LayoutError::Gap {
162                field: i,
163                expected_start: at,
164                actual_start: extent.start(),
165            });
166        }
167        at = extent.end();
168        i += 1;
169    }
170    if at != total {
171        return Err(LayoutError::Short { end: at, total_bits: total });
172    }
173    Ok(())
174}
175
176/// The width of the field named `name`, or zero if there is none.
177///
178/// ```
179/// use layline_core::{Extent, table::{FieldDef, field_width}};
180///
181/// const FIELDS: &[FieldDef<'_>] = &[
182///     FieldDef::new("kind", Extent::new(0, 3)),
183///     FieldDef::new("n_entries", Extent::new(3, 5)),
184/// ];
185/// const N: u32 = field_width(FIELDS, "n_entries");
186/// assert_eq!(N, 5);
187/// assert_eq!(field_width(FIELDS, "absent"), 0);
188/// ```
189#[must_use]
190pub const fn field_width(fields: &[FieldDef<'_>], name: &str) -> u32 {
191    let mut i = 0;
192    while i < fields.len() {
193        if str_eq(fields[i].name, name) {
194            return fields[i].extent.width();
195        }
196        i += 1;
197    }
198    0
199}
200
201/// Whether the field named `name` has the type `ty`.
202///
203/// ```
204/// use layline_core::table::{TypeDef, type_is};
205///
206/// const TYPES: &[TypeDef<'_>] = &[
207///     TypeDef::new("seq_flag", "bool"),
208///     TypeDef::new("n_entries", "u8"),
209/// ];
210/// const IS_FLAG: bool = type_is(TYPES, "seq_flag", "bool");
211/// assert!(IS_FLAG);
212/// assert!(!type_is(TYPES, "n_entries", "bool"));
213/// assert!(!type_is(TYPES, "absent", "bool"));
214/// ```
215#[must_use]
216pub const fn type_is(types: &[TypeDef<'_>], name: &str, ty: &str) -> bool {
217    let mut i = 0;
218    while i < types.len() {
219        if str_eq(types[i].field, name) {
220            return str_eq(types[i].ty, ty);
221        }
222        i += 1;
223    }
224    false
225}
226
227const fn str_eq(a: &str, b: &str) -> bool {
228    let (a, b) = (a.as_bytes(), b.as_bytes());
229    if a.len() != b.len() {
230        return false;
231    }
232    let mut i = 0;
233    while i < a.len() {
234        if a[i] != b[i] {
235            return false;
236        }
237        i += 1;
238    }
239    true
240}
241
242/// [`check_layout`] as a panic, for a `const` block in generated code.
243pub const fn assert_layout(fields: &[FieldDef<'_>], total: u64) {
244    assert!(
245        check_layout(fields, total).is_ok(),
246        "layout fields do not exactly cover the container"
247    );
248}
249
250/// A fixed-size type whose named fields cover every bit.
251///
252/// `FIELDS` passes [`check_layout`]: it ascends from bit zero to `WIRE_BYTES * 8`, with no gaps or overlaps.
253#[diagnostic::on_unimplemented(
254    message = "`{Self}` is not a fixed-size layout",
255    label = "not a `#[derive(Layout)]` type",
256    note = "`#[bytes(N)]` fields and `Dispatch` payloads need a fixed size. \
257            Add `#[derive(Layout)]`, or use `#[message]` for a `#[derive(Message)]` type"
258)]
259pub trait Layout: Sized {
260    /// The type's name, as printed in the audit.
261    const NAME: &'static str;
262
263    /// Size on the wire, in bytes.
264    const WIRE_BYTES: usize;
265
266    /// Every field, in ascending order, covering `WIRE_BYTES * 8` bits.
267    const FIELDS: &'static [crate::table::FieldDef<'static>];
268
269    /// Whether the inherent `decode` returns a `Result`, as it does when the layout checks its own bytes.
270    ///
271    /// Read by the parent, since a derive cannot see a field's type.
272    #[doc(hidden)]
273    const DECODE_FALLIBLE: bool = false;
274
275    /// Decode from a slice.
276    ///
277    /// # Errors
278    ///
279    /// [`Short`](crate::ParseError::Short) if the slice is not [`WIRE_BYTES`](Self::WIRE_BYTES)
280    /// long. Otherwise a failed `#[magic]`, `#[checksum]` or `#[range]`.
281    fn decode_slice(bytes: &[u8]) -> Result<Self, crate::ParseError>;
282
283    /// Append the [`WIRE_BYTES`](Self::WIRE_BYTES) bytes to `out`.
284    ///
285    /// # Errors
286    ///
287    /// [`Overflow`](crate::Overflow) if there is no room.
288    fn encode_into<B: crate::Buffer>(&self, out: &mut B) -> Result<(), crate::Overflow>;
289
290    /// The low bits owned by an enclosing dispatcher, or zero.
291    ///
292    /// A `#[dispatch(.., prefix = K)]` catalogue checks that every arm agrees.
293    const PREFIX_BITS: u32 = 0;
294
295    /// The [`StatedDef`] rows, in declaration order.
296    const STATED: &'static [crate::table::StatedDef<'static>] = &[];
297
298    /// The type of each field, in declaration order.
299    ///
300    /// Empty when every field is a plain integer of its declared width.
301    const TYPES: &'static [crate::table::TypeDef<'static>] = &[];
302
303    /// The `#[magic(..)]` fields, in declaration order.
304    const CONSTANTS: &'static [crate::table::ConstDef<'static>] = &[];
305
306    /// The `#[range(..)]` bounds, in declaration order.
307    const RANGES: &'static [crate::table::RangeDef<'static>] = &[];
308
309    /// The bytes each `#[checksum(..)]` field covers, in declaration order.
310    const COVERED: &'static [crate::table::CoverDef<'static>] = &[];
311
312    /// The audit records for this layout.
313    fn audit() -> crate::audit::LayoutRecords<'static> {
314        crate::audit::layout(Self::NAME, Self::WIRE_BYTES as u64 * 8, Self::FIELDS)
315            .stated(Self::STATED)
316            .types(Self::TYPES)
317            .constants(Self::CONSTANTS)
318            .ranges(Self::RANGES)
319            .covering(Self::COVERED)
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    const GOOD: &[FieldDef<'_>] = &[
328        FieldDef::new("a", Extent::new(0, 2)),
329        FieldDef::new("b", Extent::new(2, 5)),
330        FieldDef::new("c", Extent::new(7, 63)),
331    ];
332
333    #[test]
334    fn a_tiled_layout_passes() {
335        assert_eq!(check_layout(GOOD, 70), Ok(()));
336    }
337
338    #[test]
339    fn a_gap_is_named() {
340        let holey = &[FieldDef::new("a", Extent::new(0, 2)), FieldDef::new("b", Extent::new(3, 5))];
341        assert_eq!(
342            check_layout(holey, 8),
343            Err(LayoutError::Gap { field: 1, expected_start: 2, actual_start: 3 })
344        );
345    }
346
347    #[test]
348    fn a_short_layout_is_named() {
349        assert_eq!(check_layout(GOOD, 72), Err(LayoutError::Short { end: 70, total_bits: 72 }));
350    }
351}