use std::fmt::Write as _;
use crate::decimal::Decimal;
use crate::error::DataError;
use crate::text::Text;
use crate::value::Value;
use flow_types::Payload;
pub fn interpolate(value: &Value) -> Result<Text, DataError> {
Ok(interpolate_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
}
pub fn interpolate_within(value: &Value, max_bytes: usize) -> Result<Option<Text>, DataError> {
let unquoted = |text: String| text[1..text.len() - 1].to_owned();
match value {
Value::Text(text) => Ok((text.byte_len() <= max_bytes).then(|| text.clone())),
Value::Bytes(_) | Value::Duration(_) | Value::Instant(_) => {
Ok(text_form_within(value, max_bytes.saturating_add(2))?
.map(|text| Text::from(unquoted(text))))
}
other => Ok(text_form_within(other, max_bytes)?.map(Text::from)),
}
}
pub fn text_form(value: &Value) -> Result<String, DataError> {
Ok(text_form_within(value, usize::MAX)?.expect("no text is longer than usize::MAX bytes"))
}
pub fn text_form_within(value: &Value, max_bytes: usize) -> Result<Option<String>, DataError> {
spell_within(&TextForm, (), value, max_bytes)
}
pub trait Spelling<'a> {
type At;
fn newtype(&self, at: &Self::At) -> Option<(&'a str, Self::At)>;
fn part(&self, at: &Self::At, part: Part) -> Self::At;
fn decimal(&self, out: &mut String, number: &Decimal);
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Part {
Item,
Key,
Entry,
Tuple(usize),
Field(usize),
Payload {
constructor: usize,
part: usize,
},
}
struct TextForm;
impl<'a> Spelling<'a> for TextForm {
type At = ();
fn newtype(&self, (): &()) -> Option<(&'a str, ())> {
None
}
fn part(&self, (): &(), _: Part) {}
fn decimal(&self, out: &mut String, number: &Decimal) {
write!(out, "{number}").expect("writing to a String");
}
}
pub fn spell_within<'a, S: Spelling<'a>>(
spelling: &S,
at: S::At,
value: &'a Value,
max_bytes: usize,
) -> Result<Option<String>, DataError> {
let mut out = String::new();
let mut pending = vec![Piece::Value(value, at)];
while let Some(piece) = pending.pop() {
match piece {
Piece::Str(text) => out.push_str(text),
Piece::Value(value, _) if at_least_len(value) > room(max_bytes, out.len()) => {
return Ok(None);
}
Piece::Value(value, at) => write_value(spelling, &mut out, value, &at, &mut pending)?,
}
if out.len() > max_bytes {
return Ok(None);
}
}
Ok(Some(out))
}
fn room(max_bytes: usize, written: usize) -> u128 {
u128::try_from(max_bytes - written).expect("a usize fits 128 bits")
}
fn at_least_len(value: &Value) -> u128 {
let widen = |n: usize| u128::try_from(n).expect("a usize fits 128 bits");
match value {
Value::Text(text) => widen(text.byte_len()) + 2,
Value::Bytes(bytes) => widen(bytes.len().div_ceil(3)) * 4 + 2,
Value::Decimal(number) => number.text_len(),
Value::Duration(span) => span.seconds().text_len() + 3,
Value::Instant(at) => at.unix_seconds().text_len().saturating_sub(16),
_ => 0,
}
}
enum Piece<'a, A> {
Str(&'a str),
Value(&'a Value, A),
}
fn write_value<'a, S: Spelling<'a>>(
spelling: &S,
out: &mut String,
value: &'a Value,
at: &S::At,
pending: &mut Vec<Piece<'a, S::At>>,
) -> Result<(), DataError> {
let mut pieces: Vec<Piece<'a, S::At>> = Vec::new();
if let Some((name, base)) = spelling.newtype(at) {
pieces.extend([
Piece::Str(name),
Piece::Str("("),
Piece::Value(value, base),
Piece::Str(")"),
]);
pending.extend(pieces.into_iter().rev());
return Ok(());
}
let part = |part: Part| spelling.part(at, part);
match value {
Value::Unit => out.push_str("()"),
Value::Bool(flag) => out.push_str(if *flag { "true" } else { "false" }),
Value::Int(number) => write!(out, "{number}").expect("writing to a String"),
Value::Decimal(number) => spelling.decimal(out, number),
Value::Text(text) => write_literal(out, text.as_str()),
Value::Bytes(bytes) => {
write!(out, "\"{}\"", bytes.to_base64()).expect("writing to a String");
}
Value::Duration(span) => write!(out, "\"{span}\"").expect("writing to a String"),
Value::Instant(at) => write!(out, "\"{at}\"").expect("writing to a String"),
Value::List(items) => all(
&mut pieces,
"[",
items.iter().map(|item| (item, part(Part::Item))),
"]",
),
Value::Set(items) => all(
&mut pieces,
"[",
items.iter().map(|item| (item, part(Part::Item))),
"]",
),
Value::Tuple(tuple) => all(
&mut pieces,
"(",
tuple
.parts()
.iter()
.enumerate()
.map(|(at, item)| (item, part(Part::Tuple(at)))),
")",
),
Value::Dict(entries) if entries.is_empty() => out.push_str("[:]"),
Value::Dict(entries) => {
pieces.push(Piece::Str("["));
for (at, (key, item)) in entries.iter().enumerate() {
if at > 0 {
pieces.push(Piece::Str(", "));
}
pieces.extend([
Piece::Value(key, part(Part::Key)),
Piece::Str(": "),
Piece::Value(item, part(Part::Entry)),
]);
}
pieces.push(Piece::Str("]"));
}
Value::Record(record) => {
pieces.push(Piece::Str(record.shape().name()));
named(
&mut pieces,
record.shape().fields(),
record
.fields()
.iter()
.enumerate()
.map(|(at, field)| (field, part(Part::Field(at)))),
);
}
Value::Variant(variant) => {
let constructor = variant.constructor();
let payload = variant.payload().iter().enumerate().map(|(at, item)| {
let at = Part::Payload {
constructor: variant.index(),
part: at,
};
(item, part(at))
});
pieces.push(Piece::Str(constructor.name()));
match constructor.payload() {
Payload::None => {}
Payload::Positional(_) => all(&mut pieces, "(", payload, ")"),
Payload::Named(fields) => {
named(&mut pieces, fields.iter().map(|field| &**field), payload);
}
}
}
Value::Native(_) | Value::Task(_) | Value::Host(_) => return Err(DataError::NotData),
}
pending.extend(pieces.into_iter().rev());
Ok(())
}
fn all<'a, A>(
pieces: &mut Vec<Piece<'a, A>>,
open: &'a str,
items: impl Iterator<Item = (&'a Value, A)>,
close: &'a str,
) {
pieces.push(Piece::Str(open));
for (at, (item, known)) in items.enumerate() {
if at > 0 {
pieces.push(Piece::Str(", "));
}
pieces.push(Piece::Value(item, known));
}
pieces.push(Piece::Str(close));
}
fn named<'a, A>(
pieces: &mut Vec<Piece<'a, A>>,
names: impl Iterator<Item = &'a str>,
values: impl ExactSizeIterator<Item = (&'a Value, A)>,
) {
if values.len() == 0 {
pieces.push(Piece::Str(" {}"));
return;
}
pieces.push(Piece::Str(" { "));
for (at, (name, (item, known))) in names.zip(values).enumerate() {
if at > 0 {
pieces.push(Piece::Str(", "));
}
pieces.extend([
Piece::Str(name),
Piece::Str(": "),
Piece::Value(item, known),
]);
}
pieces.push(Piece::Str(" }"));
}
fn write_literal(out: &mut String, text: &str) {
out.push('"');
let mut code_points = text.chars().peekable();
while let Some(code_point) = code_points.next() {
match code_point {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
'$' if code_points.peek() == Some(&'{') => out.push_str("\\$"),
'\u{0}'..='\u{1f}' | '\u{7f}' => {
write!(out, "\\u{{{:X}}}", u32::from(code_point)).expect("writing to a String");
}
other => out.push(other),
}
}
out.push('"');
}