use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;
use std::sync::LazyLock;
use flow_abi::{Catalog, Json, Limits, Mode, Type};
use flow_value::{Constructor, Decimal, Duration, EnumShape, Instant, Int, Payload, Value};
pub use flow_abi::DecodeError;
pub fn parse_json(text: &str) -> Result<Json, DecodeError> {
flow_abi::parse(text, &LIMITS)
}
pub trait Data: Sized {
const TEXT: bool = false;
fn encode(&self) -> Json;
fn decode(json: &Json) -> Result<Self, DecodeError>;
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub struct Bytes(pub Vec<u8>);
impl From<Vec<u8>> for Bytes {
fn from(bytes: Vec<u8>) -> Self {
Bytes(bytes)
}
}
impl From<&[u8]> for Bytes {
fn from(bytes: &[u8]) -> Self {
Bytes(bytes.to_vec())
}
}
pub fn refused(problem: impl Into<String>) -> DecodeError {
DecodeError {
path: String::new(),
problem: problem.into(),
kind: flow_abi::DecodeErrorKind::Invalid,
}
}
pub fn inside(mut error: DecodeError, step: &str) -> DecodeError {
error.path = if error.path.is_empty() {
step.to_owned()
} else if error.path.starts_with('[') {
format!("{step}{}", error.path)
} else {
format!("{step}.{}", error.path)
};
error
}
pub fn within<T>(
json: &Json,
step: &str,
read: impl FnOnce(&Json) -> Result<T, DecodeError>,
) -> Result<T, DecodeError> {
read(json).map_err(|error| inside(error, step))
}
fn expected(what: &str, json: &Json) -> DecodeError {
refused(format!("should be {what}, not {}", json.kind()))
}
pub(crate) const LIMITS: Limits = Limits {
depth: 1_024,
int_bits: 16_777_216,
text_bytes: 1_073_741_824,
};
fn scalar<T>(ty: &Type, json: &Json, take: fn(Value) -> Option<T>) -> Result<T, DecodeError> {
static CATALOG: LazyLock<Catalog> = LazyLock::new(|| {
let option = EnumShape::new(
"Option",
[
Constructor::new("None", Payload::None),
Constructor::new("Some", Payload::Positional(1)),
],
);
Catalog::new(Vec::new(), option, None).expect("std's Option has None and Some")
});
let value = flow_abi::decode(&CATALOG, ty, json, Mode::Reply, &LIMITS)?;
Ok(take(value).expect("the decoder builds the type it is asked for"))
}
impl Data for Int {
fn encode(&self) -> Json {
Json::Number(Decimal::from(self))
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
scalar(&Type::Int, json, |value| match value {
Value::Int(int) => Some(int),
_ => None,
})
}
}
impl Data for Decimal {
fn encode(&self) -> Json {
Json::Number(self.clone())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
match json {
Json::Number(number) => Ok(number.clone()),
other => Err(expected("a number", other)),
}
}
}
impl Data for bool {
fn encode(&self) -> Json {
Json::Bool(*self)
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
match json {
Json::Bool(value) => Ok(*value),
other => Err(expected("a boolean", other)),
}
}
}
impl Data for String {
const TEXT: bool = true;
fn encode(&self) -> Json {
Json::String(self.clone())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
match json {
Json::String(text) => Ok(text.clone()),
other => Err(expected("a string", other)),
}
}
}
impl Data for Bytes {
fn encode(&self) -> Json {
Json::String(flow_value::Bytes::new(&self.0).to_base64())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
scalar(&Type::Bytes, json, |value| match value {
Value::Bytes(bytes) => Some(Bytes(bytes.as_slice().to_vec())),
_ => None,
})
}
}
impl Data for Duration {
fn encode(&self) -> Json {
Json::String(self.to_string())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
scalar(&Type::Duration, json, |value| match value {
Value::Duration(duration) => Some(duration),
_ => None,
})
}
}
impl Data for Instant {
fn encode(&self) -> Json {
Json::String(self.to_string())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
scalar(&Type::Instant, json, |value| match value {
Value::Instant(instant) => Some(instant),
_ => None,
})
}
}
impl Data for () {
fn encode(&self) -> Json {
Json::Array(Vec::new())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
match json {
Json::Array(items) if items.is_empty() => Ok(()),
other => Err(expected("the empty array", other)),
}
}
}
impl Data for Infallible {
fn encode(&self) -> Json {
match *self {}
}
fn decode(_: &Json) -> Result<Self, DecodeError> {
Err(refused("is of `Never`, which has no values"))
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum JsonValue {
Null,
Bool(bool),
Number(Decimal),
Text(String),
List(Vec<JsonValue>),
Object(BTreeMap<String, JsonValue>),
}
impl Data for JsonValue {
fn encode(&self) -> Json {
match self {
JsonValue::Null => Json::Null,
JsonValue::Bool(value) => Json::Bool(*value),
JsonValue::Number(number) => Json::Number(number.clone()),
JsonValue::Text(text) => Json::String(text.clone()),
JsonValue::List(items) => Json::Array(items.iter().map(Data::encode).collect()),
JsonValue::Object(members) => Json::Object(
members
.iter()
.map(|(key, value)| (key.clone(), value.encode()))
.collect(),
),
}
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
Ok(match json {
Json::Null => JsonValue::Null,
Json::Bool(value) => JsonValue::Bool(*value),
Json::Number(number) => JsonValue::Number(number.clone()),
Json::String(text) => JsonValue::Text(text.clone()),
Json::Array(_) => JsonValue::List(elements(json)?),
Json::Object(members) => {
let mut object = BTreeMap::new();
for (key, value) in members {
let step = format!("[{}]", Json::String(key.clone()).canonical());
if object
.insert(key.clone(), within(value, &step, JsonValue::decode)?)
.is_some()
{
return Err(inside(refused("repeats a key already given"), &step));
}
}
JsonValue::Object(object)
}
})
}
}
impl Data for Json {
fn encode(&self) -> Json {
self.clone()
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
Ok(json.clone())
}
}
impl<T: Data> Data for Box<T> {
fn encode(&self) -> Json {
(**self).encode()
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
T::decode(json).map(Box::new)
}
}
fn elements<T: Data, C: FromIterator<T>>(json: &Json) -> Result<C, DecodeError> {
match json {
Json::Array(items) => items
.iter()
.enumerate()
.map(|(index, item)| within(item, &format!("[{index}]"), T::decode))
.collect(),
other => Err(expected("an array", other)),
}
}
impl<T: Data> Data for Vec<T> {
fn encode(&self) -> Json {
Json::Array(self.iter().map(Data::encode).collect())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
elements(json)
}
}
impl<T: Data + Ord> Data for BTreeSet<T> {
fn encode(&self) -> Json {
Json::Array(self.iter().map(Data::encode).collect())
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
elements(json)
}
}
impl<K: Data + Ord, V: Data> Data for BTreeMap<K, V> {
fn encode(&self) -> Json {
if K::TEXT {
Json::Object(
self.iter()
.map(|(key, value)| match key.encode() {
Json::String(key) => (key, value.encode()),
_ => unreachable!("a key of Text encodes as a string"),
})
.collect(),
)
} else {
Json::Array(
self.iter()
.map(|(key, value)| Json::Array(vec![key.encode(), value.encode()]))
.collect(),
)
}
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
let mut dict = BTreeMap::new();
match json {
Json::Object(members) if K::TEXT => {
for (key, value) in members {
let step = format!("[{}]", Json::String(key.clone()).canonical());
let key = K::decode(&Json::String(key.clone()))?;
dict.insert(key, within(value, &step, V::decode)?);
}
}
Json::Array(pairs) if !K::TEXT => {
for (index, pair) in pairs.iter().enumerate() {
let (key, value) = within(pair, &format!("[{index}]"), |pair| {
let parts = positional(pair, 2)?;
Ok((part(parts, 0)?, part(parts, 1)?))
})?;
if dict.insert(key, value).is_some() {
return Err(inside(
refused("repeats a key already given"),
&format!("[{index}]"),
));
}
}
}
other => {
return Err(expected(
if K::TEXT { "an object" } else { "an array" },
other,
));
}
}
Ok(dict)
}
}
impl<T: Data> Data for Option<T> {
fn encode(&self) -> Json {
match self {
None => Json::String("None".to_owned()),
Some(value) => variant("Some", value.encode()),
}
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
match constructor(json)? {
("None", None) => Ok(None),
("Some", Some(payload)) => within(payload, "Some", T::decode).map(Some),
(name, payload) => Err(mismatch("Option", name, payload)),
}
}
}
impl<T: Data, E: Data> Data for std::result::Result<T, E> {
fn encode(&self) -> Json {
match self {
Ok(value) => variant("Ok", value.encode()),
Err(value) => variant("Err", value.encode()),
}
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
match constructor(json)? {
("Ok", Some(payload)) => within(payload, "Ok", T::decode).map(Ok),
("Err", Some(payload)) => within(payload, "Err", E::decode).map(Err),
(name, payload) => Err(mismatch("Result", name, payload)),
}
}
}
macro_rules! tuple {
($count:literal: $($part:ident $index:tt),+) => {
impl<$($part: Data),+> Data for ($($part,)+) {
fn encode(&self) -> Json {
Json::Array(vec![$(self.$index.encode()),+])
}
fn decode(json: &Json) -> Result<Self, DecodeError> {
let parts = positional(json, $count)?;
Ok(($(part::<$part>(parts, $index)?,)+))
}
}
};
}
tuple!(2: A 0, B 1);
tuple!(3: A 0, B 1, C 2);
tuple!(4: A 0, B 1, C 2, D 3);
tuple!(5: A 0, B 1, C 2, D 3, E 4);
tuple!(6: A 0, B 1, C 2, D 3, E 4, F 5);
tuple!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6);
tuple!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);
#[derive(Default, Debug)]
pub struct Fields(Vec<(String, Json)>);
impl Fields {
pub fn new() -> Self {
Fields::default()
}
#[must_use]
pub fn field<T: Data>(mut self, name: &str, value: &T) -> Self {
self.0.push((name.to_owned(), value.encode()));
self
}
#[must_use]
pub fn optional<T: Data>(mut self, name: &str, value: Option<&T>) -> Self {
if let Some(value) = value {
self.0.push((name.to_owned(), value.encode()));
}
self
}
pub fn build(self) -> Json {
Json::Object(self.0)
}
}
#[derive(Debug)]
pub struct Object<'j>(&'j [(String, Json)]);
pub fn object(json: &Json) -> Result<Object<'_>, DecodeError> {
match json {
Json::Object(members) => Ok(Object(members)),
other => Err(expected("an object", other)),
}
}
impl Object<'_> {
fn get(&self, name: &str) -> Option<&Json> {
self.0
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value)
}
pub fn field<T: Data>(&self, name: &str) -> Result<T, DecodeError> {
match self.get(name) {
Some(value) => within(value, name, T::decode),
None => Err(inside(refused("is missing"), name)),
}
}
pub fn optional<T: Data>(&self, name: &str) -> Result<Option<T>, DecodeError> {
match self.get(name) {
None | Some(Json::Null) => Ok(None),
Some(value) => within(value, name, T::decode).map(Some),
}
}
}
pub fn constructor(json: &Json) -> Result<(&str, Option<&Json>), DecodeError> {
match json {
Json::String(name) => Ok((name, None)),
Json::Object(members) if members.len() == 1 => {
Ok((members[0].0.as_str(), Some(&members[0].1)))
}
other => Err(expected(
"a constructor's name or an object of one member",
other,
)),
}
}
pub fn variant(name: &str, payload: Json) -> Json {
Json::Object(vec![(name.to_owned(), payload)])
}
pub fn mismatch(enum_name: &str, name: &str, payload: Option<&Json>) -> DecodeError {
let with = if payload.is_some() {
"with a payload"
} else {
"without a payload"
};
refused(format!(
"names no constructor of `{enum_name}`: `{name}` {with}"
))
}
pub fn positional(json: &Json, count: usize) -> Result<&[Json], DecodeError> {
match json {
Json::Array(parts) if parts.len() == count => Ok(parts),
Json::Array(parts) => Err(refused(format!(
"has {} elements, not {count}",
parts.len()
))),
other => Err(expected("an array", other)),
}
}
pub fn part<T: Data>(parts: &[Json], index: usize) -> Result<T, DecodeError> {
within(&parts[index], &format!("[{index}]"), T::decode)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_path_is_written_as_the_runtime_writes_one() {
let error = inside(inside(refused("is wrong"), "[2]"), "steps");
assert_eq!(error.path, "steps[2]");
let error = inside(inside(refused("is wrong"), "owner"), "[0]");
assert_eq!(error.path, "[0].owner");
assert_eq!(error.problem, "is wrong");
}
}
#[derive(Clone, Debug)]
pub struct ContextCodec {
graph: std::sync::Arc<flow_abi::ValidatedTypes>,
ty: Type,
mode: Mode,
}
impl ContextCodec {
pub(crate) fn is_text(&self) -> bool {
matches!(self.ty, Type::Text)
}
pub(crate) fn new(
graph: std::sync::Arc<flow_abi::ValidatedTypes>,
ty: Type,
mode: Mode,
) -> Result<Self, DecodeError> {
flow_abi::crossable(graph.catalog(), &ty)?;
flow_abi::decodable(graph.catalog(), &ty, mode)?;
Ok(Self { graph, ty, mode })
}
pub fn decode(&self, json: &Json) -> Result<Json, DecodeError> {
let value = flow_abi::decode(self.graph.catalog(), &self.ty, json, self.mode, &LIMITS)?;
self.encode_value(&value)
}
fn encode_value(&self, value: &flow_value::Value) -> Result<Json, DecodeError> {
flow_abi::encode(self.graph.catalog(), &self.ty, value)
.map_err(|error| refused(error.to_string()))
}
pub fn encode(&self, json: &Json) -> Result<Json, DecodeError> {
self.decode(json)
}
pub fn compare(&self, left: &Json, right: &Json) -> Result<std::cmp::Ordering, DecodeError> {
let decode =
|json| flow_abi::decode(self.graph.catalog(), &self.ty, json, self.mode, &LIMITS);
flow_value::compare(&decode(left)?, &decode(right)?)
.map_err(|error| refused(error.to_string()))
}
fn child(&self, ty: Type) -> Result<Self, DecodeError> {
Self::new(self.graph.clone(), ty, self.mode)
}
pub fn element(&self) -> Result<Self, DecodeError> {
match &self.ty {
Type::List(ty) | Type::Set(ty) | Type::Option(ty) => self.child((**ty).clone()),
_ => Err(refused("type has no element codec")),
}
}
pub fn key(&self) -> Result<Self, DecodeError> {
match &self.ty {
Type::Dict(key, _) => self.child((**key).clone()),
_ => Err(refused("type is not a dictionary")),
}
}
pub fn value(&self) -> Result<Self, DecodeError> {
match &self.ty {
Type::Dict(_, value) => self.child((**value).clone()),
_ => Err(refused("type is not a dictionary")),
}
}
pub fn positional(&self, index: usize) -> Result<Self, DecodeError> {
match &self.ty {
Type::Tuple(parts) => parts
.get(index)
.cloned()
.ok_or_else(|| refused("tuple index is out of range"))
.and_then(|ty| self.child(ty)),
_ => Err(refused("type is not a tuple")),
}
}
pub fn field(&self, name: &str) -> Result<Self, DecodeError> {
if let Type::Named(id, args) = &self.ty
&& let flow_abi::Body::Record(shape, fields) = &self.graph.catalog().decl(*id).body
&& let Some(index) = shape.fields().position(|field| field == name)
{
return self.child(fields[index].subst(args));
}
Err(refused(format!("type has no field {name}")))
}
pub fn decode_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
self.field(name)?.read_field(parent, name)
}
pub fn encode_field(&self, value: &Json, name: &str) -> Result<Option<Json>, DecodeError> {
self.field(name)?.write_field(value)
}
fn read_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
let value = parent.get(name);
if let Type::Option(_) = self.ty {
return match value {
None | Some(Json::Null) => Ok(Json::String("None".into())),
Some(value) => self.decode(&variant("Some", value.clone())),
};
}
self.decode(value.ok_or_else(|| inside(refused("is missing"), name))?)
}
fn write_field(&self, value: &Json) -> Result<Option<Json>, DecodeError> {
let normalized = self.encode(value)?;
if let Type::Option(_) = self.ty {
return match constructor(&normalized)? {
("None", None) => Ok(None),
("Some", Some(value)) => Ok(Some(value.clone())),
_ => Err(refused("invalid normalized Option")),
};
}
Ok(Some(normalized))
}
pub fn variant(&self, name: &str) -> Result<PayloadView, DecodeError> {
if let Type::Named(id, args) = &self.ty
&& let flow_abi::Body::Enum(shape, parts) = &self.graph.catalog().decl(*id).body
{
for (index, fields) in parts.iter().enumerate() {
let ctor = shape.constructor(index).expect("validated enum shape");
if ctor.name() == name {
return Ok(PayloadView {
parent: self.clone(),
kind: ctor.payload().clone(),
parts: fields.iter().map(|ty| ty.subst(args)).collect(),
});
}
}
}
Err(refused(format!("type has no constructor {name}")))
}
}
#[derive(Clone, Debug)]
pub struct PayloadView {
parent: ContextCodec,
kind: Payload,
parts: Vec<Type>,
}
impl PayloadView {
pub fn positional(&self, index: usize) -> Result<ContextCodec, DecodeError> {
if !matches!(self.kind, Payload::Positional(_)) {
return Err(refused("payload is not positional"));
}
self.parts
.get(index)
.cloned()
.ok_or_else(|| refused("payload index is out of range"))
.and_then(|ty| self.parent.child(ty))
}
pub fn field(&self, name: &str) -> Result<ContextCodec, DecodeError> {
if let Payload::Named(names) = &self.kind
&& let Some(index) = names.iter().position(|field| field.as_ref() == name)
{
return self.parent.child(self.parts[index].clone());
}
Err(refused(format!("payload has no field {name}")))
}
pub fn decode_field(&self, parent: &Json, name: &str) -> Result<Json, DecodeError> {
self.field(name)?.read_field(parent, name)
}
pub fn encode_field(&self, value: &Json, name: &str) -> Result<Option<Json>, DecodeError> {
self.field(name)?.write_field(value)
}
}
#[derive(Clone, Debug)]
pub struct ContextSet {
codec: ContextCodec,
values: Vec<Json>,
}
impl ContextSet {
pub fn new(codec: ContextCodec, values: Vec<Json>) -> Result<Self, DecodeError> {
let decoded = values
.into_iter()
.map(|json| {
flow_abi::decode(codec.graph.catalog(), &codec.ty, &json, codec.mode, &LIMITS)
})
.collect::<Result<Vec<_>, _>>()?;
let ordered =
flow_value::Set::from_items(decoded).map_err(|error| refused(error.to_string()))?;
let values = ordered
.iter()
.map(|value| codec.encode_value(value))
.collect::<Result<_, _>>()?;
Ok(Self { codec, values })
}
pub fn codec(&self) -> &ContextCodec {
&self.codec
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = &Json> {
self.values.iter()
}
pub fn canonical_json(&self) -> Json {
Json::Array(self.values.clone())
}
}
#[derive(Clone, Debug)]
pub struct ContextDict {
key: ContextCodec,
value: ContextCodec,
values: Vec<(Json, Json)>,
text: bool,
}
impl ContextDict {
pub fn new(
key: ContextCodec,
value: ContextCodec,
entries: Vec<(Json, Json)>,
) -> Result<Self, DecodeError> {
let text = key.ty == Type::Text;
let count = entries.len();
let decoded = entries
.into_iter()
.map(|(k, v)| {
Ok((
flow_abi::decode(key.graph.catalog(), &key.ty, &k, key.mode, &LIMITS)?,
flow_abi::decode(value.graph.catalog(), &value.ty, &v, value.mode, &LIMITS)?,
))
})
.collect::<Result<Vec<_>, DecodeError>>()?;
let ordered =
flow_value::Dict::from_entries(decoded).map_err(|error| refused(error.to_string()))?;
if ordered.len() != count {
return Err(refused("dictionary has a duplicate key"));
}
let values = ordered
.iter()
.map(|(k, v)| Ok((key.encode_value(k)?, value.encode_value(v)?)))
.collect::<Result<_, DecodeError>>()?;
Ok(Self {
key,
value,
values,
text,
})
}
pub fn key_codec(&self) -> &ContextCodec {
&self.key
}
pub fn value_codec(&self) -> &ContextCodec {
&self.value
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = &(Json, Json)> {
self.values.iter()
}
pub fn canonical_json(&self) -> Json {
if self.text {
Json::Object(
self.values
.iter()
.map(|(key, value)| match key {
Json::String(key) => (key.clone(), value.clone()),
_ => unreachable!("validated Text key"),
})
.collect(),
)
} else {
Json::Array(
self.values
.iter()
.map(|(key, value)| Json::Array(vec![key.clone(), value.clone()]))
.collect(),
)
}
}
}
pub fn read_context_set(codec: &ContextCodec, json: &Json) -> Result<ContextSet, DecodeError> {
if !matches!(codec.ty, Type::Set(_)) {
return Err(refused("type is not a set"));
}
let Json::Array(values) = codec.decode(json)? else {
return Err(refused("set must be an array"));
};
Ok(ContextSet {
codec: codec.element()?,
values,
})
}
pub fn read_context_dict(codec: &ContextCodec, json: &Json) -> Result<ContextDict, DecodeError> {
let values = match codec.decode(json)? {
Json::Object(fields) => fields
.into_iter()
.map(|(key, value)| (Json::String(key), value))
.collect(),
Json::Array(pairs) => pairs
.into_iter()
.map(|pair| match pair {
Json::Array(mut pair) if pair.len() == 2 => {
let value = pair.pop().expect("pair value");
let key = pair.pop().expect("pair key");
Ok((key, value))
}
_ => Err(refused("dictionary entry must be a pair")),
})
.collect::<Result<_, _>>()?,
_ => return Err(refused("dictionary must be an object or pairs")),
};
let key = codec.key()?;
let text = key.ty == Type::Text;
Ok(ContextDict {
key,
value: codec.value()?,
values,
text,
})
}
pub fn read_context_list<T>(
codec: &ContextCodec,
json: &Json,
read: impl Fn(&ContextCodec, &Json) -> Result<T, DecodeError>,
) -> Result<Vec<T>, DecodeError> {
let Json::Array(values) = codec.decode(json)? else {
return Err(refused("list must be an array"));
};
let child = codec.element()?;
values
.iter()
.enumerate()
.map(|(at, value)| read(&child, value).map_err(|error| inside(error, &format!("[{at}]"))))
.collect()
}
pub fn write_context_list<T>(
codec: &ContextCodec,
values: &[T],
write: impl Fn(&ContextCodec, &T) -> Result<Json, DecodeError>,
) -> Result<Json, DecodeError> {
let child = codec.element()?;
codec.encode(&Json::Array(
values
.iter()
.map(|value| write(&child, value))
.collect::<Result<_, _>>()?,
))
}
pub fn read_context_option<T>(
codec: &ContextCodec,
json: &Json,
read: impl Fn(&ContextCodec, &Json) -> Result<T, DecodeError>,
) -> Result<Option<T>, DecodeError> {
let normalized = codec.decode(json)?;
match constructor(&normalized)? {
("None", None) => Ok(None),
("Some", Some(value)) => read(&codec.element()?, value).map(Some),
_ => Err(refused("invalid Option")),
}
}
pub fn write_context_option<T>(
codec: &ContextCodec,
value: &Option<T>,
write: impl Fn(&ContextCodec, &T) -> Result<Json, DecodeError>,
) -> Result<Json, DecodeError> {
let json = match value {
None => Json::String("None".into()),
Some(value) => variant("Some", write(&codec.element()?, value)?),
};
codec.encode(&json)
}