use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use super::Derive;
use layline_core::table::StatedUnit;
use super::{Field, Kind, Scalar, Stated};
use crate::Invalid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Endian {
#[default]
Le,
Be,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BitOrder {
Lsb,
Msb,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Container {
Word {
bits: u64,
prefix: u64,
prefix_value: Option<u128>,
endian: Endian,
order: BitOrder,
},
Bytes {
bytes: usize,
endian: Endian,
},
Words {
words: usize,
endian: Endian,
order: BitOrder,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Unit {
Bits,
Bytes,
Words,
}
impl Unit {
#[must_use]
pub fn keyword(self) -> &'static str {
match self {
Unit::Bits => "bits",
Unit::Bytes => "bytes",
Unit::Words => "words",
}
}
}
impl Container {
#[must_use]
pub fn word(bits: u64, endian: Endian, order: BitOrder) -> Self {
Container::Word { bits, prefix: 0, prefix_value: None, endian, order }
}
pub fn admits(&self, name: &str, kind: &Kind) -> Result<(), Invalid> {
let no = |what: &str| Err(Invalid::field(name, String::from(what)));
if let Kind::Array(_, dims) = kind
&& dims.is_empty()
{
return no("an array with no dimensions. Give it a length, or declare a scalar");
}
match self {
Container::Bytes { .. } => match kind {
Kind::Scalar(Scalar::Bool) => {
no("byte mode stores a `bool` in a whole byte. Declare it `Scalar::ByteBool`, \
or declare the record in word mode")
}
Kind::Text { .. } => {
no("byte mode has no text. Declare it in a `#[derive(Message)]`")
}
_ => Ok(()),
},
Container::Words { .. } | Container::Word { .. }
if matches!(kind, Kind::Scalar(Scalar::ByteBool)) =>
{
no("a whole-byte `bool` is byte mode's. Declare a one-bit `Scalar::Bool`")
}
Container::Words { .. } => match kind {
Kind::Array(s, _) if !matches!(s, Scalar::U(8 | 16)) => {
no("words mode allows only `[u16; K]` and `[u8; K]` arrays")
}
_ => Ok(()),
},
Container::Word { .. } => match kind {
Kind::Scalar(Scalar::F32 | Scalar::F64) => {
no("word mode has no floats. Declare it in byte mode")
}
Kind::Nested { .. } | Kind::NestedArray { .. } => {
no("word mode has no nested layouts. Declare it in byte mode")
}
Kind::Text { .. } | Kind::Var { .. } | Kind::Msg { .. } => no(
"word mode needs a fixed width, and this field's size is read from the wire. \
Declare it in a `#[derive(Message)]`",
),
_ => Ok(()),
},
}
}
#[must_use]
pub fn unit(&self) -> Unit {
match self {
Container::Word { .. } => Unit::Bits,
Container::Bytes { .. } => Unit::Bytes,
Container::Words { .. } => Unit::Words,
}
}
#[must_use]
pub fn units(&self) -> u64 {
match self {
Container::Word { bits, .. } => *bits,
Container::Bytes { bytes, .. } => *bytes as u64,
Container::Words { words, .. } => *words as u64,
}
}
#[must_use]
pub fn endian(&self) -> Endian {
match self {
Container::Word { endian, .. }
| Container::Bytes { endian, .. }
| Container::Words { endian, .. } => *endian,
}
}
#[must_use]
pub fn order(&self) -> Option<BitOrder> {
match self {
Container::Word { order, .. } | Container::Words { order, .. } => Some(*order),
Container::Bytes { .. } => None,
}
}
#[must_use]
pub fn is_bit_addressed(&self) -> bool {
!matches!(self, Container::Bytes { .. })
}
#[must_use]
pub fn bits(&self) -> u64 {
match self {
Container::Word { bits, .. } => *bits,
Container::Bytes { bytes, .. } => *bytes as u64 * 8,
Container::Words { words, .. } => *words as u64 * 16,
}
}
#[must_use]
pub fn prefix(&self) -> u64 {
match self {
Container::Word { prefix, .. } => *prefix,
Container::Bytes { .. } | Container::Words { .. } => 0,
}
}
#[must_use]
pub fn field_bits(&self) -> u64 {
match self {
Container::Word { bits, prefix, .. } => bits.saturating_sub(*prefix),
other => other.bits(),
}
}
fn region_bits(&self, width: u64) -> u64 {
match self {
Container::Word { bits, .. } => *bits,
Container::Words { .. } => 16,
Container::Bytes { .. } => width,
}
}
fn region_start(&self, start: u64) -> u64 {
match self {
Container::Word { .. } => 0,
Container::Words { .. } => start - start % 16,
Container::Bytes { .. } => start,
}
}
#[must_use]
pub fn interior_boundary(&self) -> Option<u64> {
match self {
Container::Words { .. } => Some(16),
Container::Word { .. } | Container::Bytes { .. } => None,
}
}
#[must_use]
pub fn physical(&self, kind: &Kind, start: u64) -> u64 {
let (region, order) = match self {
Container::Word { bits, order, .. } => (*bits, *order),
Container::Words { order, .. } => (16, *order),
Container::Bytes { .. } => return start,
};
let packed = matches!(kind, Kind::Scalar(_) | Kind::Codec { .. });
if order == BitOrder::Lsb || !packed || region == 0 {
return start;
}
let base = start - start % region;
base + region.saturating_sub(start - base + kind.width())
}
pub fn check_stated(
&self,
field: &str,
kind: &Kind,
stated: Stated,
declared: u64,
) -> Result<(), String> {
let msb = matches!(
self,
Container::Word { order: BitOrder::Msb, .. }
| Container::Words { order: BitOrder::Msb, .. }
);
if !msb {
return stated.check(field, declared);
}
let claimed = stated.bits();
if claimed == declared {
return Ok(());
}
let width = kind.width();
let region = self.region_bits(width);
let place = |bits| place(stated.unit, bits);
let lands = if claimed + width <= self.region_start(claimed) + region {
format!("is physical {}", place(self.physical(kind, claimed)))
} else {
let unit = match self {
Container::Words { .. } => "word",
_ => "container",
};
format!("does not fit the {region}-bit {unit}")
};
Err(format!(
"field `{field}`: #[at({} = {})] (declared numbering, msb) {lands}, but the solver \
placed it at physical {} — declared {}",
stated.unit.name(),
stated.pos,
place(self.physical(kind, declared)),
place(declared),
))
}
}
fn place(unit: StatedUnit, bits: u64) -> String {
if bits.is_multiple_of(unit.bits()) {
format!("{} {}", unit.name(), bits / unit.bits())
} else {
format!("bit {bits} (not a byte boundary)")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LayoutDef {
pub name: String,
pub container: Container,
pub fields: Vec<Field>,
pub view: bool,
pub truncate: bool,
pub doc: Option<String>,
pub derives: Vec<Derive>,
}
impl LayoutDef {
#[must_use]
pub fn new(name: &str, container: Container, fields: Vec<Field>) -> Self {
Self {
name: String::from(name),
container,
fields,
view: false,
truncate: false,
doc: None,
derives: Vec::new(),
}
}
#[must_use]
pub fn with_doc(self, doc: &str) -> Self {
Self { doc: Some(String::from(doc)), ..self }
}
#[must_use]
pub fn with_derives(self, derives: Vec<Derive>) -> Self {
Self { derives, ..self }
}
#[must_use]
pub fn with_view(self) -> Self {
Self { view: true, ..self }
}
#[must_use]
pub fn with_truncate(self) -> Self {
Self { truncate: true, ..self }
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Positioned<'a> {
pub(crate) field: &'a Field,
pub(crate) declared: u64,
pub(crate) physical: u64,
}
pub(crate) fn positioned<'a>(
fields: &'a [Field],
container: &'a Container,
) -> impl Iterator<Item = Positioned<'a>> {
fields.iter().scan(container.prefix(), move |at, field| {
let declared = *at;
*at += field.kind.width();
Some(Positioned { field, declared, physical: container.physical(&field.kind, declared) })
})
}