lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Versioned declaration values. Each record has explicit TOML fields and
//! reconstructs one complete validated native value through its constructor.

use toml_edit::{Array, Item, TableLike, Value};

use crate::{Error, Result};

pub(crate) trait Codec: Sized {
    fn encode(&self) -> Value;
    fn decode(item: &Item, base: Option<Self>) -> Result<Self>;
    fn schema(ctx: &mut super::schema::Schema) -> serde_json::Value;
    fn schema_with_default(ctx: &mut super::schema::Schema) -> serde_json::Value {
        ctx.reference::<Self>()
    }
}

pub(crate) fn invalid(message: impl Into<String>) -> Error {
    Error::Data(message.into().into())
}

pub(crate) fn table<'a>(item: &'a Item, fields: &[&str]) -> Result<&'a dyn TableLike> {
    table_checked(item, |name| fields.contains(&name))
}

pub(crate) fn table_checked(item: &Item, admits: impl Fn(&str) -> bool) -> Result<&dyn TableLike> {
    let table = item
        .as_table_like()
        .ok_or_else(|| invalid("expected a TOML table"))?;
    for (name, _) in table.iter() {
        if !admits(name) {
            return Err(invalid(format!("unknown declaration field {name:?}")));
        }
    }
    Ok(table)
}

pub(crate) fn field<T: Codec>(table: &dyn TableLike, name: &str, base: Option<T>) -> Result<T> {
    if let Some(value) = table.get(name) {
        T::decode(value, base).map_err(|error| error.with_prefix(name))
    } else {
        base.ok_or_else(|| invalid(format!("missing declaration field {name:?}")))
    }
}

impl Codec for String {
    fn schema(_: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::primitive("string")
    }
    fn encode(&self) -> Value {
        Value::from(self.clone())
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        item.as_str()
            .map(str::to_owned)
            .ok_or_else(|| invalid("expected a string"))
    }
}

impl Codec for bool {
    fn schema(_: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::primitive("boolean")
    }
    fn encode(&self) -> Value {
        Value::from(*self)
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        item.as_bool().ok_or_else(|| invalid("expected a Boolean"))
    }
}

impl Codec for u32 {
    fn schema(_: &mut super::schema::Schema) -> serde_json::Value {
        serde_json::json!({"type":"integer","minimum":0,"maximum":u32::MAX})
    }
    fn encode(&self) -> Value {
        Value::from(i64::from(*self))
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        item.as_integer()
            .and_then(|value| u32::try_from(value).ok())
            .ok_or_else(|| invalid("expected an unsigned 32-bit integer"))
    }
}

macro_rules! signed_integer {
    ($($type:ty),+) => {$(
        impl Codec for $type {
            fn schema(_: &mut super::schema::Schema) -> serde_json::Value { serde_json::json!({"type":"integer","minimum":<$type>::MIN,"maximum":<$type>::MAX}) }
            fn encode(&self) -> Value {
                Value::from(i64::try_from(*self).expect("native signed integer representation"))
            }

            fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
                item.as_integer()
                    .and_then(|value| Self::try_from(value).ok())
                    .ok_or_else(|| invalid("expected an integer in the native range"))
            }
        }
    )+};
}
signed_integer!(i8, i16, i32, isize, u8);

impl Codec for usize {
    fn schema(ctx: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::with(
            ctx.reference::<crate::data::ExactInteger>(),
            serde_json::json!({"if":{"type":"integer"},"then":{"minimum":0}}),
        )
    }
    fn encode(&self) -> Value {
        crate::data::ExactInteger::from(*self).encode()
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        crate::data::ExactInteger::decode(item, None)?
            .to_usize()
            .ok_or_else(|| invalid("expected a nonnegative integer in the native index range"))
    }
}

impl Codec for f64 {
    fn schema(_: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::primitive("number")
    }
    fn encode(&self) -> Value {
        Value::from(*self)
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        let value = if let Some(value) = item.as_float() {
            value
        } else if let Some(value) = item.as_integer() {
            if let Ok(value) = i32::try_from(value) {
                f64::from(value)
            } else {
                crate::numeric::binary::signed_ratio(value.into(), 1_u8.into())?
            }
        } else {
            return Err(invalid("expected a number"));
        };
        if !value.is_finite() {
            return Err(invalid("declaration number must be finite"));
        }
        Ok(value)
    }
}

impl Codec for f32 {
    fn schema(_: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::primitive("number")
    }
    fn encode(&self) -> Value {
        f64::from(*self).encode()
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "the native stroke width is binary32"
        )]
        let value = f64::decode(item, None)? as f32;
        if !value.is_finite() {
            return Err(invalid("number exceeds the native binary32 range"));
        }
        Ok(value)
    }
}

impl<T: Codec> Codec for Option<T> {
    fn schema(ctx: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::any_of([super::schema::literal(false), ctx.reference::<T>()])
    }
    fn schema_with_default(ctx: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::any_of([super::schema::literal(false), T::schema_with_default(ctx)])
    }
    fn encode(&self) -> Value {
        self.as_ref()
            .map_or_else(|| Value::from(false), Codec::encode)
    }

    fn decode(item: &Item, base: Option<Self>) -> Result<Self> {
        if item.as_bool() == Some(false) {
            Ok(None)
        } else {
            T::decode(item, base.flatten()).map(Some)
        }
    }
}

impl<T: Codec> Codec for Vec<T> {
    fn schema(ctx: &mut super::schema::Schema) -> serde_json::Value {
        super::schema::array(ctx.reference::<T>())
    }
    fn encode(&self) -> Value {
        Value::Array(self.iter().map(Codec::encode).collect())
    }

    fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
        let mut values = Vec::new();
        if let Some(array) = item.as_array() {
            crate::data::source::reserve_source(&mut values, array.len())?;
            for (index, value) in array.iter().enumerate() {
                crate::operation::check()?;
                values.push(
                    T::decode(&Item::Value(value.clone()), None)
                        .map_err(|error| error.with_prefix(&format!("[{index}]")))?,
                );
            }
        } else if let Some(array) = item.as_array_of_tables() {
            crate::data::source::reserve_source(&mut values, array.len())?;
            for (index, value) in array.iter().enumerate() {
                crate::operation::check()?;
                values.push(
                    T::decode(&Item::Table(value.clone()), None)
                        .map_err(|error| error.with_prefix(&format!("[{index}]")))?,
                );
            }
        } else {
            return Err(invalid("expected an ordered array"));
        }
        Ok(values)
    }
}

// Getter modes describe ownership of real native values, never serializer
// internals. Record readers construct the entire sibling group at once.
macro_rules! retained {
    ($value:expr, $getter:ident, copy) => {
        $value.$getter()
    };
    ($value:expr, $getter:ident, borrow) => {
        $value.$getter().clone()
    };
    ($value:expr, $getter:ident, optional) => {
        $value.$getter().cloned()
    };
    ($value:expr, $getter:ident, optional_copy) => {
        $value.$getter()
    };
}

macro_rules! default_field {
    ($base:expr, $getter:ident, optional) => {
        Some($base.as_ref().and_then(|value| value.$getter().cloned()))
    };
    ($base:expr, $getter:ident, optional_copy) => {
        Some($base.as_ref().and_then(|value| value.$getter()))
    };
    ($base:expr, $getter:ident, $mode:ident) => {
        $base.as_ref().map(|value| retained!(value, $getter, $mode))
    };
}

macro_rules! encode_field {
    ($value:expr, $getter:ident, borrow) => {
        $value.$getter().encode()
    };
    ($value:expr, $getter:ident, $mode:ident) => {
        retained!($value, $getter, $mode).encode()
    };
}

macro_rules! record {
    ($type:ty { $($key:ident => $getter:ident [$mode:ident]),+ $(,)? }) => {
        impl Codec for $type {
            fn schema(ctx:&mut $crate::recipe::schema::Schema) -> serde_json::Value {
                let required=[$((stringify!($key),$crate::recipe::codec::record_required!($mode)),)+]
                    .into_iter().filter_map(|(key,required)|required.then_some(key)).collect::<Vec<_>>();
                $crate::recipe::schema::object([$((
                    stringify!($key), $crate::recipe::codec::schema_getter!(ctx,Self::$getter,$mode),
                ),)+],&required)
            }
            fn schema_with_default(ctx:&mut $crate::recipe::schema::Schema) -> serde_json::Value {
                ctx.named(&format!("Inherited<{}>",std::any::type_name::<Self>()),|ctx|{
                    $crate::recipe::schema::object([$((
                        stringify!($key),$crate::recipe::codec::inherited_getter!(ctx,Self::$getter,$mode),
                    ),)+],&[])
                })
            }
            fn encode(&self) -> Value {
                let mut record=InlineTable::new();
                $(record.insert(stringify!($key), encode_field!(self,$getter,$mode));)+
                record.into()
            }

            fn decode(item:&Item,base:Option<Self>)->Result<Self> {
                let fields=table(item,&[$(stringify!($key)),+])?;
                Self::new($(field(fields,stringify!($key),default_field!(base,$getter,$mode))?),+)
            }
        }
    };
}

macro_rules! choice {
    ($type:ty { $($variant:ident => $name:literal),+ $(,)? }) => {
        impl Codec for $type {
            fn schema(_: &mut $crate::recipe::schema::Schema) -> serde_json::Value {
                $crate::recipe::schema::choices(&[$($name),+])
            }
            fn encode(&self)->Value {
                Value::from(match self {$(Self::$variant=>$name,)+})
            }

            fn decode(item:&Item,_:Option<Self>)->Result<Self> {
                match item.as_str() {
                    $(Some($name)=>Ok(Self::$variant),)+
                    _=>Err(invalid(concat!("expected one of: ",$($name,", "),+))),
                }
            }
        }
    };
}

macro_rules! schema_getter {
    ($ctx:expr,$getter:path,borrow) => {
        $crate::recipe::schema::borrowed($ctx, $getter)
    };
    ($ctx:expr,$getter:path,optional) => {
        $crate::recipe::schema::optional_borrowed($ctx, $getter)
    };
    ($ctx:expr,$getter:path,$mode:ident) => {
        $crate::recipe::schema::getter($ctx, $getter)
    };
}

macro_rules! record_required {
    (optional) => {
        false
    };
    (optional_copy) => {
        false
    };
    ($mode:ident) => {
        true
    };
}

macro_rules! inherited_getter {
    ($ctx:expr,$getter:path,borrow) => {
        $crate::recipe::schema::inherited_borrowed($ctx, $getter)
    };
    ($ctx:expr,$getter:path,optional) => {
        $crate::recipe::schema::inherited_optional($ctx, $getter)
    };
    ($ctx:expr,$getter:path,$mode:ident) => {
        $crate::recipe::schema::inherited_getter($ctx, $getter)
    };
}
pub(crate) use {
    choice, default_field, encode_field, inherited_getter, record, record_required, retained,
    schema_getter,
};

pub(crate) fn array<T: Codec>(values: &[T]) -> Value {
    Value::Array(values.iter().map(Codec::encode).collect::<Array>())
}

pub(crate) fn array_items(item: &Item) -> Result<impl ExactSizeIterator<Item = &Item>> {
    let count = item
        .as_array()
        .map(toml_edit::Array::len)
        .or_else(|| item.as_array_of_tables().map(toml_edit::ArrayOfTables::len))
        .ok_or_else(|| invalid("expected an ordered array of declarations"))?;
    Ok((0..count).map(move |index| item.get(index).expect("actual array entry")))
}

/// The lossless JSON projection of an encoded portable declaration value.
pub(crate) fn json_value(value: Value) -> serde_json::Value {
    match value {
        Value::String(value) => serde_json::Value::from(value.value().clone()),
        Value::Integer(value) => serde_json::Value::from(*value.value()),
        Value::Float(value) => serde_json::Value::from(*value.value()),
        Value::Boolean(value) => serde_json::Value::from(*value.value()),
        Value::Datetime(value) => serde_json::Value::from(value.value().to_string()),
        Value::Array(values) => values.into_iter().map(json_value).collect(),
        Value::InlineTable(values) => values
            .into_iter()
            .map(|(key, value)| (key, json_value(value)))
            .collect(),
    }
}