1use alloc::format;
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use layline_core::table::StatedUnit;
8
9use super::{Field, Kind, Scalar, Stated};
10use crate::Invalid;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub enum Endian {
15 #[default]
17 Le,
18 Be,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum BitOrder {
25 Lsb,
27 Msb,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum Container {
35 Word {
39 bits: u64,
41 prefix: u64,
46 prefix_value: Option<u128>,
48 endian: Endian,
50 order: BitOrder,
52 },
53 Bytes {
55 bytes: usize,
57 endian: Endian,
59 },
60 Words {
62 words: usize,
64 endian: Endian,
66 order: BitOrder,
68 },
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73#[non_exhaustive]
74pub enum Unit {
75 Bits,
77 Bytes,
79 Words,
81}
82
83impl Unit {
84 #[must_use]
86 pub fn keyword(self) -> &'static str {
87 match self {
88 Unit::Bits => "bits",
89 Unit::Bytes => "bytes",
90 Unit::Words => "words",
91 }
92 }
93}
94
95impl Container {
96 #[must_use]
98 pub fn word(bits: u64, endian: Endian, order: BitOrder) -> Self {
99 Container::Word { bits, prefix: 0, prefix_value: None, endian, order }
100 }
101
102 pub fn admits(&self, name: &str, kind: &Kind) -> Result<(), Invalid> {
108 let no = |what: &str| Err(Invalid::field(name, String::from(what)));
109
110 if let Kind::Array(_, dims) = kind
111 && dims.is_empty()
112 {
113 return no("an array with no dimensions. Give it a length, or declare a scalar");
114 }
115
116 match self {
117 Container::Bytes { .. } => match kind {
118 Kind::Scalar(Scalar::Bool) => {
119 no("byte mode has no `bool`. Declare it in word mode")
120 }
121 Kind::Text { .. } => {
122 no("byte mode has no text. Declare it in a `#[derive(Message)]`")
123 }
124 _ => Ok(()),
125 },
126 Container::Words { .. } => match kind {
127 Kind::Array(s, _) if !matches!(s, Scalar::U(8 | 16)) => {
128 no("words mode allows only `[u16; K]` and `[u8; K]` arrays")
129 }
130 _ => Ok(()),
131 },
132 Container::Word { .. } => match kind {
133 Kind::Scalar(Scalar::F32 | Scalar::F64) => {
134 no("word mode has no floats. Declare it in byte mode")
135 }
136 Kind::Nested { .. } | Kind::NestedArray { .. } => {
137 no("word mode has no nested layouts. Declare it in byte mode")
138 }
139 Kind::Text { .. } | Kind::Var { .. } | Kind::Msg { .. } => no(
140 "word mode needs a fixed width, and this field's size is read from the wire. \
141 Declare it in a `#[derive(Message)]`",
142 ),
143 _ => Ok(()),
144 },
145 }
146 }
147
148 #[must_use]
150 pub fn unit(&self) -> Unit {
151 match self {
152 Container::Word { .. } => Unit::Bits,
153 Container::Bytes { .. } => Unit::Bytes,
154 Container::Words { .. } => Unit::Words,
155 }
156 }
157
158 #[must_use]
160 pub fn units(&self) -> u64 {
161 match self {
162 Container::Word { bits, .. } => *bits,
163 Container::Bytes { bytes, .. } => *bytes as u64,
164 Container::Words { words, .. } => *words as u64,
165 }
166 }
167
168 #[must_use]
170 pub fn endian(&self) -> Endian {
171 match self {
172 Container::Word { endian, .. }
173 | Container::Bytes { endian, .. }
174 | Container::Words { endian, .. } => *endian,
175 }
176 }
177
178 #[must_use]
180 pub fn order(&self) -> Option<BitOrder> {
181 match self {
182 Container::Word { order, .. } | Container::Words { order, .. } => Some(*order),
183 Container::Bytes { .. } => None,
184 }
185 }
186
187 #[must_use]
189 pub fn is_bit_addressed(&self) -> bool {
190 !matches!(self, Container::Bytes { .. })
191 }
192
193 #[must_use]
195 pub fn bits(&self) -> u64 {
196 match self {
197 Container::Word { bits, .. } => *bits,
198 Container::Bytes { bytes, .. } => *bytes as u64 * 8,
199 Container::Words { words, .. } => *words as u64 * 16,
200 }
201 }
202
203 #[must_use]
205 pub fn prefix(&self) -> u64 {
206 match self {
207 Container::Word { prefix, .. } => *prefix,
208 Container::Bytes { .. } | Container::Words { .. } => 0,
209 }
210 }
211
212 #[must_use]
214 pub fn field_bits(&self) -> u64 {
215 match self {
216 Container::Word { bits, prefix, .. } => bits.saturating_sub(*prefix),
217 other => other.bits(),
218 }
219 }
220
221 fn region_bits(&self, width: u64) -> u64 {
223 match self {
224 Container::Word { bits, .. } => *bits,
225 Container::Words { .. } => 16,
226 Container::Bytes { .. } => width,
227 }
228 }
229
230 fn region_start(&self, start: u64) -> u64 {
232 match self {
233 Container::Word { .. } => 0,
234 Container::Words { .. } => start - start % 16,
235 Container::Bytes { .. } => start,
236 }
237 }
238
239 #[must_use]
241 pub fn interior_boundary(&self) -> Option<u64> {
242 match self {
243 Container::Words { .. } => Some(16),
244 Container::Word { .. } | Container::Bytes { .. } => None,
245 }
246 }
247
248 #[must_use]
253 pub fn physical(&self, kind: &Kind, start: u64) -> u64 {
254 let (region, order) = match self {
255 Container::Word { bits, order, .. } => (*bits, *order),
256 Container::Words { order, .. } => (16, *order),
257 Container::Bytes { .. } => return start,
258 };
259 let packed = matches!(kind, Kind::Scalar(_) | Kind::Codec { .. });
260 if order == BitOrder::Lsb || !packed || region == 0 {
261 return start;
262 }
263 let base = start - start % region;
264 base + region.saturating_sub(start - base + kind.width())
265 }
266
267 pub fn check_stated(
275 &self,
276 field: &str,
277 kind: &Kind,
278 stated: Stated,
279 declared: u64,
280 ) -> Result<(), String> {
281 let msb = matches!(
282 self,
283 Container::Word { order: BitOrder::Msb, .. }
284 | Container::Words { order: BitOrder::Msb, .. }
285 );
286 if !msb {
287 return stated.check(field, declared);
288 }
289 let claimed = stated.bits();
290 if claimed == declared {
291 return Ok(());
292 }
293 let width = kind.width();
294 let region = self.region_bits(width);
295 let place = |bits| place(stated.unit, bits);
296 let lands = if claimed + width <= self.region_start(claimed) + region {
297 format!("is physical {}", place(self.physical(kind, claimed)))
298 } else {
299 let unit = match self {
300 Container::Words { .. } => "word",
301 _ => "container",
302 };
303 format!("does not fit the {region}-bit {unit}")
304 };
305 Err(format!(
306 "field `{field}`: #[at({} = {})] (declared numbering, msb) {lands}, but the solver \
307 placed it at physical {} — declared {}",
308 stated.unit.name(),
309 stated.pos,
310 place(self.physical(kind, declared)),
311 place(declared),
312 ))
313 }
314}
315
316fn place(unit: StatedUnit, bits: u64) -> String {
318 if bits.is_multiple_of(unit.bits()) {
319 format!("{} {}", unit.name(), bits / unit.bits())
320 } else {
321 format!("bit {bits} (not a byte boundary)")
322 }
323}
324
325#[derive(Debug, Clone, PartialEq, Eq)]
327#[non_exhaustive]
328pub struct LayoutDef {
329 pub name: String,
331 pub container: Container,
333 pub fields: Vec<Field>,
335 pub view: bool,
337}
338
339impl LayoutDef {
340 #[must_use]
342 pub fn new(name: &str, container: Container, fields: Vec<Field>) -> Self {
343 Self { name: String::from(name), container, fields, view: false }
344 }
345
346 #[must_use]
348 pub fn with_view(self) -> Self {
349 Self { view: true, ..self }
350 }
351}
352
353#[derive(Debug, Clone, Copy)]
355pub(crate) struct Positioned<'a> {
356 pub(crate) field: &'a Field,
357 pub(crate) declared: u64,
359 pub(crate) physical: u64,
361}
362
363pub(crate) fn positioned<'a>(
367 fields: &'a [Field],
368 container: &'a Container,
369) -> impl Iterator<Item = Positioned<'a>> {
370 fields.iter().scan(container.prefix(), move |at, field| {
371 let declared = *at;
372 *at += field.kind.width();
373 Some(Positioned { field, declared, physical: container.physical(&field.kind, declared) })
374 })
375}