1use alloc::format;
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use super::Derive;
8
9use layline_core::table::StatedUnit;
10
11use super::{Field, Kind, Scalar, Stated};
12use crate::Invalid;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
16pub enum Endian {
17 #[default]
19 Le,
20 Be,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum BitOrder {
27 Lsb,
29 Msb,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash)]
35#[non_exhaustive]
36pub enum Container {
37 Word {
41 bits: u64,
43 prefix: u64,
48 prefix_value: Option<u128>,
50 endian: Endian,
52 order: BitOrder,
54 },
55 Bytes {
57 bytes: usize,
59 endian: Endian,
61 },
62 Words {
64 words: usize,
66 endian: Endian,
68 order: BitOrder,
70 },
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[non_exhaustive]
76pub enum Unit {
77 Bits,
79 Bytes,
81 Words,
83}
84
85impl Unit {
86 #[must_use]
88 pub fn keyword(self) -> &'static str {
89 match self {
90 Unit::Bits => "bits",
91 Unit::Bytes => "bytes",
92 Unit::Words => "words",
93 }
94 }
95}
96
97impl Container {
98 #[must_use]
100 pub fn word(bits: u64, endian: Endian, order: BitOrder) -> Self {
101 Container::Word { bits, prefix: 0, prefix_value: None, endian, order }
102 }
103
104 pub fn admits(&self, name: &str, kind: &Kind) -> Result<(), Invalid> {
110 let no = |what: &str| Err(Invalid::field(name, String::from(what)));
111
112 if let Kind::Array(_, dims) = kind
113 && dims.is_empty()
114 {
115 return no("an array with no dimensions. Give it a length, or declare a scalar");
116 }
117
118 match self {
119 Container::Bytes { .. } => match kind {
120 Kind::Scalar(Scalar::Bool) => {
121 no("byte mode stores a `bool` in a whole byte. Declare it `Scalar::ByteBool`, \
122 or declare the record in word mode")
123 }
124 Kind::Text { .. } => {
125 no("byte mode has no text. Declare it in a `#[derive(Message)]`")
126 }
127 _ => Ok(()),
128 },
129 Container::Words { .. } | Container::Word { .. }
130 if matches!(kind, Kind::Scalar(Scalar::ByteBool)) =>
131 {
132 no("a whole-byte `bool` is byte mode's. Declare a one-bit `Scalar::Bool`")
133 }
134 Container::Words { .. } => match kind {
135 Kind::Array(s, _) if !matches!(s, Scalar::U(8 | 16)) => {
136 no("words mode allows only `[u16; K]` and `[u8; K]` arrays")
137 }
138 _ => Ok(()),
139 },
140 Container::Word { .. } => match kind {
141 Kind::Scalar(Scalar::F32 | Scalar::F64) => {
142 no("word mode has no floats. Declare it in byte mode")
143 }
144 Kind::Nested { .. } | Kind::NestedArray { .. } => {
145 no("word mode has no nested layouts. Declare it in byte mode")
146 }
147 Kind::Text { .. } | Kind::Var { .. } | Kind::Msg { .. } => no(
148 "word mode needs a fixed width, and this field's size is read from the wire. \
149 Declare it in a `#[derive(Message)]`",
150 ),
151 _ => Ok(()),
152 },
153 }
154 }
155
156 #[must_use]
158 pub fn unit(&self) -> Unit {
159 match self {
160 Container::Word { .. } => Unit::Bits,
161 Container::Bytes { .. } => Unit::Bytes,
162 Container::Words { .. } => Unit::Words,
163 }
164 }
165
166 #[must_use]
168 pub fn units(&self) -> u64 {
169 match self {
170 Container::Word { bits, .. } => *bits,
171 Container::Bytes { bytes, .. } => *bytes as u64,
172 Container::Words { words, .. } => *words as u64,
173 }
174 }
175
176 #[must_use]
178 pub fn endian(&self) -> Endian {
179 match self {
180 Container::Word { endian, .. }
181 | Container::Bytes { endian, .. }
182 | Container::Words { endian, .. } => *endian,
183 }
184 }
185
186 #[must_use]
188 pub fn order(&self) -> Option<BitOrder> {
189 match self {
190 Container::Word { order, .. } | Container::Words { order, .. } => Some(*order),
191 Container::Bytes { .. } => None,
192 }
193 }
194
195 #[must_use]
197 pub fn is_bit_addressed(&self) -> bool {
198 !matches!(self, Container::Bytes { .. })
199 }
200
201 #[must_use]
203 pub fn bits(&self) -> u64 {
204 match self {
205 Container::Word { bits, .. } => *bits,
206 Container::Bytes { bytes, .. } => *bytes as u64 * 8,
207 Container::Words { words, .. } => *words as u64 * 16,
208 }
209 }
210
211 #[must_use]
213 pub fn prefix(&self) -> u64 {
214 match self {
215 Container::Word { prefix, .. } => *prefix,
216 Container::Bytes { .. } | Container::Words { .. } => 0,
217 }
218 }
219
220 #[must_use]
222 pub fn field_bits(&self) -> u64 {
223 match self {
224 Container::Word { bits, prefix, .. } => bits.saturating_sub(*prefix),
225 other => other.bits(),
226 }
227 }
228
229 fn region_bits(&self, width: u64) -> u64 {
231 match self {
232 Container::Word { bits, .. } => *bits,
233 Container::Words { .. } => 16,
234 Container::Bytes { .. } => width,
235 }
236 }
237
238 fn region_start(&self, start: u64) -> u64 {
240 match self {
241 Container::Word { .. } => 0,
242 Container::Words { .. } => start - start % 16,
243 Container::Bytes { .. } => start,
244 }
245 }
246
247 #[must_use]
249 pub fn interior_boundary(&self) -> Option<u64> {
250 match self {
251 Container::Words { .. } => Some(16),
252 Container::Word { .. } | Container::Bytes { .. } => None,
253 }
254 }
255
256 #[must_use]
261 pub fn physical(&self, kind: &Kind, start: u64) -> u64 {
262 let (region, order) = match self {
263 Container::Word { bits, order, .. } => (*bits, *order),
264 Container::Words { order, .. } => (16, *order),
265 Container::Bytes { .. } => return start,
266 };
267 let packed = matches!(kind, Kind::Scalar(_) | Kind::Codec { .. });
268 if order == BitOrder::Lsb || !packed || region == 0 {
269 return start;
270 }
271 let base = start - start % region;
272 base + region.saturating_sub(start - base + kind.width())
273 }
274
275 pub fn check_stated(
283 &self,
284 field: &str,
285 kind: &Kind,
286 stated: Stated,
287 declared: u64,
288 ) -> Result<(), String> {
289 let msb = matches!(
290 self,
291 Container::Word { order: BitOrder::Msb, .. }
292 | Container::Words { order: BitOrder::Msb, .. }
293 );
294 if !msb {
295 return stated.check(field, declared);
296 }
297 let claimed = stated.bits();
298 if claimed == declared {
299 return Ok(());
300 }
301 let width = kind.width();
302 let region = self.region_bits(width);
303 let place = |bits| place(stated.unit, bits);
304 let lands = if claimed + width <= self.region_start(claimed) + region {
305 format!("is physical {}", place(self.physical(kind, claimed)))
306 } else {
307 let unit = match self {
308 Container::Words { .. } => "word",
309 _ => "container",
310 };
311 format!("does not fit the {region}-bit {unit}")
312 };
313 Err(format!(
314 "field `{field}`: #[at({} = {})] (declared numbering, msb) {lands}, but the solver \
315 placed it at physical {} — declared {}",
316 stated.unit.name(),
317 stated.pos,
318 place(self.physical(kind, declared)),
319 place(declared),
320 ))
321 }
322}
323
324fn place(unit: StatedUnit, bits: u64) -> String {
326 if bits.is_multiple_of(unit.bits()) {
327 format!("{} {}", unit.name(), bits / unit.bits())
328 } else {
329 format!("bit {bits} (not a byte boundary)")
330 }
331}
332
333#[derive(Debug, Clone, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct LayoutDef {
337 pub name: String,
339 pub container: Container,
341 pub fields: Vec<Field>,
343 pub view: bool,
345 pub truncate: bool,
348 pub doc: Option<String>,
350 pub derives: Vec<Derive>,
352}
353
354impl LayoutDef {
355 #[must_use]
357 pub fn new(name: &str, container: Container, fields: Vec<Field>) -> Self {
358 Self {
359 name: String::from(name),
360 container,
361 fields,
362 view: false,
363 truncate: false,
364 doc: None,
365 derives: Vec::new(),
366 }
367 }
368
369 #[must_use]
371 pub fn with_doc(self, doc: &str) -> Self {
372 Self { doc: Some(String::from(doc)), ..self }
373 }
374
375 #[must_use]
377 pub fn with_derives(self, derives: Vec<Derive>) -> Self {
378 Self { derives, ..self }
379 }
380
381 #[must_use]
383 pub fn with_view(self) -> Self {
384 Self { view: true, ..self }
385 }
386
387 #[must_use]
390 pub fn with_truncate(self) -> Self {
391 Self { truncate: true, ..self }
392 }
393}
394
395#[derive(Debug, Clone, Copy)]
397pub(crate) struct Positioned<'a> {
398 pub(crate) field: &'a Field,
399 pub(crate) declared: u64,
401 pub(crate) physical: u64,
403}
404
405pub(crate) fn positioned<'a>(
409 fields: &'a [Field],
410 container: &'a Container,
411) -> impl Iterator<Item = Positioned<'a>> {
412 fields.iter().scan(container.prefix(), move |at, field| {
413 let declared = *at;
414 *at += field.kind.width();
415 Some(Positioned { field, declared, physical: container.physical(&field.kind, declared) })
416 })
417}