use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use flow_types::{EnumShape, RecordShape, Type};
use flow_value::{Decimal, Duration, Instant, Int, Value, compare};
use crate::binary::{ValueReader, ValueWriter, decimal_into, payload_step, read_decimal};
use crate::bytes::{Reader, wide, write_bytes, write_int, write_text, write_uint};
use crate::catalog::Catalog;
use crate::decode::{Mode, decodable};
use crate::error::{DecodeError, DecodeErrorKind, EncodeError, EncodeErrorKind, Place};
use crate::form::{Form, Scalar, form};
use crate::limits::Limits;
use crate::wire::{Part, Shaped};
pub fn write_shaped<T: Shaped>(
out: &mut Vec<u8>,
catalog: &Catalog,
ty: &Type,
value: &T,
) -> Result<(), EncodeError> {
value.write_at(
&mut ValueWriter {
catalog,
out,
path: Place::default(),
},
ty,
)
}
pub fn read_shaped<T: Shaped>(
reader: &mut Reader<'_>,
catalog: &Catalog,
ty: &Type,
mode: Mode,
limits: &Limits,
) -> Result<T, DecodeError> {
decodable(catalog, ty, mode.settings())?;
T::read_at(
&mut ValueReader {
catalog,
limits,
path: Place::default(),
reader,
zero_width_left: limits.text_bytes,
level: 0,
},
ty,
)
}
pub fn shaped_value<T: Shaped>(
value: &T,
catalog: &Catalog,
ty: &Type,
) -> Result<Value, EncodeError> {
let mut bytes = Vec::new();
write_shaped(&mut bytes, catalog, ty, value)?;
crate::decode_bytes(catalog, ty, &bytes, Mode::Rebuild, &Limits::UNBOUNDED)
.map_err(|error| EncodeError::new(&error.path, EncodeErrorKind::Mismatch, error.problem))
}
pub fn of_shaped_value<T: Shaped>(
value: &Value,
catalog: &Catalog,
ty: &Type,
) -> Result<T, DecodeError> {
let mut bytes = Vec::new();
crate::write_value(&mut bytes, catalog, ty, value)
.map_err(|error| DecodeError::of(&error.path, DecodeErrorKind::Mismatch, error.problem))?;
let mut reader = Reader::new(&bytes);
read_shaped(&mut reader, catalog, ty, Mode::Rebuild, &Limits::UNBOUNDED)
}
impl<'c> ValueWriter<'c, '_> {
pub fn catalog(&self) -> &'c Catalog {
self.catalog
}
pub fn refuse(&self, ty: &Type) -> EncodeError {
self.mismatch(ty)
}
fn scalar(&mut self, ty: &Type, scalar: Scalar) -> Result<&mut Vec<u8>, EncodeError> {
if let Form::Scalar(found) = form(self.catalog, ty)
&& found == scalar
{
Ok(self.out)
} else {
Err(self.mismatch(ty))
}
}
pub fn unit(&mut self, ty: &Type) -> Result<(), EncodeError> {
self.scalar(ty, Scalar::Unit).map(|_| ())
}
#[expect(
clippy::fn_params_excessive_bools,
reason = "the flag is the value written, as a Bool is"
)]
pub fn bool(&mut self, ty: &Type, flag: bool) -> Result<(), EncodeError> {
self.scalar(ty, Scalar::Bool)?.push(u8::from(flag));
Ok(())
}
pub fn int(&mut self, ty: &Type, number: &Int) -> Result<(), EncodeError> {
write_int(self.scalar(ty, Scalar::Int)?, number.as_bigint());
Ok(())
}
pub fn decimal(&mut self, ty: &Type, number: &Decimal) -> Result<(), EncodeError> {
decimal_into(self.scalar(ty, Scalar::Decimal)?, number);
Ok(())
}
pub fn duration(&mut self, ty: &Type, span: &Duration) -> Result<(), EncodeError> {
decimal_into(self.scalar(ty, Scalar::Duration)?, span.seconds());
Ok(())
}
pub fn instant(&mut self, ty: &Type, at: &Instant) -> Result<(), EncodeError> {
decimal_into(self.scalar(ty, Scalar::Instant)?, at.unix_seconds());
Ok(())
}
pub fn text(&mut self, ty: &Type, text: &str) -> Result<(), EncodeError> {
if !matches!(form(self.catalog, ty), Form::Text) {
return Err(self.mismatch(ty));
}
write_text(self.out, text);
Ok(())
}
pub fn bytes(&mut self, ty: &Type, bytes: &[u8]) -> Result<(), EncodeError> {
if !matches!(form(self.catalog, ty), Form::Bytes) {
return Err(self.mismatch(ty));
}
write_bytes(self.out, bytes);
Ok(())
}
pub fn host(&mut self, ty: &Type, token: &str) -> Result<(), EncodeError> {
if !matches!(form(self.catalog, ty), Form::Host) {
return Err(self.mismatch(ty));
}
write_text(self.out, token);
Ok(())
}
pub fn list<'v, T: Shaped>(
&mut self,
ty: &Type,
items: impl ExactSizeIterator<Item = &'v T>,
) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Form::List(item) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
write_uint(self.out, wide(items.len()));
for (index, each) in items.enumerate() {
self.at(|path| path.index(index), |me| each.write_at(me, item))?;
}
Ok(())
}
pub fn set<'v, T: Shaped>(
&mut self,
ty: &Type,
items: impl ExactSizeIterator<Item = &'v T>,
) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Form::Set(item) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
self.ordered(
item,
None,
items.map(|each| -> (&dyn Part, Option<&dyn Part>) { (each, None) }),
)
}
pub fn dict<'v, K: Shaped, V: Shaped>(
&mut self,
ty: &Type,
entries: impl ExactSizeIterator<Item = (&'v K, &'v V)>,
) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Form::Dict(key, item) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
self.ordered(
key,
Some(item),
entries.map(|(each, held)| -> (&dyn Part, Option<&dyn Part>) { (each, Some(held)) }),
)
}
fn ordered<'p>(
&mut self,
key: &Type,
item: Option<&Type>,
entries: impl ExactSizeIterator<Item = (&'p dyn Part, Option<&'p dyn Part>)>,
) -> Result<(), EncodeError> {
let mut written = Vec::with_capacity(entries.len());
for (index, (each, held)) in entries.enumerate() {
let mut bytes = Vec::new();
let mut part = ValueWriter {
catalog: self.catalog,
out: &mut bytes,
path: self.path.clone(),
};
part.path.index(index);
part.at(|path| path.index(0), |me| each.write_part(me, key))?;
let ends = part.out.len();
if let (Some(item), Some(held)) = (item, held) {
part.at(|path| path.index(1), |me| held.write_part(me, item))?;
}
let order = crate::decode_bytes(
self.catalog,
key,
&bytes[..ends],
Mode::Rebuild,
&Limits::UNBOUNDED,
)
.map_err(|error| {
EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem)
})?;
written.push((order, bytes));
}
written.sort_by(|(a, _), (b, _)| compare(a, b).unwrap_or(std::cmp::Ordering::Equal));
if written
.windows(2)
.any(|pair| compare(&pair[0].0, &pair[1].0) != Ok(std::cmp::Ordering::Less))
{
return Err(EncodeError::new(
&self.path,
EncodeErrorKind::Mismatch,
"holds two keys that are one value",
));
}
write_uint(self.out, wide(written.len()));
for (_, bytes) in written {
self.out.extend_from_slice(&bytes);
}
Ok(())
}
pub fn tuple(&mut self, ty: &Type, parts: &[&dyn Part]) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Form::Tuple(types) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
if types.len() != parts.len() {
return Err(self.mismatch(ty));
}
for (index, (part, each)) in types.iter().zip(parts).enumerate() {
self.at(|path| path.index(index), |me| each.write_part(me, part))?;
}
Ok(())
}
pub fn record(&mut self, ty: &Type, fields: &[&dyn Part]) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Some(record) = form(catalog, ty).record() else {
return Err(self.mismatch(ty));
};
if record.fields.len() != fields.len() {
return Err(self.mismatch(ty));
}
for ((name, field), each) in record.shape.fields().zip(&record.fields).zip(fields) {
self.at(|path| path.field(name), |me| each.write_part(me, field))?;
}
Ok(())
}
pub fn variant(
&mut self,
ty: &Type,
index: usize,
payload: &[&dyn Part],
) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Some(shape) = form(catalog, ty).enumeration() else {
return Err(self.mismatch(ty));
};
let (Some(types), Some(ctor)) = (shape.parts(index), shape.shape.constructor(index)) else {
return Err(self.mismatch(ty));
};
if types.len() != payload.len() {
return Err(self.mismatch(ty));
}
write_uint(self.out, wide(index));
self.at(
|path| path.constructor(ctor.name()),
|me| {
for (at, (part, each)) in types.iter().zip(payload).enumerate() {
me.at(
|path| payload_step(path, ctor.payload(), at),
|me| each.write_part(me, part),
)?;
}
Ok(())
},
)
}
pub fn newtype(&mut self, ty: &Type, base: &dyn Part) -> Result<(), EncodeError> {
let catalog = self.catalog;
let Form::Newtype(base_ty, held) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
let starts = self.out.len();
base.write_part(self, &base_ty)?;
let Some(held) = held else {
return Ok(());
};
let text = Reader::new(&self.out[starts..])
.text(&Limits::LANGUAGE)
.map_err(|error| {
EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem)
})?;
if let Some(problem) = held.refusal(text) {
self.out.truncate(starts);
return Err(EncodeError::new(
&self.path,
EncodeErrorKind::Mismatch,
problem,
));
}
Ok(())
}
pub fn encoded(&mut self, ty: &Type, bytes: &[u8]) -> Result<(), EncodeError> {
crate::decode_bytes(self.catalog, ty, bytes, Mode::Rebuild, &Limits::LANGUAGE).map_err(
|error| EncodeError::new(&self.path, EncodeErrorKind::Mismatch, error.problem),
)?;
self.out.extend_from_slice(bytes);
Ok(())
}
}
#[derive(Debug)]
pub struct Fields {
types: Vec<Type>,
step: Step,
at: usize,
}
#[derive(Debug)]
enum Step {
Index,
Field(Arc<RecordShape>),
Payload(Arc<EnumShape>, usize),
}
impl Fields {
pub fn read<T: Shaped>(
&mut self,
input: &mut ValueReader<'_, '_, '_>,
) -> Result<T, DecodeError> {
let Some(ty) = self.types.get(self.at) else {
return Err(input.refuse(
DecodeErrorKind::Mismatch,
"has fewer parts than the Rust type that reads it",
));
};
match &self.step {
Step::Index => input.path.index(self.at),
Step::Field(shape) => input
.path
.field(shape.field(self.at).expect("a name per field")),
Step::Payload(shape, index) => {
let ctor = shape.constructor(*index).expect("found when opened");
payload_step(&mut input.path, ctor.payload(), self.at);
}
}
let part = T::read_at(input, ty)?;
input.path.pop();
self.at += 1;
Ok(part)
}
}
impl<'b> ValueReader<'_, '_, 'b> {
pub fn catalog(&self) -> &Catalog {
self.catalog
}
pub fn mismatch(&self, ty: &Type) -> DecodeError {
self.refuse(
DecodeErrorKind::Mismatch,
format!(
"is a value of {}, which is none of the Rust type's that reads it",
self.catalog.name(ty)
),
)
}
fn scalar(&mut self, ty: &Type, scalar: Scalar) -> Result<(), DecodeError> {
if let Form::Scalar(found) = form(self.catalog, ty)
&& found == scalar
{
Ok(())
} else {
Err(self.mismatch(ty))
}
}
pub fn unit(&mut self, ty: &Type) -> Result<(), DecodeError> {
self.scalar(ty, Scalar::Unit)
}
pub fn bool(&mut self, ty: &Type) -> Result<bool, DecodeError> {
self.scalar(ty, Scalar::Bool)?;
self.reader.bool().map_err(|error| self.here(error))
}
pub fn int(&mut self, ty: &Type) -> Result<Int, DecodeError> {
self.scalar(ty, Scalar::Int)?;
self.reader
.int(self.limits)
.map(Int::from)
.map_err(|error| self.here(error))
}
fn exact(&mut self, ty: &Type, scalar: Scalar) -> Result<Decimal, DecodeError> {
self.scalar(ty, scalar)?;
read_decimal(self.reader, self.limits).map_err(|error| self.here(error))
}
pub fn decimal(&mut self, ty: &Type) -> Result<Decimal, DecodeError> {
self.exact(ty, Scalar::Decimal)
}
pub fn duration(&mut self, ty: &Type) -> Result<Duration, DecodeError> {
self.exact(ty, Scalar::Duration).map(Duration::from_seconds)
}
pub fn instant(&mut self, ty: &Type) -> Result<Instant, DecodeError> {
self.exact(ty, Scalar::Instant)
.map(Instant::from_unix_seconds)
}
pub fn text(&mut self, ty: &Type) -> Result<&'b str, DecodeError> {
if !matches!(form(self.catalog, ty), Form::Text) {
return Err(self.mismatch(ty));
}
self.reader
.text(self.limits)
.map_err(|error| self.here(error))
}
pub fn bytes(&mut self, ty: &Type) -> Result<&'b [u8], DecodeError> {
if !matches!(form(self.catalog, ty), Form::Bytes) {
return Err(self.mismatch(ty));
}
self.reader
.bytes(self.limits)
.map_err(|error| self.here(error))
}
pub fn host(&mut self, ty: &Type) -> Result<&'b str, DecodeError> {
if !matches!(form(self.catalog, ty), Form::Host) {
return Err(self.mismatch(ty));
}
self.reader
.text(self.limits)
.map_err(|error| self.here(error))
}
fn within<T>(
&mut self,
read: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
let outer = self.level;
self.level = self.enter(outer)?;
let read = read(self);
self.level = outer;
read
}
pub fn list<T: Shaped>(&mut self, ty: &Type) -> Result<Vec<T>, DecodeError> {
let catalog = self.catalog;
let Form::List(item) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
self.within(|me| {
let count = me.count(&[item])?;
let mut items = Vec::with_capacity(me.backed(count));
for index in 0..count {
me.path.index(index);
items.push(T::read_at(me, item)?);
me.path.pop();
}
Ok(items)
})
}
fn order(&self, ty: &Type, starts: usize) -> Result<Value, DecodeError> {
let mut reader = Reader::new(self.reader.since(starts));
ValueReader {
catalog: self.catalog,
limits: self.limits,
path: self.path.clone(),
reader: &mut reader,
zero_width_left: self.limits.text_bytes,
level: self.level,
}
.value(ty, self.level)
}
pub fn set<T: Shaped + Ord>(&mut self, ty: &Type) -> Result<BTreeSet<T>, DecodeError> {
let catalog = self.catalog;
let Form::Set(item) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
self.within(|me| {
let count = me.count(&[item])?;
let mut items = BTreeSet::new();
let mut previous = None;
for index in 0..count {
me.path.index(index);
let starts = me.reader.position();
items.insert(T::read_at(me, item)?);
let order = me.order(item, starts)?;
me.path.pop();
if let Some(before) = &previous {
me.after("element", index, before, &order)?;
}
previous = Some(order);
}
Ok(items)
})
}
pub fn dict<K: Shaped + Ord, V: Shaped>(
&mut self,
ty: &Type,
) -> Result<BTreeMap<K, V>, DecodeError> {
let catalog = self.catalog;
let Form::Dict(key, item) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
self.within(|me| {
let count = me.count(&[key, item])?;
let mut entries = BTreeMap::new();
let mut previous = None;
for index in 0..count {
me.path.index(index);
me.path.index(0);
let starts = me.reader.position();
let each = K::read_at(me, key)?;
let order = me.order(key, starts)?;
me.path.pop();
me.path.index(1);
let held = V::read_at(me, item)?;
me.path.pop();
me.path.pop();
if let Some(before) = &previous {
me.after("key", index, before, &order)?;
}
previous = Some(order);
entries.insert(each, held);
}
Ok(entries)
})
}
fn parts<T>(
&mut self,
ty: &Type,
mut fields: Fields,
read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
let value = read(self, &mut fields)?;
if fields.at == fields.types.len() {
Ok(value)
} else {
Err(self.mismatch(ty))
}
}
pub fn tuple<T>(
&mut self,
ty: &Type,
read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
let catalog = self.catalog;
let Form::Tuple(types) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
let fields = Fields {
types: types.to_vec(),
step: Step::Index,
at: 0,
};
self.within(|me| me.parts(ty, fields, read))
}
pub fn record<T>(
&mut self,
ty: &Type,
read: impl FnOnce(&mut Self, &mut Fields) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
let catalog = self.catalog;
let Some(record) = form(catalog, ty).record() else {
return Err(self.mismatch(ty));
};
let fields = Fields {
types: record.fields,
step: Step::Field(Arc::clone(record.shape)),
at: 0,
};
self.within(|me| me.parts(ty, fields, read))
}
pub fn variant<T>(
&mut self,
ty: &Type,
read: impl FnOnce(&mut Self, usize, &mut Fields) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
let catalog = self.catalog;
let Some(shape) = form(catalog, ty).enumeration() else {
return Err(self.mismatch(ty));
};
let index = self.reader.count().map_err(|error| self.here(error))?;
let (Some(types), Some(ctor)) = (shape.parts(index), shape.shape.constructor(index)) else {
return Err(self.refuse(
DecodeErrorKind::Mismatch,
format!(
"names constructor {index}, which {} does not have",
catalog.name(ty)
),
));
};
let fields = Fields {
types: types.into_iter().map(Cow::into_owned).collect(),
step: Step::Payload(Arc::clone(shape.shape), index),
at: 0,
};
self.within(|me| {
me.path.constructor(ctor.name());
let value = me.parts(ty, fields, |me, fields| read(me, index, fields))?;
me.path.pop();
Ok(value)
})
}
pub fn newtype<T: Shaped>(&mut self, ty: &Type) -> Result<T, DecodeError> {
let catalog = self.catalog;
let Form::Newtype(base, held) = form(catalog, ty) else {
return Err(self.mismatch(ty));
};
let starts = self.reader.position();
let value = T::read_at(self, &base)?;
if let Some(held) = held {
let text = Reader::new(self.reader.since(starts))
.text(self.limits)
.map_err(|error| self.here(error))?;
if let Some(problem) = held.refusal(text) {
return Err(self.refuse(DecodeErrorKind::Mismatch, problem));
}
}
Ok(value)
}
pub fn encoded(&mut self, ty: &Type) -> Result<&'b [u8], DecodeError> {
let starts = self.reader.position();
self.value(ty, self.level)?;
Ok(self.reader.since(starts))
}
}