Skip to main content

layline_codegen/model/
field.rs

1//! Fields and their types.
2
3use alloc::format;
4use alloc::string::String;
5use alloc::vec;
6use alloc::vec::Vec;
7
8use layline_core::table::StatedUnit;
9
10use super::Coverage;
11
12/// An `#[at]` position, checked against the position computed from field widths.
13///
14/// Counted from the start of the [`LayoutDef`](crate::LayoutDef) or
15/// [`MessageDef`](crate::MessageDef) body. It catches a mistyped field width.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct Stated {
19    /// The unit of [`pos`](Self::pos).
20    pub unit: StatedUnit,
21    /// The position.
22    pub pos: u64,
23}
24
25impl Stated {
26    /// `#[at(<unit> = pos)]`.
27    #[must_use]
28    pub fn new(unit: StatedUnit, pos: u64) -> Self {
29        Self { unit, pos }
30    }
31
32    /// `#[at(bit = pos)]`.
33    #[must_use]
34    pub fn bit(pos: u64) -> Self {
35        Self { unit: StatedUnit::Bit, pos }
36    }
37
38    /// `#[at(byte = pos)]`.
39    #[must_use]
40    pub fn byte(pos: u64) -> Self {
41        Self { unit: StatedUnit::Byte, pos }
42    }
43
44    /// The position in bits.
45    #[must_use]
46    pub fn bits(self) -> u64 {
47        self.pos * self.unit.bits()
48    }
49
50    /// The `STATED` table row for the bit position `physical`.
51    ///
52    /// Uses this position's unit if it divides `physical`, and bits otherwise.
53    #[must_use]
54    pub fn published(self, physical: u64) -> Stated {
55        if physical.is_multiple_of(self.unit.bits()) {
56            Stated { unit: self.unit, pos: physical / self.unit.bits() }
57        } else {
58            Stated::bit(physical)
59        }
60    }
61
62    /// Checks the position against `at`, with no bit-order mirroring.
63    ///
64    /// # Errors
65    ///
66    /// The diagnostic text.
67    pub(crate) fn check(self, field: &str, at: u64) -> Result<(), String> {
68        if self.bits() == at {
69            return Ok(());
70        }
71        let noun = self.unit.name();
72        let landed = if self.unit == StatedUnit::Byte && !at.is_multiple_of(8) {
73            format!("bit {at} — not a byte boundary")
74        } else {
75            format!("{noun} {}", at / self.unit.bits())
76        };
77        Err(format!(
78            "field `{field}`: #[at({noun} = {})] but the solver placed it at {landed}",
79            self.pos
80        ))
81    }
82}
83
84/// A scalar field type.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86#[non_exhaustive]
87pub enum Scalar {
88    /// An unsigned integer of this many bits, at most 128: 8, 16, 32, 64 or 128 in byte mode.
89    U(u64),
90    /// A signed integer of this many bits, sign-extended.
91    I(u64),
92    /// `f32`.
93    F32,
94    /// `f64`.
95    F64,
96    /// `bool`, one bit wide.
97    Bool,
98}
99
100impl Scalar {
101    /// The width in bits.
102    #[must_use]
103    pub fn bits(self) -> u64 {
104        match self {
105            Scalar::U(n) | Scalar::I(n) => n,
106            Scalar::F32 => 32,
107            Scalar::F64 => 64,
108            Scalar::Bool => 1,
109        }
110    }
111
112    /// The smallest Rust primitive that holds this scalar, such as `u16` for 12 bits.
113    #[must_use]
114    pub fn primitive(self) -> &'static str {
115        match self {
116            Scalar::F32 => "f32",
117            Scalar::F64 => "f64",
118            Scalar::Bool => "bool",
119            Scalar::U(n) => match n {
120                0..=8 => "u8",
121                9..=16 => "u16",
122                17..=32 => "u32",
123                33..=64 => "u64",
124                _ => "u128",
125            },
126            Scalar::I(n) => match n {
127                0..=8 => "i8",
128                9..=16 => "i16",
129                17..=32 => "i32",
130                33..=64 => "i64",
131                _ => "i128",
132            },
133        }
134    }
135}
136
137/// A number taken from an earlier field: `field * scale + offset`.
138///
139/// The runtime equivalent is [`layline_core::table::By`].
140#[derive(Debug, Clone, PartialEq, Eq, Hash)]
141#[non_exhaustive]
142pub struct By {
143    /// The field to read. It must come before the field that uses it.
144    pub field: String,
145    /// The multiplier.
146    pub scale: u32,
147    /// The value added after scaling.
148    pub offset: i32,
149}
150
151impl By {
152    /// The field's value, unscaled.
153    #[must_use]
154    pub fn field(field: &str) -> Self {
155        Self { field: String::from(field), scale: 1, offset: 0 }
156    }
157
158    /// `field * scale + offset`.
159    #[must_use]
160    pub fn new(field: &str, scale: u32, offset: i32) -> Self {
161        Self { field: String::from(field), scale, offset }
162    }
163}
164
165/// A byte length.
166///
167/// [`Count`](crate::Count) counts elements instead.
168#[derive(Debug, Clone, PartialEq, Eq, Hash)]
169#[non_exhaustive]
170pub enum Len {
171    /// A fixed number of bytes.
172    Bytes(usize),
173    /// Read from an earlier field. Encode writes the field from the actual length.
174    Field {
175        /// The length field.
176        by: By,
177        /// The largest length allowed.
178        cap: Option<usize>,
179    },
180    /// Up to and including the first `terminator` byte.
181    Until {
182        /// The byte that ends the value.
183        terminator: u8,
184    },
185    /// To the end of the body.
186    Fill,
187}
188
189/// A field's type and width.
190#[derive(Debug, Clone, PartialEq, Eq, Hash)]
191#[non_exhaustive]
192pub enum Kind {
193    /// A scalar.
194    Scalar(Scalar),
195    /// An array of scalars, outermost length first: `[[f64; 3]; 2]` is `[2, 3]`.
196    Array(Scalar, Vec<usize>),
197    /// A `FieldCodec` type.
198    Codec {
199        /// The type path.
200        ty: String,
201        /// The width in bits.
202        bits: u64,
203    },
204    /// A nested layout.
205    Nested {
206        /// The type path.
207        ty: String,
208        /// The size in bytes.
209        bytes: usize,
210    },
211    /// An array of nested layouts.
212    NestedArray {
213        /// The element type path.
214        ty: String,
215        /// One element's size in bytes.
216        bytes: usize,
217        /// The number of elements.
218        len: usize,
219    },
220    /// A `VarCodec` type, whose size is read from the wire.
221    Var {
222        /// The type path.
223        ty: String,
224    },
225    /// A nested [`MessageDef`](crate::MessageDef).
226    Msg {
227        /// The type path.
228        ty: String,
229        /// Whether the Rust field is a `Box`, as a type that contains itself needs.
230        boxed: bool,
231        /// The fields passed as the message's [`needs`](crate::MessageDef::needs), in order.
232        with: Vec<String>,
233    },
234    /// A `#[checksum(..)]` field in a fixed layout.
235    ///
236    /// Messages use [`Segment::Checksum`](crate::Segment::Checksum).
237    Checksum {
238        /// The integer type.
239        repr: Scalar,
240        /// The path of the `layline::Checksum` algorithm.
241        algorithm: String,
242        /// The bytes it covers.
243        over: Coverage,
244    },
245    /// A `String`.
246    Text {
247        /// The length in bytes.
248        len: Len,
249        /// The `TextCodec` type path. `None` is UTF-8.
250        codec: Option<String>,
251    },
252}
253
254impl Kind {
255    /// `[u8; n]`.
256    ///
257    /// Same as `Array(Scalar::U(8), vec![n])`, but [`describe`](Kind::describe)s as raw bytes.
258    #[must_use]
259    pub fn bytes(n: usize) -> Self {
260        Kind::array(Scalar::U(8), n)
261    }
262
263    /// `[s; len]`.
264    #[must_use]
265    pub fn array(s: Scalar, len: usize) -> Self {
266        Kind::Array(s, vec![len])
267    }
268
269    /// `#[checksum(algorithm, over = ..)]`.
270    #[must_use]
271    pub fn checksum(repr: Scalar, algorithm: &str, over: Coverage) -> Self {
272        Kind::Checksum { repr, algorithm: String::from(algorithm), over }
273    }
274
275    /// The width in bits, or `None` if the size is read from the wire.
276    #[must_use]
277    pub fn bits(&self) -> Option<u64> {
278        Some(match self {
279            Kind::Scalar(s) | Kind::Checksum { repr: s, .. } => s.bits(),
280            Kind::Array(s, dims) => s.bits() * dims.iter().product::<usize>() as u64,
281            Kind::Codec { bits, .. } => *bits,
282            Kind::Nested { bytes, .. } => *bytes as u64 * 8,
283            Kind::NestedArray { bytes, len, .. } => (*bytes * *len) as u64 * 8,
284            Kind::Text { len: Len::Bytes(n), .. } => *n as u64 * 8,
285            Kind::Var { .. } | Kind::Msg { .. } | Kind::Text { .. } => return None,
286        })
287    }
288
289    /// [`bits`](Self::bits), or `0` if not fixed.
290    pub(crate) fn width(&self) -> u64 {
291        self.bits().unwrap_or(0)
292    }
293
294    /// Whether a count, length or offset can read its number from this field.
295    #[must_use]
296    pub fn is_integer(&self) -> bool {
297        match self {
298            Kind::Scalar(Scalar::U(_) | Scalar::I(_)) | Kind::Var { .. } | Kind::Codec { .. } => {
299                true
300            }
301            Kind::Scalar(Scalar::F32 | Scalar::F64 | Scalar::Bool)
302            | Kind::Array(..)
303            | Kind::Nested { .. }
304            | Kind::NestedArray { .. }
305            | Kind::Msg { .. }
306            | Kind::Text { .. }
307            | Kind::Checksum { .. } => false,
308        }
309    }
310
311    /// A short description for error messages, such as "an integer".
312    #[must_use]
313    pub fn describe(&self) -> &'static str {
314        match self {
315            Kind::Scalar(Scalar::U(_) | Scalar::I(_)) => "an integer",
316            Kind::Scalar(Scalar::F32 | Scalar::F64) => "a float",
317            Kind::Scalar(Scalar::Bool) => "a bool",
318            Kind::Array(Scalar::U(8), _) => "a run of raw bytes",
319            Kind::Array(..) => "an array",
320            Kind::Codec { .. } => "a `FieldCodec` value",
321            Kind::Nested { .. } => "a nested layout",
322            Kind::NestedArray { .. } => "an array of nested layouts",
323            Kind::Var { .. } => "a self-delimiting value",
324            Kind::Msg { .. } => "a nested message",
325            Kind::Checksum { .. } => "a check value over the bytes it covers",
326            Kind::Text { .. } => "text",
327        }
328    }
329}
330
331/// A named field.
332#[derive(Debug, Clone, PartialEq, Eq)]
333#[non_exhaustive]
334pub struct Field {
335    /// The field name.
336    pub name: String,
337    /// The type and width.
338    pub kind: Kind,
339    /// Documentation.
340    pub doc: Option<String>,
341    /// The `#[at]` position.
342    pub stated: Option<Stated>,
343    /// The `#[magic]` bytes the field must hold.
344    pub magic: Option<Vec<u8>>,
345    /// The `#[range]` of allowed values.
346    pub range: Option<Range>,
347    /// Whether the field is spare: bits the format reserves that carry no information.
348    ///
349    /// The bits round-trip like any other field. Serde leaves a spare field out, under the same
350    /// `cfg` as the module's serde derive.
351    pub spare: bool,
352    /// The field's visibility, such as `pub(crate)`. `None` is `pub`.
353    ///
354    /// A field the generated type keeps in step with something else, such as a label that a
355    /// catalogue arm already decided, is not the caller's to set.
356    pub visibility: Option<String>,
357}
358
359impl Field {
360    /// A field with no documentation or attributes.
361    #[must_use]
362    pub fn new(name: &str, kind: Kind) -> Self {
363        Self {
364            name: String::from(name),
365            kind,
366            doc: None,
367            stated: None,
368            magic: None,
369            range: None,
370            spare: false,
371            visibility: None,
372        }
373    }
374
375    /// Marks the field spare: its bits carry no information.
376    #[must_use]
377    pub fn with_spare(self) -> Self {
378        Self { spare: true, ..self }
379    }
380
381    /// Sets the visibility, such as `pub(crate)` or `""` for private.
382    #[must_use]
383    pub fn with_visibility(self, visibility: &str) -> Self {
384        Self { visibility: Some(String::from(visibility)), ..self }
385    }
386
387    /// Sets the documentation.
388    #[must_use]
389    pub fn with_doc(self, doc: &str) -> Self {
390        Self { doc: Some(String::from(doc)), ..self }
391    }
392
393    /// Sets the `#[at]` position.
394    #[must_use]
395    pub fn with_stated(self, stated: Stated) -> Self {
396        Self { stated: Some(stated), ..self }
397    }
398
399    /// Sets the `#[magic]` bytes.
400    #[must_use]
401    pub fn with_magic(self, bytes: &[u8]) -> Self {
402        Self { magic: Some(bytes.to_vec()), ..self }
403    }
404
405    /// Sets the `#[range]`.
406    #[must_use]
407    pub fn with_range(self, range: Range) -> Self {
408        Self { range: Some(range), ..self }
409    }
410}
411
412/// The values a `#[range]` allows.
413#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
414#[non_exhaustive]
415pub struct Range {
416    /// The lowest allowed value. `None` is the type's minimum.
417    pub lo: Option<i64>,
418    /// The highest allowed value. `None` is the type's maximum.
419    pub hi: Option<i64>,
420}
421
422impl Range {
423    /// `lo..=hi`. A `None` end is unbounded.
424    #[must_use]
425    pub fn new(lo: Option<i64>, hi: Option<i64>) -> Self {
426        Self { lo, hi }
427    }
428}