use alloc::borrow::Cow;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use super::error::SerialValueError;
use super::value::{SerialValue, TableId};
pub(crate) use techy_derive::{FromSerialValue, ToSerialValue};
pub trait ToSerialValue {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError>;
fn is_absent_field(&self) -> bool {
false
}
}
pub trait FromSerialValue: Sized {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError>;
fn from_serial_field(name: &'static str, value: Option<&SerialValue>) -> Result<Self, SerialValueError> {
match value {
Some(value) => Self::from_serial_value(value),
None => Err(SerialValueError::MissingField { name }),
}
}
}
fn mismatch(expected: &'static str, found: &SerialValue) -> SerialValueError {
SerialValueError::TypeMismatch { expected: Cow::Borrowed(expected), found: found.kind_name() }
}
impl ToSerialValue for SerialValue {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(self.clone())
}
}
impl FromSerialValue for SerialValue {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
Ok(value.clone())
}
}
impl ToSerialValue for bool {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Bool(*self))
}
}
impl FromSerialValue for bool {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::Bool(b) => Ok(*b),
other => Err(mismatch("a boolean", other)),
}
}
}
impl ToSerialValue for char {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Str(String::from(*self)))
}
}
impl FromSerialValue for char {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::Str(s) => {
let mut chars = s.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => Ok(c),
_ => Err(mismatch("a one-character string", value)),
}
}
other => Err(mismatch("a one-character string", other)),
}
}
}
macro_rules! int_conversions {
($($t:ty),* $(,)?) => {$(
impl ToSerialValue for $t {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
i64::try_from(*self).map(SerialValue::Int).map_err(|_| {
SerialValueError::IntegerOutOfRange { value: self.to_string(), target: "i64" }
})
}
}
impl FromSerialValue for $t {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::Int(i) => <$t>::try_from(*i).map_err(|_| {
SerialValueError::IntegerOutOfRange {
value: i.to_string(),
target: stringify!($t),
}
}),
other => Err(mismatch("an integer", other)),
}
}
}
)*};
}
int_conversions!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
impl ToSerialValue for String {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Str(self.clone()))
}
}
impl FromSerialValue for String {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::Str(s) => Ok(s.clone()),
other => Err(mismatch("a string", other)),
}
}
}
impl ToSerialValue for str {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Str(String::from(self)))
}
}
impl ToSerialValue for Cow<'static, str> {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Str(String::from(&**self)))
}
}
impl FromSerialValue for Cow<'static, str> {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
String::from_serial_value(value).map(Cow::Owned)
}
}
impl<T: ToSerialValue> ToSerialValue for Option<T> {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
match self {
Some(value) => value.to_serial_value(),
None => Ok(SerialValue::Null),
}
}
fn is_absent_field(&self) -> bool {
self.is_none()
}
}
impl<T: FromSerialValue> FromSerialValue for Option<T> {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::Null => Ok(None),
other => T::from_serial_value(other).map(Some),
}
}
fn from_serial_field(_name: &'static str, value: Option<&SerialValue>) -> Result<Self, SerialValueError> {
match value {
Some(value) => Self::from_serial_value(value),
None => Ok(None),
}
}
}
impl<T: ToSerialValue> ToSerialValue for Vec<T> {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
self.iter().map(ToSerialValue::to_serial_value).collect::<Result<Vec<_>, _>>().map(SerialValue::List)
}
}
impl<T: FromSerialValue> FromSerialValue for Vec<T> {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::List(items) => items.iter().map(T::from_serial_value).collect(),
other => Err(mismatch("a list", other)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub(crate) struct SerialBytes(pub(crate) Vec<u8>);
impl ToSerialValue for SerialBytes {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Bytes(self.0.clone()))
}
}
impl FromSerialValue for SerialBytes {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
match value {
SerialValue::Bytes(bytes) => Ok(SerialBytes(bytes.clone())),
other => Err(mismatch("a byte string", other)),
}
}
}
impl ToSerialValue for TableId {
fn to_serial_value(&self) -> Result<SerialValue, SerialValueError> {
Ok(SerialValue::Int(i64::from(self.ordinal())))
}
}
impl FromSerialValue for TableId {
fn from_serial_value(value: &SerialValue) -> Result<Self, SerialValueError> {
u32::from_serial_value(value).map(TableId::new)
}
}
pub fn index_from_serial_value(value: &SerialValue) -> Result<(TableId, u32), SerialValueError> {
match value {
SerialValue::Index { table, index } => Ok((*table, *index)),
other => Err(mismatch("a table position", other)),
}
}
pub struct FieldWriter {
entries: Vec<(String, SerialValue)>,
}
impl FieldWriter {
pub fn with_capacity(fields: usize) -> FieldWriter {
FieldWriter { entries: Vec::with_capacity(fields) }
}
pub(crate) fn field<T: ToSerialValue + ?Sized>(
&mut self,
name: &'static str,
value: &T,
) -> Result<(), SerialValueError> {
if value.is_absent_field() {
return Ok(());
}
self.push(name, value.to_serial_value()?);
Ok(())
}
pub(crate) fn push(&mut self, name: &'static str, value: SerialValue) {
self.entries.push((String::from(name), value));
}
pub fn finish(self) -> SerialValue {
SerialValue::Map(self.entries)
}
}
pub struct FieldReader<'a> {
entries: &'a [(String, SerialValue)],
}
impl<'a> FieldReader<'a> {
pub fn new(
value: &'a SerialValue,
what: &'static str,
fields: &'static [&'static str],
) -> Result<FieldReader<'a>, SerialValueError> {
let entries = match value {
SerialValue::Map(entries) => entries.as_slice(),
other => {
return Err(SerialValueError::TypeMismatch {
expected: Cow::Owned(alloc::format!("a map (‘{what}’)")),
found: other.kind_name(),
})
}
};
for (position, (key, _)) in entries.iter().enumerate() {
if !fields.contains(&key.as_str()) {
return Err(SerialValueError::UnknownField { name: key.clone(), expected: fields });
}
if entries[..position].iter().any(|(earlier, _)| earlier == key) {
return Err(SerialValueError::DuplicateField { name: key.clone() });
}
}
Ok(FieldReader { entries })
}
pub(crate) fn field<T: FromSerialValue>(&self, name: &'static str) -> Result<T, SerialValueError> {
T::from_serial_field(name, self.get(name))
}
pub(crate) fn get(&self, name: &str) -> Option<&'a SerialValue> {
self.entries.iter().find(|(key, _)| key == name).map(|(_, value)| value)
}
}
pub fn unit_variant(name: &'static str) -> SerialValue {
SerialValue::Str(String::from(name))
}
pub fn data_variant(name: &'static str, data: SerialValue) -> SerialValue {
SerialValue::Map(Vec::from([(String::from(name), data)]))
}
pub fn read_variant<'a>(
value: &'a SerialValue,
what: &'static str,
variants: &'static [&'static str],
) -> Result<(&'a str, Option<&'a SerialValue>), SerialValueError> {
let (name, payload) = match value {
SerialValue::Str(name) => (name.as_str(), None),
SerialValue::Map(entries) => match entries.as_slice() {
[(name, payload)] => (name.as_str(), Some(payload)),
_ => return Err(enum_mismatch(what, value)),
},
_ => return Err(enum_mismatch(what, value)),
};
if !variants.contains(&name) {
return Err(unknown_variant(name, variants));
}
Ok((name, payload))
}
fn enum_mismatch(what: &'static str, found: &SerialValue) -> SerialValueError {
SerialValueError::TypeMismatch {
expected: Cow::Owned(alloc::format!(
"an enum value of ‘{what}’ (a variant name, or a one-entry map from a variant \
name to its data)"
)),
found: found.kind_name(),
}
}
pub fn unknown_variant(name: &str, variants: &'static [&'static str]) -> SerialValueError {
SerialValueError::UnknownVariant { name: String::from(name), expected: variants }
}
pub fn expect_unit_variant(name: &str, payload: Option<&SerialValue>) -> Result<(), SerialValueError> {
match payload {
None => Ok(()),
Some(_) => Err(SerialValueError::TypeMismatch {
expected: Cow::Owned(alloc::format!("the string ‘{name}’ (a unit variant has no data)")),
found: "map",
}),
}
}
pub fn expect_data_variant<'a>(
name: &'static str,
payload: Option<&'a SerialValue>,
) -> Result<&'a SerialValue, SerialValueError> {
match payload {
Some(payload) => Ok(payload),
None => Err(SerialValueError::TypeMismatch {
expected: Cow::Owned(alloc::format!("a one-entry map from ‘{name}’ to the data of the variant")),
found: "str",
}),
}
}
pub(crate) mod diagnostic;
pub(crate) mod parse_result;
pub(crate) mod source;
pub(crate) mod specs;
pub(crate) mod state;
pub(crate) mod tree;
#[cfg(test)]
mod tests;