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 has no `bool`. Declare it in word mode")
122 }
123 Kind::Text { .. } => {
124 no("byte mode has no text. Declare it in a `#[derive(Message)]`")
125 }
126 _ => Ok(()),
127 },
128 Container::Words { .. } => match kind {
129 Kind::Array(s, _) if !matches!(s, Scalar::U(8 | 16)) => {
130 no("words mode allows only `[u16; K]` and `[u8; K]` arrays")
131 }
132 _ => Ok(()),
133 },
134 Container::Word { .. } => match kind {
135 Kind::Scalar(Scalar::F32 | Scalar::F64) => {
136 no("word mode has no floats. Declare it in byte mode")
137 }
138 Kind::Nested { .. } | Kind::NestedArray { .. } => {
139 no("word mode has no nested layouts. Declare it in byte mode")
140 }
141 Kind::Text { .. } | Kind::Var { .. } | Kind::Msg { .. } => no(
142 "word mode needs a fixed width, and this field's size is read from the wire. \
143 Declare it in a `#[derive(Message)]`",
144 ),
145 _ => Ok(()),
146 },
147 }
148 }
149
150 #[must_use]
152 pub fn unit(&self) -> Unit {
153 match self {
154 Container::Word { .. } => Unit::Bits,
155 Container::Bytes { .. } => Unit::Bytes,
156 Container::Words { .. } => Unit::Words,
157 }
158 }
159
160 #[must_use]
162 pub fn units(&self) -> u64 {
163 match self {
164 Container::Word { bits, .. } => *bits,
165 Container::Bytes { bytes, .. } => *bytes as u64,
166 Container::Words { words, .. } => *words as u64,
167 }
168 }
169
170 #[must_use]
172 pub fn endian(&self) -> Endian {
173 match self {
174 Container::Word { endian, .. }
175 | Container::Bytes { endian, .. }
176 | Container::Words { endian, .. } => *endian,
177 }
178 }
179
180 #[must_use]
182 pub fn order(&self) -> Option<BitOrder> {
183 match self {
184 Container::Word { order, .. } | Container::Words { order, .. } => Some(*order),
185 Container::Bytes { .. } => None,
186 }
187 }
188
189 #[must_use]
191 pub fn is_bit_addressed(&self) -> bool {
192 !matches!(self, Container::Bytes { .. })
193 }
194
195 #[must_use]
197 pub fn bits(&self) -> u64 {
198 match self {
199 Container::Word { bits, .. } => *bits,
200 Container::Bytes { bytes, .. } => *bytes as u64 * 8,
201 Container::Words { words, .. } => *words as u64 * 16,
202 }
203 }
204
205 #[must_use]
207 pub fn prefix(&self) -> u64 {
208 match self {
209 Container::Word { prefix, .. } => *prefix,
210 Container::Bytes { .. } | Container::Words { .. } => 0,
211 }
212 }
213
214 #[must_use]
216 pub fn field_bits(&self) -> u64 {
217 match self {
218 Container::Word { bits, prefix, .. } => bits.saturating_sub(*prefix),
219 other => other.bits(),
220 }
221 }
222
223 fn region_bits(&self, width: u64) -> u64 {
225 match self {
226 Container::Word { bits, .. } => *bits,
227 Container::Words { .. } => 16,
228 Container::Bytes { .. } => width,
229 }
230 }
231
232 fn region_start(&self, start: u64) -> u64 {
234 match self {
235 Container::Word { .. } => 0,
236 Container::Words { .. } => start - start % 16,
237 Container::Bytes { .. } => start,
238 }
239 }
240
241 #[must_use]
243 pub fn interior_boundary(&self) -> Option<u64> {
244 match self {
245 Container::Words { .. } => Some(16),
246 Container::Word { .. } | Container::Bytes { .. } => None,
247 }
248 }
249
250 #[must_use]
255 pub fn physical(&self, kind: &Kind, start: u64) -> u64 {
256 let (region, order) = match self {
257 Container::Word { bits, order, .. } => (*bits, *order),
258 Container::Words { order, .. } => (16, *order),
259 Container::Bytes { .. } => return start,
260 };
261 let packed = matches!(kind, Kind::Scalar(_) | Kind::Codec { .. });
262 if order == BitOrder::Lsb || !packed || region == 0 {
263 return start;
264 }
265 let base = start - start % region;
266 base + region.saturating_sub(start - base + kind.width())
267 }
268
269 pub fn check_stated(
277 &self,
278 field: &str,
279 kind: &Kind,
280 stated: Stated,
281 declared: u64,
282 ) -> Result<(), String> {
283 let msb = matches!(
284 self,
285 Container::Word { order: BitOrder::Msb, .. }
286 | Container::Words { order: BitOrder::Msb, .. }
287 );
288 if !msb {
289 return stated.check(field, declared);
290 }
291 let claimed = stated.bits();
292 if claimed == declared {
293 return Ok(());
294 }
295 let width = kind.width();
296 let region = self.region_bits(width);
297 let place = |bits| place(stated.unit, bits);
298 let lands = if claimed + width <= self.region_start(claimed) + region {
299 format!("is physical {}", place(self.physical(kind, claimed)))
300 } else {
301 let unit = match self {
302 Container::Words { .. } => "word",
303 _ => "container",
304 };
305 format!("does not fit the {region}-bit {unit}")
306 };
307 Err(format!(
308 "field `{field}`: #[at({} = {})] (declared numbering, msb) {lands}, but the solver \
309 placed it at physical {} — declared {}",
310 stated.unit.name(),
311 stated.pos,
312 place(self.physical(kind, declared)),
313 place(declared),
314 ))
315 }
316}
317
318fn place(unit: StatedUnit, bits: u64) -> String {
320 if bits.is_multiple_of(unit.bits()) {
321 format!("{} {}", unit.name(), bits / unit.bits())
322 } else {
323 format!("bit {bits} (not a byte boundary)")
324 }
325}
326
327#[derive(Debug, Clone, PartialEq, Eq)]
329#[non_exhaustive]
330pub struct LayoutDef {
331 pub name: String,
333 pub container: Container,
335 pub fields: Vec<Field>,
337 pub view: bool,
339 pub doc: Option<String>,
341 pub derives: Vec<Derive>,
343}
344
345impl LayoutDef {
346 #[must_use]
348 pub fn new(name: &str, container: Container, fields: Vec<Field>) -> Self {
349 Self {
350 name: String::from(name),
351 container,
352 fields,
353 view: false,
354 doc: None,
355 derives: Vec::new(),
356 }
357 }
358
359 #[must_use]
361 pub fn with_doc(self, doc: &str) -> Self {
362 Self { doc: Some(String::from(doc)), ..self }
363 }
364
365 #[must_use]
367 pub fn with_derives(self, derives: Vec<Derive>) -> Self {
368 Self { derives, ..self }
369 }
370
371 #[must_use]
373 pub fn with_view(self) -> Self {
374 Self { view: true, ..self }
375 }
376}
377
378#[derive(Debug, Clone, Copy)]
380pub(crate) struct Positioned<'a> {
381 pub(crate) field: &'a Field,
382 pub(crate) declared: u64,
384 pub(crate) physical: u64,
386}
387
388pub(crate) fn positioned<'a>(
392 fields: &'a [Field],
393 container: &'a Container,
394) -> impl Iterator<Item = Positioned<'a>> {
395 fields.iter().scan(container.prefix(), move |at, field| {
396 let declared = *at;
397 *at += field.kind.width();
398 Some(Positioned { field, declared, physical: container.physical(&field.kind, declared) })
399 })
400}