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 /// Decode from the first [`WIRE_BYTES`](Self::WIRE_BYTES) bytes of `bytes`, ignoring the rest.
284 /// Returns the value and the bytes used, always `WIRE_BYTES`.
285 ///
286 /// # Errors
287 ///
288 /// [`Short`](crate::ParseError::Short) if `bytes` is shorter than the layout. Otherwise as
289 /// [`decode_slice`](Self::decode_slice).
290 fn decode_prefix(bytes: &[u8]) -> Result<(Self, usize), crate::ParseError> {
291 match bytes.get(..Self::WIRE_BYTES) {
292 Some(head) => Self::decode_slice(head).map(|value| (value, Self::WIRE_BYTES)),
293 None => Err(crate::ParseError::Short {
294 need_bytes: Self::WIRE_BYTES,
295 got_bytes: bytes.len(),
296 at: 0,
297 }),
298 }
299 }
300
301 /// Append the [`WIRE_BYTES`](Self::WIRE_BYTES) bytes to `out`.
302 ///
303 /// # Errors
304 ///
305 /// [`Overflow`](crate::Overflow) if there is no room.
306 fn encode_into<B: crate::Buffer>(&self, out: &mut B) -> Result<(), crate::Overflow>;
307
308 /// The low bits owned by an enclosing dispatcher, or zero.
309 ///
310 /// A `#[dispatch(.., prefix = K)]` catalogue checks that every arm agrees.
311 const PREFIX_BITS: u32 = 0;
312
313 /// The [`StatedDef`] rows, in declaration order.
314 const STATED: &'static [crate::table::StatedDef<'static>] = &[];
315
316 /// The type of each field, in declaration order.
317 ///
318 /// Empty when every field is a plain integer of its declared width.
319 const TYPES: &'static [crate::table::TypeDef<'static>] = &[];
320
321 /// The `#[magic(..)]` fields, in declaration order.
322 const CONSTANTS: &'static [crate::table::ConstDef<'static>] = &[];
323
324 /// The `#[range(..)]` bounds, in declaration order.
325 const RANGES: &'static [crate::table::RangeDef<'static>] = &[];
326
327 /// The bytes each `#[checksum(..)]` field covers, in declaration order.
328 const COVERED: &'static [crate::table::CoverDef<'static>] = &[];
329
330 /// The audit records for this layout.
331 fn audit() -> crate::audit::LayoutRecords<'static> {
332 crate::audit::layout(Self::NAME, Self::WIRE_BYTES as u64 * 8, Self::FIELDS)
333 .stated(Self::STATED)
334 .types(Self::TYPES)
335 .constants(Self::CONSTANTS)
336 .ranges(Self::RANGES)
337 .covering(Self::COVERED)
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344
345 const GOOD: &[FieldDef<'_>] = &[
346 FieldDef::new("a", Extent::new(0, 2)),
347 FieldDef::new("b", Extent::new(2, 5)),
348 FieldDef::new("c", Extent::new(7, 63)),
349 ];
350
351 #[test]
352 fn a_tiled_layout_passes() {
353 assert_eq!(check_layout(GOOD, 70), Ok(()));
354 }
355
356 #[test]
357 fn a_gap_is_named() {
358 let holey = &[FieldDef::new("a", Extent::new(0, 2)), FieldDef::new("b", Extent::new(3, 5))];
359 assert_eq!(
360 check_layout(holey, 8),
361 Err(LayoutError::Gap { field: 1, expected_start: 2, actual_start: 3 })
362 );
363 }
364
365 #[test]
366 fn a_short_layout_is_named() {
367 assert_eq!(check_layout(GOOD, 72), Err(LayoutError::Short { end: 70, total_bits: 72 }));
368 }
369}