use std::borrow::Cow;
use std::cmp::Ordering;
use std::sync::Arc;
use flow_types::Payload;
use flow_value::{
Bytes, Decimal, Dict, Duration, HostToken, Instant, Int, Set, Text, Value, compare,
};
use crate::build::{Begun, Frame, Make, Source, Walk, build};
use crate::bytes::{Reader, wide, write_bytes, write_int, write_signed, write_text, write_uint};
use crate::catalog::{Catalog, StdForm};
use crate::decode::{Mode, decodable};
use crate::error::{DecodeError, DecodeErrorKind, EncodeError, EncodeErrorKind, Place};
use crate::form::{EnumForm, Form, Scalar, form};
use crate::limits::Limits;
use flow_types::Type;
pub fn encode_bytes(catalog: &Catalog, ty: &Type, value: &Value) -> Result<Vec<u8>, EncodeError> {
let mut out = Vec::new();
write_value(&mut out, catalog, ty, value)?;
Ok(out)
}
pub fn write_value(
out: &mut Vec<u8>,
catalog: &Catalog,
ty: &Type,
value: &Value,
) -> Result<(), EncodeError> {
ValueWriter {
catalog,
out,
path: Place::default(),
}
.value(ty, value)
}
pub fn write_scalar(out: &mut Vec<u8>, scalar: Scalar, value: &Value) -> Result<(), EncodeError> {
scalar_into(out, scalar, value).ok_or_else(|| {
EncodeError::new(
&Place::default(),
EncodeErrorKind::Mismatch,
format!("is not a value of {}", scalar_name(scalar)),
)
})
}
fn scalar_into(out: &mut Vec<u8>, scalar: Scalar, value: &Value) -> Option<()> {
match (scalar, value) {
(Scalar::Unit, Value::Unit) => {}
(Scalar::Bool, Value::Bool(flag)) => out.push(u8::from(*flag)),
(Scalar::Int, Value::Int(number)) => write_int(out, number.as_bigint()),
(Scalar::Decimal, Value::Decimal(number)) => decimal_into(out, number),
(Scalar::Duration, Value::Duration(span)) => decimal_into(out, span.seconds()),
(Scalar::Instant, Value::Instant(at)) => decimal_into(out, at.unix_seconds()),
_ => return None,
}
Some(())
}
pub(crate) fn decimal_into(out: &mut Vec<u8>, number: &Decimal) {
write_int(out, number.coefficient());
write_signed(out, number.exponent());
}
fn scalar_name(scalar: Scalar) -> &'static str {
match scalar {
Scalar::Unit => "Unit",
Scalar::Bool => "Bool",
Scalar::Int => "Int",
Scalar::Decimal => "Decimal",
Scalar::Duration => "Duration",
Scalar::Instant => "Instant",
}
}
fn same<T: PartialEq>(a: &Arc<T>, b: &Arc<T>) -> bool {
Arc::ptr_eq(a, b) || a == b
}
#[derive(Debug)]
pub struct ValueWriter<'c, 'o> {
pub(crate) catalog: &'c Catalog,
pub(crate) out: &'o mut Vec<u8>,
pub(crate) path: Place,
}
impl<'c> ValueWriter<'c, '_> {
pub(crate) fn mismatch(&self, ty: &Type) -> EncodeError {
EncodeError::new(
&self.path,
EncodeErrorKind::Mismatch,
format!("is not a value of {}", self.catalog.name(ty)),
)
}
pub(crate) fn at(
&mut self,
step: impl FnOnce(&mut Place),
go: impl FnOnce(&mut Self) -> Result<(), EncodeError>,
) -> Result<(), EncodeError> {
step(&mut self.path);
go(self)?;
self.path.pop();
Ok(())
}
fn value(&mut self, ty: &Type, value: &Value) -> Result<(), EncodeError> {
let root = self.begin(&Cow::Borrowed(ty), value)?;
build(self, root)
}
#[inline]
fn begin<'a>(
&mut self,
ty: &Cow<'a, Type>,
value: &'a Value,
) -> Result<Writing<'a>, EncodeError>
where
'c: 'a,
{
match ty {
Cow::Borrowed(ty) => self.open(form(self.catalog, ty), ty, value, Cow::Borrowed),
Cow::Owned(ty) => self.open(form(self.catalog, ty), ty, value, |part: &Type| {
Cow::Owned(part.clone())
}),
}
}
#[inline]
fn open<'f, 'a>(
&mut self,
form: Form<'f>,
ty: &Type,
value: &'a Value,
keep: impl Fn(&'f Type) -> Cow<'a, Type>,
) -> Result<Writing<'a>, EncodeError>
where
'c: 'a,
{
match self.leaf(&form, ty, value) {
Some(written) => written.map(Begun::Done),
None => self.open_aggregate(form, ty, value, keep),
}
}
#[inline]
fn leaf(
&mut self,
form: &Form<'_>,
ty: &Type,
value: &Value,
) -> Option<Result<(), EncodeError>> {
match (form, value) {
(Form::Scalar(scalar), _) => {
return Some(
scalar_into(self.out, *scalar, value).ok_or_else(|| self.mismatch(ty)),
);
}
(Form::Text, Value::Text(text)) => write_text(self.out, text.as_str()),
(Form::Bytes, Value::Bytes(bytes)) => write_bytes(self.out, bytes.as_slice()),
(Form::Host, Value::Host(token)) => write_text(self.out, token.as_str()),
(Form::Text | Form::Bytes | Form::Host, _) => return Some(Err(self.mismatch(ty))),
_ => return None,
}
Some(Ok(()))
}
fn open_aggregate<'f, 'a>(
&mut self,
form: Form<'f>,
ty: &Type,
value: &'a Value,
keep: impl Fn(&'f Type) -> Cow<'a, Type>,
) -> Result<Writing<'a>, EncodeError>
where
'c: 'a,
{
let (make, types) = match (form, value) {
(Form::List(item), Value::List(items)) => {
write_uint(self.out, wide(items.len()));
(Make::List, Parts::Items(keep(item), items.len()))
}
(Form::Set(item), Value::Set(items)) => {
write_uint(self.out, wide(items.len()));
(Make::Set, Parts::Items(keep(item), items.len()))
}
(Form::Dict(key, item), Value::Dict(entries)) => {
write_uint(self.out, wide(entries.len()));
(
Make::Dict,
Parts::Entries(keep(key), keep(item), entries.len()),
)
}
(Form::Tuple(parts), Value::Tuple(tuple)) if parts.len() == tuple.parts().len() => {
(Make::Tuple, Parts::Each(parts.iter().map(keep).collect()))
}
(Form::Record(record), Value::Record(value)) if same(value.shape(), record.shape) => {
let fields = record.fields.into_iter().map(Cow::Owned).collect();
(Make::Record(Arc::clone(record.shape)), Parts::Each(fields))
}
(Form::Enum(shape), Value::Variant(variant)) if same(variant.shape(), shape.shape) => {
let parts = shape
.parts(variant.index())
.expect("a variant's constructor is its shape's");
write_uint(self.out, wide(variant.index()));
self.path.constructor(variant.constructor().name());
let parts = parts.into_iter().map(|part| kept(part, &keep)).collect();
let make = Make::Variant(Arc::clone(shape.shape), variant.index());
(make, Parts::Each(parts))
}
(Form::Newtype(base, held), _) => {
if let Some(problem) = StdForm::out_of(held, value) {
return Err(EncodeError::new(
&self.path,
EncodeErrorKind::Mismatch,
problem,
));
}
return self.begin(&Cow::Owned(base), value);
}
(Form::Task(_) | Form::NoEncoding, _) => {
return Err(EncodeError::new(
&self.path,
EncodeErrorKind::NoEncoding,
"has a type with no encoding",
));
}
_ => return Err(self.mismatch(ty)),
};
Ok(Frame::open(make, Writes { types, value }, 0, 0))
}
}
type Writing<'a> = Begun<Writes<'a>, Make, ()>;
struct Writes<'a> {
types: Parts<'a>,
value: &'a Value,
}
impl<'a, 'c: 'a> Walk<Writes<'a>, Make, ()> for ValueWriter<'c, '_> {
type Error = EncodeError;
fn path(&mut self) -> &mut Place {
&mut self.path
}
fn next(
&mut self,
frame: &mut Frame<Writes<'a>, Make, ()>,
) -> Result<Option<Writing<'a>>, EncodeError> {
if let Parts::Items(item, count) = &frame.parts.types
&& frame.values.is_empty()
&& !matches!(**item, Type::Named(..))
{
let form = form(self.catalog, item);
if matches!(
form,
Form::Scalar(_) | Form::Text | Form::Bytes | Form::Host
) {
for (at, value) in frame.parts.value.parts().enumerate() {
self.path.index(at);
self.leaf(&form, item, value)
.expect("a form that holds no other value")?;
self.path.pop();
}
frame.values.resize(*count, ());
return Ok(None);
}
}
loop {
let at = frame.values.len();
let Some(ty) = next_part(&frame.parts.types, &frame.make, at, &mut self.path) else {
return Ok(None);
};
let value = frame
.parts
.value
.part(at)
.expect("a value holds a part for each of its type's");
match self.begin(ty, value)? {
Begun::Done(()) => {
frame.values.push(());
for _ in 0..part_steps(&frame.parts.types, frame.values.len()) {
self.path.pop();
}
}
open @ Begun::Open(_) => return Ok(Some(open)),
}
}
}
fn steps(frame: &Frame<Writes<'a>, Make, ()>) -> usize {
part_steps(&frame.parts.types, frame.values.len())
}
fn finish(&mut self, frame: Frame<Writes<'a>, Make, ()>) -> Result<(), EncodeError> {
if let Make::Variant(..) = frame.make {
self.path.pop();
}
Ok(())
}
}
pub(crate) fn payload_step(path: &mut Place, payload: &Payload, index: usize) {
match payload {
Payload::Named(names) => path.field(&names[index]),
_ => path.index(index),
}
}
pub fn decode_bytes(
catalog: &Catalog,
ty: &Type,
bytes: &[u8],
mode: Mode,
limits: &Limits,
) -> Result<Value, DecodeError> {
let mut reader = Reader::new(bytes);
let value = read_value(&mut reader, catalog, ty, mode, limits)?;
if !reader.is_empty() {
return Err(DecodeError::of(
&Place::default(),
DecodeErrorKind::Syntax {
at: reader.position(),
},
format!(
"ends at byte {}, before the {} bytes given do",
reader.position(),
bytes.len()
),
));
}
Ok(value)
}
pub fn read_value(
reader: &mut Reader<'_>,
catalog: &Catalog,
ty: &Type,
mode: Mode,
limits: &Limits,
) -> Result<Value, DecodeError> {
decodable(catalog, ty, mode.settings())?;
ValueReader {
catalog,
limits,
path: Place::default(),
reader,
zero_width_left: limits.text_bytes,
level: 0,
}
.value(ty, 0)
}
pub fn read_scalar(
reader: &mut Reader<'_>,
scalar: Scalar,
limits: &Limits,
) -> Result<Value, DecodeError> {
Ok(match scalar {
Scalar::Unit => Value::Unit,
Scalar::Bool => Value::Bool(reader.bool()?),
Scalar::Int => Value::Int(Int::from(reader.int(limits)?)),
Scalar::Decimal => Value::Decimal(read_decimal(reader, limits)?),
Scalar::Duration => Value::Duration(Duration::from_seconds(read_decimal(reader, limits)?)),
Scalar::Instant => {
Value::Instant(Instant::from_unix_seconds(read_decimal(reader, limits)?))
}
})
}
pub fn write_instant(out: &mut Vec<u8>, at: &Instant) {
decimal_into(out, at.unix_seconds());
}
pub fn read_instant(reader: &mut Reader<'_>, limits: &Limits) -> Result<Instant, DecodeError> {
Ok(Instant::from_unix_seconds(read_decimal(reader, limits)?))
}
pub(crate) fn read_decimal(
reader: &mut Reader<'_>,
limits: &Limits,
) -> Result<Decimal, DecodeError> {
let at = reader.position();
let coefficient = reader.int(limits)?;
let exponent = reader.signed()?;
let unnormalized = || {
DecodeError::of(
&Place::default(),
DecodeErrorKind::Syntax { at },
format!("has a Decimal that is not normalized at byte {at}"),
)
};
let normalized = if coefficient.magnitude().bits() == 0 {
exponent == 0
} else {
(coefficient.magnitude() % 10u32).bits() != 0
};
if !normalized {
return Err(unnormalized());
}
let number = Decimal::new(coefficient, exponent).map_err(|_| unnormalized())?;
debug_assert_eq!(number.exponent(), exponent, "already normalized");
Ok(number)
}
#[derive(Debug)]
pub struct ValueReader<'c, 'r, 'b> {
pub(crate) catalog: &'c Catalog,
pub(crate) limits: &'c Limits,
pub(crate) path: Place,
pub(crate) reader: &'r mut Reader<'b>,
pub(crate) zero_width_left: usize,
pub(crate) level: usize,
}
impl<'c> ValueReader<'c, '_, '_> {
pub(crate) fn refuse(&self, kind: DecodeErrorKind, problem: impl Into<String>) -> DecodeError {
DecodeError::of(&self.path, kind, problem.into())
}
pub(crate) fn here(&self, mut error: DecodeError) -> DecodeError {
error.path = self.path.clone();
error
}
pub(crate) fn enter(&self, level: usize) -> Result<usize, DecodeError> {
let level = level + 1;
if level > self.limits.depth {
return Err(self.refuse(
DecodeErrorKind::TooLarge,
format!("nests deeper than {} levels", self.limits.depth),
));
}
Ok(level)
}
pub(crate) fn value(&mut self, ty: &Type, level: usize) -> Result<Value, DecodeError> {
let root = self.begin(&Cow::Borrowed(ty), level)?;
build(self, root)
}
fn begin<'t>(
&mut self,
ty: &Cow<'t, Type>,
level: usize,
) -> Result<Begun<Parts<'t>>, DecodeError>
where
'c: 't,
{
match ty {
Cow::Borrowed(ty) => self.open(form(self.catalog, ty), ty, level, Cow::Borrowed),
Cow::Owned(ty) => self.open(form(self.catalog, ty), ty, level, |part: &Type| {
Cow::Owned(part.clone())
}),
}
}
fn open<'f, 't>(
&mut self,
form: Form<'f>,
ty: &Type,
level: usize,
keep: impl Fn(&'f Type) -> Cow<'t, Type>,
) -> Result<Begun<Parts<'t>>, DecodeError> {
let value = match form {
Form::Scalar(scalar) => {
read_scalar(self.reader, scalar, self.limits).map_err(|error| self.here(error))?
}
Form::Text => {
let text = self
.reader
.text(self.limits)
.map_err(|error| self.here(error))?;
Value::Text(Text::new(text))
}
Form::Bytes => {
let bytes = self
.reader
.bytes(self.limits)
.map_err(|error| self.here(error))?;
Value::Bytes(Bytes::new(bytes))
}
Form::Host => {
let token = self
.reader
.text(self.limits)
.map_err(|error| self.here(error))?;
Value::Host(HostToken::new(token))
}
Form::List(item) => {
let level = self.enter(level)?;
let count = self.count(&[item])?;
let room = self.backed(count);
return Ok(Frame::open(
Make::List,
Parts::Items(keep(item), count),
room,
level,
));
}
Form::Set(item) => {
let level = self.enter(level)?;
let count = self.count(&[item])?;
let room = self.backed(count);
return Ok(Frame::open(
Make::Set,
Parts::Items(keep(item), count),
room,
level,
));
}
Form::Dict(key, item) => {
let level = self.enter(level)?;
let count = self.count(&[key, item])?;
let room = self.backed(count).saturating_mul(2);
let parts = Parts::Entries(keep(key), keep(item), count);
return Ok(Frame::open(Make::Dict, parts, room, level));
}
Form::Tuple(parts) => {
let level = self.enter(level)?;
let parts = Parts::Each(parts.iter().map(keep).collect());
return Ok(Frame::open(Make::Tuple, parts, 0, level));
}
Form::Record(record) => {
let level = self.enter(level)?;
let make = Make::Record(Arc::clone(record.shape));
let fields = record.fields.into_iter().map(Cow::Owned).collect();
return Ok(Frame::open(make, Parts::Each(fields), 0, level));
}
Form::Enum(shape) => return self.begin_variant(ty, &shape, level, keep),
Form::Newtype(base, held) => {
let parts = Parts::One(Cow::Owned(base));
return Ok(Frame::open(Make::Newtype(held), parts, 1, level));
}
Form::NoEncoding => {
return Err(self.refuse(
DecodeErrorKind::Mismatch,
"has a type with no encoding, so it holds no value",
));
}
Form::Never | Form::Task(_) => {
return Err(self.refuse(
DecodeErrorKind::Mismatch,
"has a type with no values to decode",
));
}
};
Ok(Begun::Done(value))
}
pub(crate) fn count(&mut self, types: &[&Type]) -> Result<usize, DecodeError> {
let count = self.reader.count().map_err(|error| self.here(error))?;
if types.iter().all(|ty| empty(self.catalog, ty, 0)) {
let Some(left) = self.zero_width_left.checked_sub(count) else {
return Err(self.refuse(
DecodeErrorKind::TooLarge,
format!(
"holds more than {} elements written in no bytes",
self.limits.text_bytes
),
));
};
self.zero_width_left = left;
} else if count > self.reader.remaining() {
return Err(self.refuse(
DecodeErrorKind::Mismatch,
format!(
"holds {count} elements, more than the {} bytes left can",
self.reader.remaining()
),
));
}
Ok(count)
}
pub(crate) fn backed(&self, count: usize) -> usize {
count.min(self.reader.remaining())
}
pub(crate) fn ascending<'v>(
&self,
what: &str,
items: impl Iterator<Item = &'v Value>,
) -> Result<(), DecodeError> {
let mut previous: Option<&Value> = None;
for (index, item) in items.enumerate() {
if let Some(before) = previous {
self.after(what, index, before, item)?;
}
previous = Some(item);
}
Ok(())
}
pub(crate) fn after(
&self,
what: &str,
index: usize,
before: &Value,
item: &Value,
) -> Result<(), DecodeError> {
match compare(before, item) {
Ok(Ordering::Less) => Ok(()),
Ok(Ordering::Equal) => Err(self.refuse(
DecodeErrorKind::Duplicate,
format!("repeats {what} {}", index - 1),
)),
Ok(Ordering::Greater) => Err(self.refuse(
DecodeErrorKind::Mismatch,
format!(
"has {what} {index} out of ascending order, after {what} {}",
index - 1
),
)),
Err(_) => Err(self.refuse(
DecodeErrorKind::Mismatch,
format!("has {what}s that are not data"),
)),
}
}
fn begin_variant<'f, 't>(
&mut self,
ty: &Type,
shape: &EnumForm<'f>,
level: usize,
keep: impl Fn(&'f Type) -> Cow<'t, Type>,
) -> Result<Begun<Parts<'t>>, DecodeError> {
let index = self.reader.count().map_err(|error| self.here(error))?;
let Some(parts) = shape.parts(index) else {
return Err(self.refuse(
DecodeErrorKind::Mismatch,
format!(
"names constructor {index}, which {} does not have",
self.catalog.name(ty)
),
));
};
let level = self.enter(level)?;
let ctor = shape.shape.constructor(index).expect("found above");
self.path.constructor(ctor.name());
let make = Make::Variant(Arc::clone(shape.shape), index);
let parts = parts.into_iter().map(|part| kept(part, &keep)).collect();
Ok(Frame::open(make, Parts::Each(parts), 0, level))
}
}
enum Parts<'t> {
Items(Cow<'t, Type>, usize),
Each(Vec<Cow<'t, Type>>),
Entries(Cow<'t, Type>, Cow<'t, Type>, usize),
One(Cow<'t, Type>),
}
fn kept<'f, 't>(part: Cow<'f, Type>, keep: impl Fn(&'f Type) -> Cow<'t, Type>) -> Cow<'t, Type> {
match part {
Cow::Borrowed(part) => keep(part),
Cow::Owned(part) => Cow::Owned(part),
}
}
#[inline]
fn next_part<'p, 't>(
parts: &'p Parts<'t>,
make: &Make,
at: usize,
path: &mut Place,
) -> Option<&'p Cow<'t, Type>> {
match parts {
Parts::Items(item, count) => {
if at == *count {
return None;
}
path.index(at);
Some(item)
}
Parts::Each(types) => {
let ty = types.get(at)?;
match make {
Make::Record(shape) => path.field(shape.field(at).expect("a name per field")),
Make::Variant(shape, index) | Make::Unwritten(shape, index) => {
let ctor = shape.constructor(*index).expect("found when opened");
payload_step(path, ctor.payload(), at);
}
Make::Tuple | Make::List | Make::Set | Make::Dict | Make::Newtype(_) => {
path.index(at);
}
}
Some(ty)
}
Parts::Entries(key, item, count) => {
if at / 2 == *count {
return None;
}
if at.is_multiple_of(2) {
path.index(at / 2);
path.index(0);
Some(key)
} else {
path.index(1);
Some(item)
}
}
Parts::One(ty) => (at == 0).then_some(ty),
}
}
fn part_steps(parts: &Parts<'_>, done: usize) -> usize {
match parts {
Parts::One(_) => 0,
Parts::Entries(..) if done % 2 == 1 => 1,
Parts::Entries(..) => 2,
Parts::Items(..) | Parts::Each(_) => 1,
}
}
impl<'t, 'c: 't> Source<Parts<'t>> for ValueReader<'c, '_, '_> {
fn path(&mut self) -> &mut Place {
&mut self.path
}
fn next(
&mut self,
frame: &mut Frame<Parts<'t>>,
) -> Result<Option<Begun<Parts<'t>>>, DecodeError> {
let at = frame.values.len();
let Some(ty) = next_part(&frame.parts, &frame.make, at, &mut self.path) else {
return Ok(None);
};
self.begin(ty, frame.level).map(Some)
}
fn steps(frame: &Frame<Parts<'t>>) -> usize {
part_steps(&frame.parts, frame.values.len())
}
fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError> {
self.ascending("element", items.iter())?;
Ok(Set::from_items(items).expect("decoded values are data"))
}
fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError> {
self.ascending("key", entries.iter().map(|(key, _)| key))?;
Ok(Dict::from_entries(entries).expect("decoded keys are data"))
}
fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError> {
match form.refusal(text.as_str()) {
Some(problem) => Err(self.refuse(DecodeErrorKind::Mismatch, problem)),
None => Ok(Value::Text(text)),
}
}
}
fn empty(catalog: &Catalog, ty: &Type, depth: usize) -> bool {
if depth > 32 {
return false;
}
match form(catalog, ty) {
Form::Scalar(Scalar::Unit) => true,
Form::Tuple(parts) => parts.iter().all(|part| empty(catalog, part, depth + 1)),
Form::Record(record) => record
.fields
.iter()
.all(|field| empty(catalog, field, depth + 1)),
Form::Newtype(base, _) => empty(catalog, &base, depth + 1),
_ => false,
}
}