chore: move to crates folder

This commit is contained in:
Alexander Medvedev committed 2026-08-06 12:56:40 +02:00
1 parent 5d10c0d8a8
commit cb3660bcd2
3393 files changed
+1270 -741

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
[package]
name = "pumpkin-codecs"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
serde_json.workspace = true
tracing.workspace = true
[lints]
workspace = true
+120
View File
@@ -0,0 +1,120 @@
use crate::{DataResult, Decode, DynamicOps, Encode};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Either<L, R> {
Left(L),
Right(R),
}
impl<L, R> Either<L, R> {
pub const fn is_left(&self) -> bool {
matches!(self, Self::Left(_))
}
pub const fn is_right(&self) -> bool {
matches!(self, Self::Right(_))
}
pub fn left(self) -> Option<L> {
match self {
Self::Left(l) => Some(l),
Self::Right(_) => None,
}
}
pub fn right(self) -> Option<R> {
match self {
Self::Left(_) => None,
Self::Right(r) => Some(r),
}
}
}
impl<L: Encode, R: Encode> Encode for Either<L, R> {
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value> {
match self {
Self::Left(l) => l.encode(ops, prefix),
Self::Right(r) => r.encode(ops, prefix),
}
}
}
impl<L: Decode, R: Decode> Decode for Either<L, R> {
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)> {
let left = L::decode(input.clone(), ops).map(|(l, t)| (Self::Left(l), t));
// If the left result is a success, return that.
if left.is_success() {
return left;
}
let right = R::decode(input, ops).map(|(r, t)| (Self::Right(r), t));
// If the right result is a success, return that.
if right.is_success() {
return right;
}
// Since no result is a complete success by this point, we look for partial results.
if left.has_result_or_partial() {
return left;
}
if right.has_result_or_partial() {
return right;
}
DataResult::new_error(format!(
"Failed to parse either. First: {}; Second: {}",
left.get_message().unwrap(),
right.get_message().unwrap()
))
}
}
#[cfg(test)]
mod test {
use super::Either;
use crate::json_ops::JsonOps;
use crate::{assert_decode, assert_encode_success};
use serde_json::json;
#[test]
fn simple() {
assert_encode_success!(Either::<i32, String>::Left(5), JsonOps, json!(5));
assert_encode_success!(
Either::<i32, String>::Right("I am some text.".to_string()),
JsonOps,
json!("I am some text.")
);
// Decoding
assert_decode!(
Either<i32, String>,
json!(-238),
JsonOps,
is_success
);
assert_decode!(
Either<u32, String>,
json!(-238),
JsonOps,
is_error
);
assert_decode!(
Either<u32, String>,
json!("hello"),
JsonOps,
is_success
);
assert_decode!(
Either<u32, String>,
json!(true),
JsonOps,
is_error
);
}
}
+277
View File
@@ -0,0 +1,277 @@
use crate::list_builder::ListBuilder;
use crate::{DataResult, Decode, DynamicOps, Encode, FlatTryFrom, Lifecycle};
/// A wrapped [`Vec`] that can only contain a size of elements between `MIN` and `MAX` (inclusive).
pub struct BoundedVec<T, const MIN: usize, const MAX: usize>(Vec<T>);
impl<T, const MIN: usize, const MAX: usize> From<BoundedVec<T, MIN, MAX>> for Vec<T> {
fn from(value: BoundedVec<T, MIN, MAX>) -> Self {
value.0
}
}
impl<T, const MIN: usize, const MAX: usize> FlatTryFrom<Vec<T>> for BoundedVec<T, MIN, MAX> {
fn flat_try_from(value: Vec<T>) -> DataResult<Self> {
let size = value.len();
if size < MIN {
create_too_short_error(MIN, MAX, size)
} else if size > MAX {
create_too_long_error(MIN, MAX, size)
} else {
DataResult::new_success(Self(value))
}
}
}
fn create_too_short_error<T>(min: usize, max: usize, size: usize) -> DataResult<T> {
DataResult::new_error(format!(
"List is too short: {size}, expected range [{min}-{max}]"
))
}
fn create_too_long_error<T>(min: usize, max: usize, size: usize) -> DataResult<T> {
DataResult::new_error(format!(
"List is too long: {size}, expected range [{min}-{max}]"
))
}
impl<T, const MIN: usize, const MAX: usize> Encode for BoundedVec<T, MIN, MAX>
where
T: Encode,
{
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value> {
let size = self.0.len();
if size < MIN {
create_too_short_error(MIN, MAX, size)
} else if size > MAX {
create_too_long_error(MIN, MAX, size)
} else {
let mut builder = ops.list_builder();
for e in &self.0 {
builder = builder.add_data_result(e.encode_start(ops));
}
builder.build(prefix)
}
}
}
impl<T, const MIN: usize, const MAX: usize> Decode for BoundedVec<T, MIN, MAX>
where
T: Decode,
{
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)> {
let iter = ops.get_iter(input).with_lifecycle(Lifecycle::Stable);
iter.flat_map(|i| {
let mut total_count = 0;
let mut elements: Vec<T> = vec![];
let mut failed: Vec<O::Value> = vec![];
// This is used to keep track of the overall `DataResult`.
// If any one element has a partial result, this turns into a partial result.
// If any one element has no result, this turns into a non-result.
let mut result = DataResult::new_success(());
for element in i {
total_count += 1;
if elements.len() >= MAX {
failed.push(element.clone());
continue;
}
let element_result = T::decode(element.clone(), ops);
result = result.add_message(&element_result);
if let Some(element) = element_result.into_result_or_partial() {
elements.push(element.0);
}
}
if total_count < MIN {
return create_too_short_error(MIN, MAX, total_count);
}
let pair = (Self(elements), ops.create_list(failed));
if total_count > MAX {
result = create_too_long_error(MIN, MAX, total_count);
}
result.with_complete_or_partial(pair)
})
}
}
impl<T> Encode for Vec<T>
where
T: Encode,
{
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value> {
let mut builder = ops.list_builder();
for e in self {
builder = builder.add_data_result(e.encode_start(ops));
}
builder.build(prefix)
}
}
impl<T> Decode for Vec<T>
where
T: Decode,
{
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)> {
let iter = ops.get_iter(input).with_lifecycle(Lifecycle::Stable);
iter.flat_map(|i| {
let mut elements: Self = vec![];
let mut result = DataResult::new_success(());
for element in i {
let element_result = T::decode(element.clone(), ops);
result = result.add_message(&element_result);
if let Some(element) = element_result.into_result_or_partial() {
elements.push(element.0);
}
}
let pair = (elements, ops.create_list(Vec::new()));
result.with_complete_or_partial(pair)
})
}
}
/// A wrapper around a `Vec` that cannot have it be empty, similar to Minecraft's `ExtraCodecs.nonEmptyList`.
pub struct NonEmptyVec<T>(Vec<T>);
impl<T> From<NonEmptyVec<T>> for Vec<T> {
/// Returns the wrapped `Vec` of this `NonEmptyVec`.
fn from(value: NonEmptyVec<T>) -> Self {
value.0
}
}
impl<T> Encode for NonEmptyVec<T>
where
T: Encode,
{
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value> {
if self.0.is_empty() {
DataResult::new_error("List must have contents")
} else {
self.0.encode(ops, prefix)
}
}
}
impl<T> Decode for NonEmptyVec<T>
where
T: Decode,
{
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)> {
Vec::<T>::decode(input, ops).flat_map(|(v, c)| Self::flat_try_from(v).map(|v| (v, c)))
}
}
impl<T> FlatTryFrom<Vec<T>> for NonEmptyVec<T> {
fn flat_try_from(value: Vec<T>) -> DataResult<Self> {
if value.is_empty() {
DataResult::new_error("List must have contents")
} else {
DataResult::new_success(Self(value))
}
}
}
// Utility functions
/// Tries to check a list to have a fixed size `size`, returning the appropriate
/// [`DataResult`].
///
/// # Arguments
/// - `list`: The list to validate.
/// - `size`: The required size.
///
/// # Returns
/// A successful result if `list.len() == size`; otherwise, it returns a partial/non-result.
/// If this result is partial, it will also be `size` elements long.
pub fn validate_fixed_size<T>(list: Vec<T>, size: usize) -> DataResult<Vec<T>> {
if list.len() == size {
DataResult::new_success(list)
} else {
let message = format!("Input is not a list of {size} elements");
if list.len() > size {
DataResult::new_partial_error(message, list.into_iter().take(size).collect())
} else {
DataResult::new_error(message)
}
}
}
//
#[cfg(test)]
mod test {
use crate::assert_decode;
use crate::assert_encode_success;
use crate::json_ops::JsonOps;
use serde_json::json;
#[test]
fn encoding() {
assert_encode_success!(vec![1, 2], JsonOps, json!([1, 2]));
let vec: Vec<i32> = vec![];
assert_encode_success!(vec, JsonOps, json!([]));
assert_encode_success!(vec![-3, 192, 182], JsonOps, json!([-3, 192, 182]));
assert_encode_success!(
vec!["a".to_string(), "b".to_string()],
JsonOps,
json!(["a", "b"])
);
assert_encode_success!(vec!["one".to_string()], JsonOps, json!(["one"]));
assert_encode_success!(
vec!["1".to_string(), "2".to_string(), "3".to_string()],
JsonOps,
json!(["1", "2", "3"])
);
assert_encode_success!(vec![1, 2], JsonOps, json!([1, 2]));
assert_encode_success!(vec![true, false], JsonOps, json!([true, false]));
assert_encode_success!(
vec![vec![true, false], vec![true, false]],
JsonOps,
json!([[true, false], [true, false]])
);
assert_encode_success!(
vec![vec![vec![true, true], vec![false, false]]],
JsonOps,
json!([[[true, true], [false, false]]])
);
}
#[test]
fn decoding() {
type NumberGrid = Vec<Vec<f64>>;
assert_decode!(Vec<i16>, json!([1, 2, 3]), JsonOps, is_success);
assert_decode!(Vec<i16>, json!([1, 2, 6, 24, 120]), JsonOps, is_success);
assert_decode!(Vec<i16>, json!(["string", "b"]), JsonOps, is_error);
assert_decode!(Vec<i16>, json!(false), JsonOps, is_error);
assert_decode!(NumberGrid, json!([[0, 0.5, 1.0]]), JsonOps, is_success);
assert_decode!(
NumberGrid,
json!([[0, 0.5, 1.0], [1, 4, 5], [-293.4, 1, 293]]),
JsonOps,
is_success
);
assert_decode!(
NumberGrid,
json!([[0, 0.5, 1.0], [1, false, 5], [-293.4, 1, 293]]),
JsonOps,
is_error
);
assert_decode!(
NumberGrid,
json!([[1, 1.5, 2.0], [-20]]),
JsonOps,
is_success
);
assert_decode!(NumberGrid, json!([[]]), JsonOps, is_success);
assert_decode!(NumberGrid, json!([[[[]]]]), JsonOps, is_error);
}
}
+250
View File
@@ -0,0 +1,250 @@
use crate::map_like::MapLike;
use crate::struct_builder::StructBuilder;
use crate::{DataResult, Decode, DynamicOps, Encode, Lifecycle};
use std::collections::HashMap;
use std::fmt::Display;
use std::hash::{BuildHasher, Hash};
fn encode_base_hash_map<
O: DynamicOps,
K: Encode + Eq + Hash + Display,
V: Encode,
S: BuildHasher + Default,
>(
map: &HashMap<K, V, S>,
ops: &'static O,
mut prefix: impl StructBuilder<Value = O::Value>,
) -> impl StructBuilder<Value = O::Value> {
for (key, element) in map {
prefix =
prefix.add_key_result_value_result(key.encode_start(ops), element.encode_start(ops));
}
prefix
}
fn decode_base_hash_map<
O: DynamicOps,
K: Decode + Eq + Hash + Display,
V: Decode,
S: BuildHasher + Default,
>(
input: &impl MapLike<Value = O::Value>,
ops: &'static O,
) -> DataResult<HashMap<K, V, S>> {
let mut read_map: HashMap<K, V, S> = HashMap::with_hasher(S::default());
let mut failed: Vec<(O::Value, O::Value)> = vec![];
let result = input.iter().fold(
DataResult::new_success_with_lifecycle((), Lifecycle::Stable),
|r, (k, e)| {
// First, we try to parse the key and value.
let key_result = K::parse(k.clone(), ops);
let element_result = V::parse(e.clone(), ops);
let entry_result =
key_result.apply_2_and_make_stable(|kr, er| (kr, er), element_result);
let accumulated = r.add_message(&entry_result);
let entry = entry_result.into_result_or_partial();
if let Some((key, element)) = entry {
// If this parses successfully, we try adding it to our map.
if read_map.contains_key(&key) {
// There was already a value for this key.
failed.push((k, e.clone()));
return accumulated.add_message::<()>(&DataResult::new_error(format!(
"Duplicate entry for key: {key}"
)));
}
read_map.insert(key, element);
} else {
// Could not parse.
failed.push((k, e.clone()));
}
accumulated
},
);
let errors = ops.create_map(failed);
result
.with_complete_or_partial(read_map)
.map_error(|e| format!("{e} (Missed inputs: {errors})"))
}
impl<K, V, S: BuildHasher + Default> Encode for HashMap<K, V, S>
where
K: Encode + Eq + Hash + Display,
V: Encode,
{
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value> {
encode_base_hash_map::<O, K, V, S>(self, ops, ops.map_builder()).build(prefix)
}
}
impl<K, V, S: BuildHasher + Default> Decode for HashMap<K, V, S>
where
K: Decode + Eq + Hash + Display,
V: Decode,
{
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)> {
ops.get_map(&input)
.with_lifecycle(Lifecycle::Stable)
.flat_map(|map| decode_base_hash_map(&map, ops))
.map(|r| (r, input))
}
}
#[cfg(test)]
mod test {
use crate::codec::*;
use crate::json_ops::JsonOps;
use crate::{
FlatTryFrom, assert_decode, assert_encode_success, comap_flat_map_codec_impl,
flat_xmap_codec_impl,
};
use serde_json::json;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
#[test]
fn simple_encoding() {
let mut map = HashMap::<String, i32>::new();
map.insert("Amy".to_string(), 10);
map.insert("Leo".to_string(), 24);
map.insert("Patrick".to_string(), -65);
assert_encode_success!(map, JsonOps, json!({"Amy": 10, "Leo": 24, "Patrick": -65}));
}
#[test]
fn string_integer_map() {
// A basic implementation to check if a number is prime.
fn is_prime(number: u32) -> bool {
if number < 2 {
return false;
}
for i in 2..number {
if number.is_multiple_of(i) {
return false;
}
}
true
}
/// A `u32` wrapper that encodes a `String`.
#[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Eq, Hash)]
struct StringInteger(u32);
impl Display for StringInteger {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<&StringInteger> for String {
fn from(value: &StringInteger) -> Self {
// This will always succeed.
value.0.to_string()
}
}
impl FlatTryFrom<String> for StringInteger {
fn flat_try_from(value: String) -> DataResult<Self> {
// Try to parse an integer.
value.parse().map_or_else(
|_| DataResult::new_error("Could not parse String"),
|i| DataResult::new_success(Self(i)),
)
}
}
comap_flat_map_codec_impl!(String => StringInteger, StringInteger::flat_try_from, String::from);
let mut map = HashMap::<StringInteger, bool>::new();
// Calculate the map for the first 20 numbers.
for i in 1..=20 {
map.insert(StringInteger(i), is_prime(i));
}
assert_encode_success!(
map,
JsonOps,
json!({
"1": false, "2": true, "3": true, "4": false, "5": true, "6": false, "7": true, "8": false, "9": false, "10": false,
"11": true, "12": false, "13": true, "14": false, "15": false, "16": false, "17": true, "18": false, "19": true, "20": false
})
);
assert_decode!(
HashMap<StringInteger, bool>,
json!({
"1": true, "2": true, "3": true, "4": false, "5": false
}),
JsonOps,
is_success
);
}
#[test]
fn letter_frequency() {
/// A wrapper of a `String` that only allows a single letter.
#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Hash)]
struct Letter(String);
impl Display for Letter {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FlatTryFrom<String> for Letter {
fn flat_try_from(value: String) -> DataResult<Self> {
// Try to parse a single letter.
if value.len() == 1 {
DataResult::new_success(Self(value))
} else {
DataResult::new_error(format!("Not a letter: {value}"))
}
}
}
impl FlatTryFrom<&Letter> for String {
fn flat_try_from(value: &Letter) -> DataResult<Self> {
Letter::flat_try_from(value.0.clone()).map(|l| l.0)
}
}
flat_xmap_codec_impl!(String => Letter, Letter::flat_try_from, String::flat_try_from);
type LetterData = HashMap<Letter, u64>;
let mut map = LetterData::new();
map.insert(Letter("b".to_string()), 62);
map.insert(Letter("z".to_string()), 2342);
assert_encode_success!(map, JsonOps, json!({"b": 62, "z": 2342}));
let mut map = LetterData::new();
map.insert(Letter("d".to_string()), 12452);
map.insert(Letter("candy".to_string()), 2342);
assert!(map.encode_start(&JsonOps).is_error());
assert_decode!(
LetterData,
json!({"a": 13, "c": 34, "x": 1, "e": 21}),
JsonOps,
is_success
);
assert_decode!(
LetterData,
json!({"b": 45, "w": 10, "l": 90, "word": 5}),
JsonOps,
is_error
);
}
}
+260
View File
@@ -0,0 +1,260 @@
pub mod either;
pub mod list;
pub mod map;
pub mod optional_field;
pub(crate) mod primitive;
use crate::codec::optional_field::OptionalFieldDecode;
use crate::map_like::MapLike;
use crate::struct_builder::StructBuilder;
use crate::{DataResult, DynamicOps};
/// A trait for something that can be encoded by a [`DynamicOps`] to its format.
pub trait Encode {
/// Encodes this value to a value represented by the provided [`DynamicOps`]
/// with the provided prefix.
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value>;
/// Encodes this value to a value represented by the provided [`DynamicOps`] without a prefix.
fn encode_start<O: DynamicOps>(&self, ops: &'static O) -> DataResult<O::Value> {
self.encode(ops, ops.empty())
}
}
/// A trait for something which can be added to a [`MapLike`] as a field with a provided name.
pub trait FieldEncode {
/// Encodes this value to a map by adding a field, whose:
/// - key is the field's `name`.
/// - value is the encoded value represented by the provided [`DynamicOps`].
fn encode_field<O: DynamicOps, B: StructBuilder<Value = O::Value>>(
&self,
name: &'static str,
ops: &'static O,
prefix: B,
) -> B;
/// Encodes this value to a map by adding a defaulted field, whose:
/// - key is the field's `name`.
/// - value is the encoded value represented by the provided [`DynamicOps`].
///
/// The field may not be encoded if `default` == `*self`.
fn encode_defaulted_field<O: DynamicOps, B: StructBuilder<Value = O::Value>>(
&self,
name: &'static str,
ops: &'static O,
prefix: B,
default: Self,
) -> B
where
Self: PartialEq;
}
impl<T: Encode> FieldEncode for T {
fn encode_field<O: DynamicOps, B: StructBuilder<Value = O::Value>>(
&self,
name: &'static str,
ops: &'static O,
prefix: B,
) -> B {
prefix.add_string_key_value_result(name, self.encode_start(ops))
}
fn encode_defaulted_field<O: DynamicOps, B: StructBuilder<Value = O::Value>>(
&self,
name: &'static str,
ops: &'static O,
prefix: B,
default: Self,
) -> B
where
Self: PartialEq,
{
if default == *self {
prefix.add_string_key_value_result(name, self.encode_start(ops))
} else {
prefix
}
}
}
/// A trait for something that can be decoded from the value represented by a [`DynamicOps`].
pub trait Decode: Sized {
/// Decodes a value of this type from a value represented by the provided [`DynamicOps`],
/// along with the remaining data.
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)>;
/// Decodes a value of this type from a value represented by the provided [`DynamicOps`],
/// without providing any other data.
fn parse<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<Self> {
Self::decode(input, ops).map(|(r, _)| r)
}
}
/// A trait for something which can be decoded from a [`MapLike`] from a field with a provided name.
pub trait FieldDecode: Sized {
/// Decodes a value of this type from a map by decoding one of its fields, whose:
/// - key is the field's `name`.
/// - value is the value represented by a [`DynamicsOps`] that is meant to be decoded.
fn decode_field<O: DynamicOps>(
name: &'static str,
input: &impl MapLike<Value = O::Value>,
ops: &'static impl DynamicOps<Value = O::Value>,
) -> DataResult<Self>;
/// Decodes a value of this type from a map by decoding one of its defaulted fields, whose:
/// - key is the field's `name`.
/// - value is the value represented by a [`DynamicsOps`] that is meant to be decoded.
///
/// If a value could not be decoded, the `default` value is returned.
/// This method has an extra `lenient` parameter. If it is `true`, errors
/// while trying to decode an explicit value, and the default value will be decoded instead.
fn decode_defaulted_field<O: DynamicOps>(
name: &'static str,
input: &impl MapLike<Value = O::Value>,
ops: &'static impl DynamicOps<Value = O::Value>,
default: Self,
lenient: bool,
) -> DataResult<Self>;
}
impl<T: Decode> FieldDecode for T {
fn decode_field<O: DynamicOps>(
name: &'static str,
input: &impl MapLike<Value = O::Value>,
ops: &'static impl DynamicOps<Value = O::Value>,
) -> DataResult<Self> {
input.get_str(name).map_or_else(
|| DataResult::new_error(format!("No key {name} in map")),
|v| Self::parse(v.clone(), ops),
)
}
fn decode_defaulted_field<O: DynamicOps>(
name: &'static str,
input: &impl MapLike<Value = O::Value>,
ops: &'static impl DynamicOps<Value = O::Value>,
default: Self,
lenient: bool,
) -> DataResult<Self> {
let decoded_option = Option::decode_optional_field::<O>(name, input, ops, lenient);
decoded_option.map(|o| o.unwrap_or(default))
}
}
/// Provides a fallible/infallible encode conversion from a first type to a second type via `backward`.
///
/// You probably do not need to use this directly.
#[macro_export]
macro_rules! encode_impl {
(infallible $second_type:ty, $backward:path) => {
impl $crate::Encode for $second_type {
fn encode<O: $crate::DynamicOps>(
&self,
ops: &'static O,
prefix: O::Value,
) -> $crate::DataResult<O::Value> {
$backward(self).encode(ops, prefix)
}
}
};
(fallible $second_type:ty, $backward:path) => {
impl $crate::Encode for $second_type {
fn encode<O: $crate::DynamicOps>(
&self,
ops: &'static O,
prefix: O::Value,
) -> $crate::DataResult<O::Value> {
$backward(self).flat_map(|m| m.encode(ops, prefix))
}
}
};
}
/// Provides a fallible/infallible decode conversion from a first type to a second type via `forward`.
///
/// You probably do not need to use this directly.
#[macro_export]
macro_rules! decode_impl {
(infallible $first_type:ty, $second_type:ty, $forward:path) => {
impl $crate::Decode for $second_type {
fn decode<O: $crate::DynamicOps>(
input: O::Value,
ops: &'static O,
) -> $crate::DataResult<(Self, O::Value)> {
<$first_type>::decode(input, ops).map(|(s, p)| ($forward(s), p))
}
}
};
(fallible $first_type:ty, $second_type:ty, $forward:path) => {
impl $crate::Decode for $second_type {
fn decode<O: $crate::DynamicOps>(
input: O::Value,
ops: &'static O,
) -> $crate::DataResult<(Self, O::Value)> {
<$first_type>::decode(input, ops).flat_map(|(s, p)| $forward(s).map(|m| (m, p)))
}
}
};
}
/// Provides easy `xmap`-like `Encode` and `Decode` implementations of a *second type*
/// by using the already-existing implementations of a *first type*.
///
/// The macro is written as `xmap_codec_impl!(first => second, forward, backward)`,
/// where:
/// - `forward` is the infallible conversion `fn(first) -> second` (for decoding).
/// - `backward` is the infallible conversion `fn(&second) -> first` (for encoding).
#[macro_export]
macro_rules! xmap_codec_impl {
($first_type:ty => $second_type:ty, $forward:path, $backward:path) => {
$crate::encode_impl!(infallible $second_type, $backward);
$crate::decode_impl!(infallible $first_type, $second_type, $forward);
};
}
/// Provides easy `comapFlatMap`-like `Encode` and `Decode` implementations of a *second type*
/// by using the already-existing implementations of a *first type*.
///
/// The macro is written as `comap_flat_map_codec_impl!(first => second, forward, backward)`,
/// where:
/// - `forward` is the fallible conversion `fn(first) -> DataResult<second>` (for decoding).
/// - `backward` is the infallible conversion `fn(&second) -> first` (for encoding).
#[macro_export]
macro_rules! comap_flat_map_codec_impl {
($first_type:ty => $second_type:ty, $forward:path, $backward:path) => {
$crate::encode_impl!(infallible $second_type, $backward);
$crate::decode_impl!(fallible $first_type, $second_type, $forward);
};
}
/// Provides easy `flatComapMap`-like `Encode` and `Decode` implementations of a *second type*
/// by using the already-existing implementations of a *first type*.
///
/// The macro is written as `flat_comap_map_codec_impl!(first => second, forward, backward)`,
/// where:
/// - `forward` is the infallible conversion `fn(first) -> second` (for decoding).
/// - `backward` is the fallible conversion `fn(&second) -> DataResult<first>` (for encoding).
#[macro_export]
macro_rules! flat_comap_map_codec_impl {
($first_type:ty => $second_type:ty, $forward:path, $backward:path) => {
$crate::encode_impl!(fallible $second_type, $backward);
$crate::decode_impl!(infallible $first_type, $second_type, $forward);
};
}
/// Provides easy `flatXmap`-like `Encode` and `Decode` implementations of a *second type*
/// by using the already-existing implementations of a *first type*.
///
/// The macro is written as `flat_xmap_codec_impl!(first => second, forward, backward)`,
/// where:
/// - `forward` is the fallible conversion `fn(first) -> DataResult<second>` (for decoding).
/// - `backward` is the fallible conversion `fn(&second) -> DataResult<first>` (for encoding).
#[macro_export]
macro_rules! flat_xmap_codec_impl {
($first_type:ty => $second_type:ty, $forward:path, $backward:path) => {
$crate::encode_impl!(fallible $second_type, $backward);
$crate::decode_impl!(fallible $first_type, $second_type, $forward);
};
}
@@ -0,0 +1,77 @@
use crate::codec::FieldEncode;
use crate::map_like::MapLike;
use crate::struct_builder::StructBuilder;
use crate::{DataResult, Decode, DynamicOps, Encode};
/// A trait for something which can be added to a [`MapLike`] as an optional field with a provided name.
pub trait OptionalFieldEncode {
/// Encodes this value to a map by adding an optional field, whose:
/// - key is the field's `name`.
/// - value is the encoded value represented by the provided [`DynamicOps`].
fn encode_optional_field<O: DynamicOps, B: StructBuilder<Value = O::Value>>(
&self,
name: &'static str,
ops: &'static O,
prefix: B,
) -> B;
}
impl<T> OptionalFieldEncode for Option<T>
where
T: Encode,
{
fn encode_optional_field<O: DynamicOps, B: StructBuilder<Value = O::Value>>(
&self,
name: &'static str,
ops: &'static O,
prefix: B,
) -> B {
if let Some(value) = self {
value.encode_field(name, ops, prefix)
} else {
prefix
}
}
}
/// A trait to decode an optional field of a [`MapLike`] into a
/// value of the implementing type.
///
/// There is no `OptionalFieldEncode` variant of this trait; just
/// use [`FieldEncode::encode_field`] for encoding an optional field.
pub trait OptionalFieldDecode: Sized {
/// Decodes an optional field from a map, similar to [`FieldDecode::decode_field`].
///
/// However, this method has an extra `lenient` parameter. If it is `true`, errors
/// while decoding a `Some` option will not occur, and a `None` will be decoded instead.
fn decode_optional_field<O: DynamicOps>(
name: &'static str,
input: &impl MapLike<Value = O::Value>,
ops: &'static impl DynamicOps<Value = O::Value>,
lenient: bool,
) -> DataResult<Self>;
}
impl<T> OptionalFieldDecode for Option<T>
where
T: Decode,
{
fn decode_optional_field<O: DynamicOps>(
name: &'static str,
input: &impl MapLike<Value = O::Value>,
ops: &'static impl DynamicOps<Value = O::Value>,
lenient: bool,
) -> DataResult<Self> {
input.get_str(name).map_or_else(
|| DataResult::new_success(None),
|value| {
let result = T::parse(value.clone(), ops);
if result.is_error() && lenient {
DataResult::new_success(None)
} else {
result.map(Some)
}
},
)
}
}
@@ -0,0 +1,198 @@
use crate::codec::primitive::sealed::Primitive;
use crate::{DataResult, Decode, DynamicOps, Encode};
mod sealed {
use super::{DataResult, DynamicOps};
/// Sealed trait to easily implement `Encode` and `Decode` for
/// primitive DFU types.
pub trait Primitive: Sized {
fn primitive_encode<O: DynamicOps>(&self, ops: &'static O) -> O::Value;
fn primitive_decode<O: DynamicOps>(ops: &'static O, input: O::Value) -> DataResult<Self>;
}
}
impl<T: Primitive> Encode for T {
fn encode<O: DynamicOps>(&self, ops: &'static O, prefix: O::Value) -> DataResult<O::Value> {
ops.merge_into_primitive(prefix, self.primitive_encode(ops))
}
}
impl<T: Primitive> Decode for T {
fn decode<O: DynamicOps>(input: O::Value, ops: &'static O) -> DataResult<(Self, O::Value)> {
T::primitive_decode(ops, input).map(|r| (r, ops.empty()))
}
}
macro_rules! impl_number {
($ty:ty, $create_func:ident) => {
impl Primitive for $ty {
fn primitive_encode<O: DynamicOps>(&self, ops: &'static O) -> O::Value {
ops.$create_func(*self)
}
fn primitive_decode<O: DynamicOps>(
ops: &'static O,
input: O::Value,
) -> DataResult<Self> {
ops.get_number(&input).map(|n| <$ty>::from(n))
}
}
};
}
macro_rules! impl_number_and_unsigned {
($ty:ty, $uty:ty, $create_func:ident) => {
impl_number!($ty, $create_func);
// Unsigned type
impl Encode for $uty {
fn encode<O: DynamicOps>(
&self,
ops: &'static O,
prefix: O::Value,
) -> DataResult<O::Value> {
<$ty>::try_from(*self).map_or_else(
|_| {
DataResult::new_error(concat!(
"Could not fit ",
stringify!($uty),
" into ",
stringify!($ty)
))
},
|i| i.encode(ops, prefix),
)
}
}
impl Decode for $uty {
fn decode<O: DynamicOps>(
input: O::Value,
ops: &'static O,
) -> DataResult<(Self, O::Value)> {
<$ty>::parse(input, ops).flat_map(|i| {
<$uty>::try_from(i).map_or_else(
|_| {
DataResult::new_error(concat!(
"Could not fit ",
stringify!($ty),
" into ",
stringify!($uty)
))
},
|u| DataResult::new_success((u, ops.empty())),
)
})
}
}
};
}
impl_number_and_unsigned!(i8, u8, create_byte);
impl_number_and_unsigned!(i16, u16, create_short);
impl_number_and_unsigned!(i32, u32, create_int);
impl_number_and_unsigned!(i64, u64, create_long);
impl_number!(f32, create_float);
impl_number!(f64, create_double);
impl Primitive for bool {
fn primitive_encode<O: DynamicOps>(&self, ops: &'static O) -> O::Value {
ops.create_bool(*self)
}
fn primitive_decode<O: DynamicOps>(ops: &'static O, input: O::Value) -> DataResult<Self> {
ops.get_bool(&input)
}
}
impl Primitive for String {
fn primitive_encode<O: DynamicOps>(&self, ops: &'static O) -> O::Value {
ops.create_string(self.as_str())
}
fn primitive_decode<O: DynamicOps>(ops: &'static O, input: O::Value) -> DataResult<Self> {
ops.get_string(&input)
}
}
macro_rules! stream_struct {
($stream:ident, $ty:ty, $create_func:ident, $get_func:ident) => {
#[doc = concat!("A [`Vec<", stringify!($ty), ">`] wrapper that has built-in DFU support for encoding and decoding.")]
#[derive(Debug, Clone)]
pub struct $stream(pub Vec<$ty>);
impl From<Vec<$ty>> for $stream {
fn from(value: Vec<$ty>) -> Self {
Self(value)
}
}
impl From<$stream> for Vec<$ty> {
fn from(value: $stream) -> Vec<$ty> {
value.0
}
}
impl Primitive for $stream {
fn primitive_encode<O: DynamicOps>(&self, ops: &'static O) -> O::Value {
ops.$create_func(self.0.clone())
}
fn primitive_decode<O: DynamicOps>(ops: &'static O, input: O::Value) -> DataResult<Self> {
ops.$get_func(input).map(From::from)
}
}
};
}
stream_struct!(ByteBuffer, i8, create_byte_list, get_byte_list);
stream_struct!(IntStream, i32, create_int_list, get_int_list);
stream_struct!(LongStream, i64, create_long_list, get_long_list);
#[cfg(test)]
mod test {
use crate::json_ops::JsonOps;
use crate::{ByteBuffer, IntStream, LongStream, assert_decode, assert_encode_success};
use serde_json::json;
#[test]
fn encoding() {
assert_encode_success!(3, JsonOps, json!(3));
assert_encode_success!(-68i8, JsonOps, json!(-68));
assert_encode_success!(-913_813_743, JsonOps, json!(-913_813_743));
assert_encode_success!("Hello, world!".to_string(), JsonOps, json!("Hello, world!"));
assert_encode_success!(String::new(), JsonOps, json!(""));
assert_encode_success!(ByteBuffer::from(vec![1, 2, 3]), JsonOps, json!([1, 2, 3]));
assert_encode_success!(
IntStream::from(vec![3, 6, 9, 11, 15]),
JsonOps,
json!([3, 6, 9, 11, 15])
);
assert_encode_success!(
LongStream::from(vec![4, 6, 9, 12]),
JsonOps,
json!([4, 6, 9, 12])
);
assert_encode_success!(3u8, JsonOps, json!(3));
assert_encode_success!(923_482_312u64, JsonOps, json!(923_482_312));
}
#[test]
fn decoding() {
assert_decode!(i32, json!(-2), JsonOps, is_success);
assert_decode!(bool, json!("hello"), JsonOps, is_error);
assert_decode!(bool, json!(0), JsonOps, is_error);
assert_decode!(IntStream, json!([1, 2, 3]), JsonOps, is_success);
assert_decode!(LongStream, json!([]), JsonOps, is_success);
assert_decode!(ByteBuffer, json!(["not a number"]), JsonOps, is_error);
assert_decode!(String, json!("cool"), JsonOps, is_success);
assert_decode!(String, json!(1), JsonOps, is_error);
assert_decode!(u32, json!(-45), JsonOps, is_error);
assert_decode!(u64, json!(-132_541_235), JsonOps, is_error);
assert_decode!(u64, json!(132_541_235), JsonOps, is_success);
}
}
+698
View File
@@ -0,0 +1,698 @@
use crate::lifecycle::Lifecycle;
/// Collects the partial value and message from a `DataResult` if it is an error.
/// Returns an [`Option`] of the provided `DataResult`.
/// - The partial value is stored into `$partial_name`.
/// - If a message is found, it is pushed to `$messages_vec`.
macro_rules! collect_partial_and_message {
($partial_name:ident, $result:ident, $messages_vec:ident) => {
let $partial_name = match $result {
DataResult::Success { result, .. } => Some(result),
DataResult::Error {
message,
partial_result,
..
} => {
$messages_vec.push(message);
partial_result
}
};
};
}
/// A macro to generate a function to apply a function to each result of `n` `DataResult`s.
macro_rules! impl_apply {
(@internal_method $self:ident $f:ident $($result:ident),+) => {
let result_1 = $self;
if !(result_1.is_error() $(|| $result.is_error())+) {
// All n results are successful.
return DataResult::new_success($f(
result_1.into_result().unwrap()
$( , $result.into_result().unwrap() )+
));
}
let mut messages: Vec<String> = vec![];
// Collect any found errors.
collect_partial_and_message!(partial_1, result_1, messages);
$( collect_partial_and_message!($result, $result, messages); )+
return DataResult::new_option_error_with_lifecycle(
messages.join("; "),
match (partial_1, $($result, )+) {
(Some(result_1), $(Some($result), )+) => Some($f(result_1 $(, $result )+)),
_ => None,
},
Lifecycle::Experimental,
);
};
($name:ident, $n:literal, $($ty:ident, $result:ident),+) => {
#[doc = concat!("Applies a function to each result of ", stringify!($n), " `DataResult`s of different types.")]
///
/// - If any of the given results is a non-result, the returned result will also be a non-result.
/// - Any errors found in error results (non-result or partial result) will be added to the returned result.
/// - If all results are at least partial, `f` is called, which should return the final item to be wrapped in the returned result.
///
/// The returned result is a *success* **if and only if** all provided results are successes as well.
pub fn $name<$($ty,)+ T>(
self,
f: impl FnOnce(R $(,$ty)+) -> T
$(, $result: DataResult<$ty>)+
) -> DataResult<T> {
impl_apply!(@internal_method self f $($result),+);
}
};
(expect $name:ident, $n:literal, $($ty:ident, $result:ident),+) => {
#[doc = concat!("Applies a function to each result of ", stringify!($n), " `DataResult`s of different types.")]
///
/// - If any of the given results is a non-result, the returned result will also be a non-result.
/// - Any errors found in error results (non-result or partial result) will be added to the returned result.
/// - If all results are at least partial, `f` is called, which should return the final item to be wrapped in the returned result.
///
/// The returned result is a *success* **if and only if** all provided results are successes as well.
#[expect(clippy::too_many_arguments)]
pub fn $name<$($ty,)+ T>(
self,
f: impl FnOnce(R $(,$ty)+) -> T
$(, $result: DataResult<$ty>)+
) -> DataResult<T> {
impl_apply!(@internal_method self f $($result),+);
}
};
}
/// A result that can either represent a successful result, or a
/// *partial* or non-result with an error.
///
/// `R` is the type of result stored.
#[derive(Clone, Debug)]
#[must_use]
pub enum DataResult<R> {
/// Contains a complete result and has no error.
Success { result: R, lifecycle: Lifecycle },
/// Contains no or a partial result and has an error.
/// The error is a *format string*.
Error {
partial_result: Option<R>,
lifecycle: Lifecycle,
message: String,
},
}
impl<R> DataResult<R> {
/// Returns this `DataResult`'s lifecycle.
pub const fn lifecycle(&self) -> Lifecycle {
match self {
Self::Success { lifecycle, .. } | Self::Error { lifecycle, .. } => *lifecycle,
}
}
/// Sets this `DataResult`'s lifecycle and returns a new result.
pub fn with_lifecycle(self, new_lifecycle: Lifecycle) -> Self {
match self {
Self::Success { result, .. } => Self::Success {
result,
lifecycle: new_lifecycle,
},
Self::Error {
partial_result,
message,
..
} => Self::Error {
partial_result,
message,
lifecycle: new_lifecycle,
},
}
}
/// Adds another `Lifecycle` to this `DataResult`'s lifecycle and returns the new result.
pub fn add_lifecycle(self, added_lifecycle: Lifecycle) -> Self {
let new_lifecycle = self.lifecycle().add(added_lifecycle);
self.with_lifecycle(new_lifecycle)
}
/// Returns a *successful* `DataResult` with an experimental lifecycle.
#[inline]
pub const fn new_success(result: R) -> Self {
Self::new_success_with_lifecycle(result, Lifecycle::Experimental)
}
/// Returns a *successful* `DataResult` with a given lifecycle.
#[inline]
pub const fn new_success_with_lifecycle(result: R, lifecycle: Lifecycle) -> Self {
Self::Success { result, lifecycle }
}
/// Returns an *errored* `DataResult` with no result and an experimental lifecycle.
#[inline]
pub fn new_error(error: impl Into<String>) -> Self {
Self::new_error_with_lifecycle(error.into(), Lifecycle::Experimental)
}
/// Returns an *errored* `DataResult` with a partial result and an experimental lifecycle.
#[inline]
pub fn new_partial_error(error: impl Into<String>, partial_result: R) -> Self {
Self::new_partial_error_with_lifecycle(
error.into(),
partial_result,
Lifecycle::Experimental,
)
}
/// Returns an *errored* `DataResult` with no result and a given lifecycle.
#[inline]
pub fn new_error_with_lifecycle<T>(
message: impl Into<String>,
lifecycle: Lifecycle,
) -> DataResult<T> {
DataResult::Error {
partial_result: None,
lifecycle,
message: message.into(),
}
}
/// Returns an *errored* `DataResult` with a partial result and a given lifecycle.
#[inline]
pub fn new_partial_error_with_lifecycle(
message: impl Into<String>,
partial_result: R,
lifecycle: Lifecycle,
) -> Self {
Self::Error {
partial_result: Some(partial_result),
lifecycle,
message: message.into(),
}
}
/// Returns an *errored* `DataResult` with result [`Option<R>`] and a given lifecycle.
#[inline]
const fn new_option_error_with_lifecycle(
message: String,
partial_result: Option<R>,
lifecycle: Lifecycle,
) -> Self {
Self::Error {
partial_result,
lifecycle,
message,
}
}
/// Tries to get a complete result from this `DataResult`. If no such result exists, this returns [`None`] (even for partial results).
///
/// To allow partial results, use [`DataResult::into_result_or_partial`].
#[inline]
pub fn into_result(self) -> Option<R> {
if let Self::Success { result, .. } = self {
Some(result)
} else {
None
}
}
/// Tries to get a complete or partial result. If no such result exists, this returns [`None`].
pub fn into_result_or_partial(self) -> Option<R> {
match self {
Self::Success { result, .. } => Some(result),
Self::Error { partial_result, .. } => partial_result,
}
}
/// Tries to get a complete or partial result as a reference. If no such result exists, this returns [`None`].
pub const fn result_or_partial_as_ref(&self) -> Option<&R> {
match self {
Self::Success { result, .. } => Some(result),
Self::Error { partial_result, .. } => partial_result.as_ref(),
}
}
/// Tries to get a complete result from this `DataResult`. If no such result exists, this function panics.
pub fn unwrap(self) -> R {
self.expect("No complete result found for DataResult")
}
/// Tries to get a complete or partial result from this `DataResult`. If no such result exists, this function panics.
pub fn unwrap_or_partial(self) -> R {
self.expect_or_partial("No complete or partial result found for DataResult")
}
/// Tries to get a complete result from this `DataResult`. If no such result exists, this function panics with a custom message.
pub fn expect(self, message: &str) -> R {
self.into_result().unwrap_or_else(|| panic!("{}", message))
}
/// Tries to get a complete or partial result from this `DataResult`. If no such result exists, this function panics with a custom message.
pub fn expect_or_partial(self, message: &str) -> R {
self.into_result_or_partial()
.unwrap_or_else(|| panic!("{}", message))
}
/// Returns whether this `DataResult` has a complete or partial result.
pub const fn has_result_or_partial(&self) -> bool {
!matches!(
self,
Self::Error {
partial_result: None,
..
}
)
}
/// Appends two messages to form a bigger one.
/// This is useful for stacking message for data results with more than 1 error.
#[must_use]
pub fn append_messages(first: &str, second: &str) -> String {
format!("{first}; {second}")
}
/// Maps a `DataResult` of a type `R` to a `DataResult` of a type `T` by applying a function, leaving non-results untouched.
///
/// `f` is applied to complete results and partial ones. For partial results, `f` is applied to their partial value.
pub fn map<T>(self, op: impl FnOnce(R) -> T) -> DataResult<T> {
match self {
Self::Success { result, lifecycle } => {
DataResult::new_success_with_lifecycle(op(result), lifecycle)
}
Self::Error {
partial_result,
lifecycle,
message,
} => DataResult::new_option_error_with_lifecycle(
message,
partial_result.map(op),
lifecycle,
),
}
}
/// Maps a `DataResult` of a type `R` to a type `T`.
/// - If there is a complete result, `f` (the result function) is called with that result.
/// - Otherwise, if there is an error, `default` (the error function) is called with the error as the parameter.
pub fn map_or_else<T>(self, default: impl FnOnce(Self) -> T, f: impl Fn(R) -> T) -> T {
match self {
Self::Success { result, .. } => f(result),
Self::Error { .. } => default(self),
}
}
/// Chains a `DataResult` with another function taking a `DataResult`.
/// - If there is a complete or partial result, `f` is called with that result, and the value returned by `f` is returned.
/// For a partial result, new messages are propagated via concatenation.
/// - Otherwise, if there is an error with no result, this propagates this error `DataResult`.
///
/// In other words, `f` will process the complete or partial result of this `DataResult` (if any), appending errors if necessary.
///
/// The name of this function is equivalent to `and_then`.
pub fn flat_map<T>(self, f: impl FnOnce(R) -> DataResult<T>) -> DataResult<T> {
match self {
Self::Success { result, lifecycle } => {
// Add this DataResult's lifecycle to the new DataResult.
f(result).add_lifecycle(lifecycle)
}
Self::Error {
partial_result,
lifecycle,
message,
} => {
if let Some(result) = partial_result {
// Try mapping the internal partial value.
let second_result = f(result);
let new_lifecycle = second_result.lifecycle().add(lifecycle);
match second_result {
DataResult::Success { result, .. } => {
DataResult::new_partial_error_with_lifecycle(
message,
result,
new_lifecycle,
)
}
DataResult::Error {
partial_result,
message: second_message,
..
} => DataResult::new_option_error_with_lifecycle(
Self::append_messages(&message, &second_message),
partial_result,
new_lifecycle,
),
}
} else {
// Return this same Error.
DataResult::Error {
partial_result: None,
lifecycle,
message,
}
}
}
}
}
/// Applies a function wrapped in a `DataResult` to the value wrapped in this `DataResult`.
pub fn apply<T>(self, function_result: DataResult<impl FnOnce(R) -> T>) -> DataResult<T> {
let lifecycle = self.lifecycle().add(function_result.lifecycle());
match (self, function_result) {
(Self::Success { result, .. }, DataResult::Success { result: f, .. }) => {
DataResult::new_success_with_lifecycle(f(result), lifecycle)
}
(
Self::Success { result, .. },
DataResult::Error {
partial_result,
message: func_message,
..
},
) => DataResult::new_option_error_with_lifecycle(
func_message,
partial_result.map(|f| f(result)),
lifecycle,
),
(
Self::Error {
partial_result,
message,
..
},
DataResult::Success { result: f, .. },
) => DataResult::new_option_error_with_lifecycle(
message,
partial_result.map(f),
lifecycle,
),
(
Self::Error {
partial_result,
message,
..
},
DataResult::Error {
partial_result: partial_func_result,
message: func_message,
..
},
) => DataResult::new_option_error_with_lifecycle(
Self::append_messages(&message, &func_message),
partial_result.and_then(|r| partial_func_result.map(|f| f(r))),
lifecycle,
),
}
}
/// Similar to [`Self::apply_2`], but this also marks the returned `DataResult` as [`Lifecycle::Stable`].
pub fn apply_2_and_make_stable<R2, T>(
self,
f: impl FnOnce(R, R2) -> T,
second_result: DataResult<R2>,
) -> DataResult<T> {
self.apply_2(f, second_result)
.with_lifecycle(Lifecycle::Stable)
}
impl_apply!(apply_2, 2, R2, second_result);
impl_apply!(apply_3, 3, R2, result_2, R3, result_3);
impl_apply!(apply_4, 4, R2, result_2, R3, result_3, R4, result_4);
impl_apply!(
apply_5, 5, R2, result_2, R3, result_3, R4, result_4, R5, result_5
);
impl_apply!(
apply_6, 6, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6
);
impl_apply!(expect apply_7, 7, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7);
impl_apply!(expect apply_8, 8, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8);
impl_apply!(expect apply_9, 9, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9);
impl_apply!(expect apply_10, 10, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10);
impl_apply!(expect apply_11, 11, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10, R11, result_11);
impl_apply!(expect apply_12, 12, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10, R11, result_11, R12, result_12);
impl_apply!(expect apply_13, 13, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10, R11, result_11, R12, result_12, R13, result_13);
impl_apply!(expect apply_14, 14, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10, R11, result_11, R12, result_12, R13, result_13, R14, result_14);
impl_apply!(expect apply_15, 15, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10, R11, result_11, R12, result_12, R13, result_13, R14, result_14, R15, result_15);
impl_apply!(expect apply_16, 16, R2, result_2, R3, result_3, R4, result_4, R5, result_5, R6, result_6, R7, result_7, R8, result_8, R9, result_9, R10, result_10, R11, result_11, R12, result_12, R13, result_13, R14, result_14, R15, result_15, R16, result_16);
/// Applies a function to `DataResult` errors, leaving successes untouched.
/// This can be used to provide additional context to an error.
pub fn map_error(self, f: impl FnOnce(String) -> String) -> Self {
match self {
Self::Success { .. } => self,
Self::Error {
message,
lifecycle,
partial_result,
} => Self::new_option_error_with_lifecycle(f(message), partial_result, lifecycle),
}
}
/// Promotes a `DataResult` containing a partial result to a success `DataResult`, providing
/// the error message to a function `f` (consumer function) and removing it from the new `DataResult`.
/// `DataResult`s with no result or a complete result are left untouched.
pub fn promote_partial(self, f: impl FnOnce(String)) -> Self {
match self {
Self::Success { .. } => self,
Self::Error {
message,
lifecycle,
partial_result,
} => {
f(message.clone());
partial_result.map_or_else(
|| Self::new_error_with_lifecycle(message, lifecycle),
|result| Self::new_success_with_lifecycle(result, lifecycle),
)
}
}
}
/// Returns a `DataResult` with a new partial value (always partial), leaving `DataResult`s with a complete result untouched.
pub fn with_partial(self, partial_value: R) -> Self {
match self {
Self::Success { .. } => self,
Self::Error {
message, lifecycle, ..
} => Self::new_partial_error_with_lifecycle(message, partial_value, lifecycle),
}
}
/// Returns a `DataResult` with a new result/partial result, depending on the type of `DataResult` this is.
/// - For a complete result, this returns another `DataResult` whose complete result is `value`.
/// - For a partial result, this returns another `DataResult` whose partial result is `value`.
/// - For a non-result, this returns itself.
pub fn with_complete_or_partial<T>(self, value: T) -> DataResult<T> {
match self {
Self::Success { lifecycle, .. } => {
DataResult::new_success_with_lifecycle(value, lifecycle)
}
Self::Error {
message,
lifecycle,
partial_result: Some(_),
} => DataResult::new_partial_error_with_lifecycle(message, value, lifecycle),
Self::Error {
message, lifecycle, ..
} => Self::new_error_with_lifecycle(message, lifecycle),
}
}
/// Returns whether this `DataResult` was a success.
pub const fn is_success(&self) -> bool {
matches!(self, &Self::Success { .. })
}
/// Returns whether this `DataResult` was an error (including partial result errors).
pub const fn is_error(&self) -> bool {
!self.is_success()
}
/// Add a message of another `DataResult` (`other_result`) to this `DataResult`.
///
/// This is useful for *unit tuple* `DataResult`s used simply for final results of complex objects.
/// - If `other_result` is a complete result, nothing happens.
/// - If both results are partial, the returned result is also partial. Otherwise, it is a non-result.
/// - Messages found in any `DataResult` error are concatenated and used in the returned result.
///
/// This always returns a *stable* result.
pub fn add_message<T>(self, other_result: &DataResult<T>) -> Self {
match (self, other_result) {
// Both results are successful.
(Self::Success { result: r, .. }, DataResult::Success { .. }) => {
Self::new_success_with_lifecycle(r, Lifecycle::Stable)
}
// Both results are errors.
(
Self::Error {
partial_result: p1,
message: m1,
..
},
DataResult::Error {
partial_result: p2,
message: m2,
..
},
) => Self::new_option_error_with_lifecycle(
Self::append_messages(&m1, m2),
if p1.is_some() && p2.is_some() {
p1
} else {
None
},
Lifecycle::Stable,
),
// Exactly one of both results is an error.
(
Self::Error {
message: m1,
partial_result,
..
},
_,
) => Self::new_option_error_with_lifecycle(m1, partial_result, Lifecycle::Stable),
(
Self::Success { result, .. },
DataResult::Error {
message: m2,
partial_result,
..
},
) => Self::new_option_error_with_lifecycle(
m2.clone(),
partial_result.is_some().then_some(result),
Lifecycle::Stable,
),
}
}
/// Tries to add errors from the given `result` and adds them to `self`
/// if `self` is not already an error result.
///
/// The [`Lifecycle`] of the returned `DataResult` is the addition of both results.
pub fn with_errors_from<T>(self, result: &DataResult<T>) -> Self {
let current_lifecycle = self.lifecycle();
match (self, result) {
(s @ Self::Error { .. }, _) | (s, DataResult::Success { .. }) => s,
(
Self::Success { result: val, .. },
DataResult::Error {
message,
lifecycle: other_lifecycle,
..
},
) => Self::new_partial_error_with_lifecycle(
message.clone(),
val,
current_lifecycle.add(*other_lifecycle),
),
}
}
/// Returns the message of this `DataResult`, if any. Only error results have messages.
pub fn get_message(self) -> Option<String> {
match self {
Self::Success { .. } => None,
Self::Error { message, .. } => Some(message),
}
}
}
// Assertion functions
/// Asserts that the `$left` `DataResult` is a complete result (success) whose stored result is `$right`.
#[macro_export]
macro_rules! assert_success {
($left:expr, $right:expr $(,)?) => {{
let result = $left;
assert!(
result.is_success(),
"Expected a `DataResult` success, got: {:?}",
result
);
assert_eq!(
result.unwrap(),
$right,
"`DataResult` was successful but the value doesn't match"
);
}};
}
/// Asserts that encoding the left expression will lead to a complete result (success) whose stored result is `$right`.
#[macro_export]
macro_rules! assert_encode_success {
($left:expr, $ops:expr, $right:expr $(,)?) => {{
let result = $crate::codec::Encode::encode_start(&$left, &$ops);
assert!(
result.is_success(),
"Expected a `DataResult` success, got: {:?}",
result
);
assert_eq!(
result.unwrap(),
$right,
"`DataResult` was successful but the value doesn't match"
);
}};
}
/// Asserts that decoding the left expression will lead to a `DataResult` whose provided method returns `true`.
#[macro_export]
macro_rules! assert_decode {
($ty:ty, $input:expr, $ops:expr, $func:ident $(,)?) => {{
let result = <$ty as $crate::codec::Decode>::parse($input, &$ops);
assert!(
result.$func(),
concat!(
"Expected a `DataResult` that returns `true` for ",
stringify!($func),
", got: {:?}"
),
result
);
}};
}
impl<T> Default for DataResult<T> {
fn default() -> Self {
Self::new_error("Default DataResult")
}
}
/// A type conversion from one type to this type that may fail, resulting in a [`DataResult`].
///
/// Always prefer using [`FlatTryFrom`] over [`FlatTryInto`] for implementing the conversion,
/// as an implementation of [`FlatTryInto`] will automatically work as well.
pub trait FlatTryFrom<T>: Sized {
/// Performs the conversion.
fn flat_try_from(value: T) -> DataResult<Self>;
}
impl<T> FlatTryFrom<T> for T {
fn flat_try_from(value: T) -> DataResult<Self> {
DataResult::new_success(value)
}
}
impl<T, U> FlatTryInto<U> for T
where
U: FlatTryFrom<T>,
{
#[inline]
/// Calls `U::flat_try_from()`, which performs the conversion.
fn flat_try_into(self) -> DataResult<U> {
U::flat_try_from(self)
}
}
/// A type conversion from this type to another that may fail, resulting in a [`DataResult`].
///
/// Always prefer using [`FlatTryFrom`] over [`FlatTryInto`] for implementing the conversion,
/// as an implementation of [`FlatTryInto`] will automatically work as well.
pub trait FlatTryInto<T>: Sized {
/// Performs the conversion.
fn flat_try_into(self) -> DataResult<T>;
}
+337
View File
@@ -0,0 +1,337 @@
use crate::Number;
use crate::data_result::DataResult;
use crate::list_builder::{ListBuilder, new_list_builder_impl};
use crate::map_like::MapLike;
use crate::struct_builder::ResultStructBuilder;
use std::{collections::HashMap, fmt::Display};
/// Generates a default implementation for a create_*number* function.
macro_rules! create_number_impl {
($name:ident, $ty:ty, $number_ty:ident, $func:ident) => {
/// Returns how a generic
#[doc = concat!("`", stringify!($name), "`")]
/// in Java (equivalent to
#[doc = concat!("[`", stringify!($ty), "`])")]
/// is represented by this `DynamicOps`.
fn $func(&self, data: $ty) -> Self::Value {
self.create_number(Number::$number_ty(data))
}
};
}
/// A macro providing a default implementation of a get_... function in `DynamicOps`.
///
/// Those functions include:
/// - [`DynamicOps::get_byte_buffer`] (put `box` before the target expression (usually self))
/// - [`DynamicOps::get_int_list`]
/// - [`DynamicOps::get_long_list`]
#[macro_export]
macro_rules! impl_get_list {
($target:expr, $input:expr, $ty:literal) => {
$target.get_iter($input).flat_map(|iter| {
// We want all elements in the iterator to be numbers.
iter.map(|e| $target.get_number(&e).into_result().map(Into::into))
.collect::<Option<Vec<_>>>()
.map_or_else(
|| DataResult::new_error(concat!("Some elements are not ", $ty)),
DataResult::new_success,
)
})
};
}
/// A trait describing methods to read and write a specific format (like NBT or JSON).
/// The `Value` of this trait is the type that can be used to represent anything in this format.
pub trait DynamicOps {
type Value: PartialEq + Display + Clone;
type StructBuilder: ResultStructBuilder<Value = Self::Value>;
/// Returns how an empty value is represented by this `DynamicOps`.
fn empty(&self) -> Self::Value;
/// Returns how an empty list is represented by this `DynamicOps`.
fn empty_list(&self) -> Self::Value {
self.create_list(vec![])
}
/// Returns how an empty map is represented by this `DynamicOps`.
fn empty_map(&self) -> Self::Value {
self.create_map(HashMap::new())
}
/// Returns how a generic number is represented by this `DynamicOps`.
fn create_number(&self, n: Number) -> Self::Value;
create_number_impl!(byte, i8, Byte, create_byte);
create_number_impl!(short, i16, Short, create_short);
create_number_impl!(int, i32, Int, create_int);
create_number_impl!(long, i64, Long, create_long);
create_number_impl!(float, f32, Float, create_float);
create_number_impl!(double, f64, Double, create_double);
/// Returns how a boolean is represented by this `DynamicOps`.
fn create_bool(&self, data: bool) -> Self::Value;
/// Returns how a string is represented by this `DynamicOps`.
fn create_string(&self, data: &str) -> Self::Value;
/// Returns how a list is represented by this `DynamicOps`.
fn create_list<I>(&self, values: I) -> Self::Value
where
I: IntoIterator<Item = Self::Value>;
/// Returns how a map is represented by this `DynamicOps`.
fn create_map<I>(&self, entries: I) -> Self::Value
where
I: IntoIterator<Item = (Self::Value, Self::Value)>;
/// Tries to get a `bool` represented by this `DynamicOps`.
fn get_bool(&self, input: &Self::Value) -> DataResult<bool>;
/// Tries to get a number represented by this `DynamicOps`.
fn get_number(&self, input: &Self::Value) -> DataResult<Number>;
/// Tries to get a string represented by this `DynamicOps`.
fn get_string(&self, input: &Self::Value) -> DataResult<String>;
/// Gets an [`Iterator`] of key-value pairs from a map represented by this `DynamicOps`.
/// This is only applicable to map-like values.
fn get_map_iter<'a>(
&'a self,
input: &'a Self::Value,
) -> DataResult<impl Iterator<Item = (Self::Value, &'a Self::Value)> + 'a>;
/// Tries to get a [`MapLike`] for a map represented by this `DynamicOps`.
fn get_map<'a>(
&self,
input: &'a Self::Value,
) -> DataResult<impl MapLike<Value = Self::Value> + 'a>;
/// Gets an [`Iterator`] from a generic value represented by this `DynamicOps`.
/// This is the equivalent of DFU's `getStream()` function, and is only applicable to list-like values.
fn get_iter(&self, input: Self::Value) -> DataResult<impl Iterator<Item = Self::Value>>;
/// Gets a `Box<[u8]>` (byte buffer) from a generic value represented by this `DynamicOps`.
/// This is the equivalent of DFU's `getByteBuffer()` function.
fn get_byte_list(&self, input: Self::Value) -> DataResult<Vec<i8>> {
impl_get_list!(self, input, "bytes")
}
/// Creates a byte buffer that can be represented by this `DynamicOps` using a [`Vec<u8>`].
fn create_byte_list(&self, vec: Vec<i8>) -> Self::Value {
self.create_list(vec.into_iter().map(|b| self.create_byte(b)))
}
/// Gets a [`Vec<i32>`] (`int` list) from a generic value represented by this `DynamicOps`.
/// This is the equivalent of DFU's `getIntStream()` function.
fn get_int_list(&self, input: Self::Value) -> DataResult<Vec<i32>> {
impl_get_list!(self, input, "ints")
}
/// Creates an `int` list ([`Vec<i32>`]) that can be represented by this `DynamicOps`.
fn create_int_list(&self, vec: Vec<i32>) -> Self::Value {
self.create_list(vec.into_iter().map(|i| self.create_int(i)))
}
/// Gets a [`Vec<i64>`] (`long` list) from a generic value represented by this `DynamicOps`.
/// This is the equivalent of DFU's `getLongStream()` function.
fn get_long_list(&self, input: Self::Value) -> DataResult<Vec<i64>> {
impl_get_list!(self, input, "longs")
}
/// Creates a `long` list ([`Vec<i64>`]) that can be represented by this `DynamicOps`.
fn create_long_list(&self, vec: Vec<i64>) -> Self::Value {
self.create_list(vec.into_iter().map(|l| self.create_long(l)))
}
/// Merges a value represented by this `DynamicOps` to a list represented by this `DynamicOps`.
/// This is only valid if `list` is an actual list.
fn merge_into_list(&self, list: Self::Value, value: Self::Value) -> DataResult<Self::Value>;
/// Merges a list of values represented by this `DynamicOps` into another such list.
/// This is only valid if `list` is an actual list.
fn merge_values_into_list<I>(&self, list: Self::Value, values: I) -> DataResult<Self::Value>
where
I: IntoIterator<Item = Self::Value>,
{
let mut result = DataResult::new_success(list);
for value in values {
result = result.flat_map(|list_value| self.merge_into_list(list_value, value));
}
result
}
/// Adds a key-value pair, both represented by this `DynamicOps`, to a map also represented by this `DynamicOps`,
/// returning the new map. This is only valid if `map` is an actual map or is empty.
fn merge_into_map(
&self,
map: Self::Value,
key: Self::Value,
value: Self::Value,
) -> DataResult<Self::Value>
where
Self::Value: Clone;
/// Merges a map represented by this `DynamicOps` into another such map, returning the new map.
/// This is only valid if `map` is an actual map or is empty.
fn merge_entries_into_map<I>(&self, map: Self::Value, entries: I) -> DataResult<Self::Value>
where
I: IntoIterator<Item = (Self::Value, Self::Value)>,
Self::Value: Clone,
{
let mut result = DataResult::new_success(map);
for (key, value) in entries {
result = result.flat_map(|list_value| self.merge_into_map(list_value, key, value));
}
result
}
/// Merges a [`MapLike`] represented by this `DynamicOps` into another such map, returning the new map.
/// This is only valid if `map` is an actual map or is empty.
fn merge_map_like_into_map<M>(
&self,
map: Self::Value,
other_map_like: M,
) -> DataResult<Self::Value>
where
M: MapLike<Value = Self::Value>,
Self::Value: Clone,
{
let mut result = DataResult::new_success(map);
for (key, value) in other_map_like.iter() {
result =
result.flat_map(|list_value| self.merge_into_map(list_value, key, value.clone()));
}
result
}
/// Merges a value represented by this `DynamicOps` into a primitive type.
fn merge_into_primitive(
&self,
prefix: Self::Value,
value: Self::Value,
) -> DataResult<Self::Value>
where
<Self as DynamicOps>::Value: PartialEq,
{
if prefix == self.empty() {
DataResult::new_success(value)
} else {
DataResult::new_error(format!(
"Do not know how to append a primitive value {value} to {prefix}"
))
}
}
/// Tries to remove something from a value represented by this `DynamicOps` using a key.
/// This returns the new value if successful, otherwise, this returns itself.
fn remove(&self, input: Self::Value, key: &str) -> Self::Value;
/// Tries to get a value from a value represented by this `DynamicOps` using a key.
/// Only works for values that can be [`MapLike`]-viewed.
fn get_element<'a>(&'a self, input: &'a Self::Value, key: &str) -> DataResult<&'a Self::Value> {
self.get_element_generic(input, &self.create_string(key))
}
/// Tries to get a value from a value represented by this `DynamicOps` using a key also represented by this `DynamicOps`.
fn get_element_generic<'a>(
&'a self,
input: &'a Self::Value,
key: &Self::Value,
) -> DataResult<&'a Self::Value>
where {
self.get_map_iter(input).flat_map(|mut iter| {
iter.find(|(k, _)| k == key).map_or_else(
|| DataResult::new_error(format!("No element {key} in the map")),
|(_, v)| DataResult::new_success(v),
)
})
}
/// Tries to set a value represented by this `DynamicOps` to a key to a map also represented by this `DynamicOps`.
/// - It this was successful, this returns the new map value.
/// - Otherwise, this simply returns `input`.
fn set_element(&self, input: &Self::Value, key: &str, value: Self::Value) -> Self::Value
where
Self::Value: Clone,
{
self.merge_into_map(input.clone(), self.create_string(key), value)
.into_result()
.unwrap_or(input.clone())
}
/// Tries to update a value represented by this `DynamicOps` of a map also represented by this `DynamicOps`, with
/// a key and a mapper function (`f`) whose return value will be the new value of the specified key.
/// - It this was successful, this returns the newly manipulated map.
/// - Otherwise, this simply returns `input`.
fn update_element<F>(&self, input: &Self::Value, key: &str, f: F) -> Self::Value
where
F: FnOnce(&Self::Value) -> Self::Value,
{
self.get_element(input, key)
.map(|v| self.set_element(input, key, f(v)))
.into_result()
.unwrap_or(input.clone())
}
/// Tries to update a value represented by this `DynamicOps` of a map also represented by this `DynamicOps`, with
/// a key also represented by this `DynamicOps` and a mapper function (`f`) whose return value will be the new key's value.
/// - It this was successful, this returns the newly manipulated map.
/// - Otherwise, this simply returns `input`.
fn update_element_generic<F>(&self, input: &Self::Value, key: &Self::Value, f: F) -> Self::Value
where
F: FnOnce(&Self::Value) -> Self::Value,
{
self.get_element_generic(input, key)
.flat_map(|v| self.merge_into_map(input.clone(), key.clone(), f(v)))
.into_result()
.unwrap_or(input.clone())
}
/// Converts a value represented by this `DynamicOps` to another value represented by another `DynamicOps`.
fn convert_to<U>(&self, out_ops: &impl DynamicOps<Value = U>, input: Self::Value) -> U;
/// Converts a list represented by this `DynamicOps` to another list represented by another `DynamicOps`.
fn convert_list<U>(&self, out_ops: &impl DynamicOps<Value = U>, input: Self::Value) -> U {
out_ops.create_list(
self.get_iter(input)
.into_result()
.into_iter()
.flatten()
.map(|v| self.convert_to(out_ops, v)),
)
}
/// Converts a map represented by this `DynamicOps` to another map represented by another `DynamicOps`.
fn convert_map<U>(&self, out_ops: &impl DynamicOps<Value = U>, input: Self::Value) -> U {
out_ops.create_map(
self.get_map_iter(&input)
.into_result()
.into_iter()
.flatten()
.map(|(k, v)| {
(
self.convert_to(out_ops, k),
self.convert_to(out_ops, v.clone()),
)
}),
)
}
/// Returns a [`ListBuilder`] for this `DynamicOps`.
fn list_builder(&'static self) -> impl ListBuilder<Value = Self::Value>
where
Self: Sized,
{
new_list_builder_impl(self)
}
/// Returns a [`MapBuilder`] for this `DynamicOps`.
fn map_builder(&'static self) -> Self::StructBuilder;
}
+384
View File
@@ -0,0 +1,384 @@
use std::fmt::{Debug, Display};
use crate::{Number, data_result::DataResult, dynamic_ops::DynamicOps, map_like::MapLike};
use crate::lifecycle::Lifecycle;
use crate::struct_builder::{ResultStructBuilder, StringStructBuilder, StructBuilder};
use crate::{impl_string_struct_builder, impl_struct_builder};
use serde_json::{Map, Value};
use tracing::warn;
/// A [`DynamicOps`] to serialize to/deserialize from JSON data.
pub struct JsonOps;
impl JsonOps {
/// A function to get a JSON value as a string, similar to Google's GSON's `getAsString()` method for `JsonElement`.
/// This is to keep parity with the `JsonOps` methods that check for `compressed`.
///
/// In particular, this method may return `Some` for *ONLY* the following:
/// - Booleans (always)
/// - Numbers (always)
/// - Strings (always)
/// - Arrays with exactly 1 element (in this case, this is called for that element).
///
/// Any other case returns `None`.
fn get_as_string(input: &Value) -> Option<String> {
match input {
Value::Array(elements) => {
// If we have an array, it must only have 1 element.
if elements.len() == 1 {
Self::get_as_string(&elements[0])
} else {
None
}
}
Value::Bool(b) => Some(b.to_string()),
Value::Number(n) => Some(n.to_string()),
Value::String(s) => Some(s.clone()),
_ => None,
}
}
/// Whether a JSON value is considered to be a valid key.
///
/// If this returns `true`, it is safe to say that calling [`get_as_string`] with `input` will always return a [`Some`].
const fn is_valid_key(input: &Value) -> bool {
matches!(input, Value::String(_))
}
}
impl DynamicOps for JsonOps {
type Value = Value;
type StructBuilder = JsonStructBuilder;
fn empty(&self) -> Self::Value {
Value::Null
}
fn create_number(&self, n: Number) -> Self::Value {
n.into()
}
fn create_bool(&self, data: bool) -> Self::Value {
Value::Bool(data)
}
fn create_string(&self, data: &str) -> Self::Value {
Value::String(data.to_owned())
}
fn create_list<I>(&self, values: I) -> Self::Value
where
I: IntoIterator<Item = Self::Value>,
{
Value::Array(values.into_iter().collect())
}
fn create_map<I>(&self, entries: I) -> Self::Value
where
I: IntoIterator<Item = (Self::Value, Self::Value)>,
{
Value::Object(
entries
.into_iter()
.filter_map(|(k, v)| Self::get_as_string(&k).map(|k| (k, v)))
.collect(),
)
}
fn get_bool(&self, input: &Self::Value) -> DataResult<bool> {
if let Value::Bool(b) = input {
DataResult::new_success(*b)
} else {
DataResult::new_error(format!("Not a boolean: {input}"))
}
}
fn get_number(&self, input: &Self::Value) -> DataResult<Number> {
if let Value::Number(_) = input {
input.try_into().map_or_else(
|_| DataResult::new_error(format!("Not a number: {input}")),
DataResult::new_success,
)
} else {
DataResult::new_error(format!("Not a number: {input}"))
}
}
fn get_string(&self, input: &Self::Value) -> DataResult<String> {
if let Value::String(_) = input {
// Unwrapping is fine as only strings are possible here.
DataResult::new_success(Self::get_as_string(input).unwrap())
} else {
DataResult::new_error(format!("Not a string: {input}"))
}
}
fn get_map_iter<'a>(
&self,
input: &'a Self::Value,
) -> DataResult<impl Iterator<Item = (Self::Value, &'a Self::Value)> + 'a> {
if let Value::Object(map) = input {
DataResult::new_success(map.iter().map(|(k, v)| (Value::String(k.clone()), v)))
} else {
DataResult::new_error(format!("Not a JSON object: {input}"))
}
}
fn get_map<'a>(
&self,
input: &'a Self::Value,
) -> DataResult<impl MapLike<Value = Self::Value> + 'a> {
if let Value::Object(map) = input {
DataResult::new_success(JsonMapLike { map })
} else {
DataResult::new_error(format!("Not a JSON object: {input}"))
}
}
fn get_iter(&self, input: Self::Value) -> DataResult<impl Iterator<Item = Self::Value>> {
// This only works for JSON arrays.
if let Value::Array(list) = input {
DataResult::new_success(list.into_iter())
} else {
DataResult::new_error(format!("Not a JSON array: {input}"))
}
}
fn merge_into_list(&self, list: Self::Value, value: Self::Value) -> DataResult<Self::Value> {
if matches!(list, Value::Array(_)) || list == self.empty() {
let mut result_vec = vec![];
if let Value::Array(a) = list {
result_vec.extend(a);
}
result_vec.push(value);
DataResult::new_success(Value::Array(result_vec))
} else {
DataResult::new_partial_error(format!("Not a list: {list}"), list)
}
}
fn merge_values_into_list<I>(&self, list: Self::Value, values: I) -> DataResult<Self::Value>
where
I: IntoIterator<Item = Self::Value>,
{
if matches!(list, Value::Array(_)) || list == self.empty() {
let mut result_vec = vec![];
if let Value::Array(a) = list {
result_vec.extend(a);
}
result_vec.extend(values);
DataResult::new_success(Value::Array(result_vec))
} else {
DataResult::new_partial_error(format!("Not a list: {list}"), list)
}
}
fn merge_into_map(
&self,
map: Self::Value,
key: Self::Value,
value: Self::Value,
) -> DataResult<Self::Value>
where
Self::Value: Clone,
{
if !matches!(map, Value::Object(_)) && map != self.empty() {
return DataResult::new_partial_error(format!("Not a map: {map}"), map);
}
if !Self::is_valid_key(&key) {
return DataResult::new_partial_error(format!("Key is not a string: {key}"), map);
}
let mut output_map = Map::new();
if let Value::Object(mut m) = map {
output_map.append(&mut m);
}
output_map.insert(Self::get_as_string(&key).unwrap(), value);
DataResult::new_success(Value::Object(output_map))
}
fn merge_map_like_into_map<M>(
&self,
map: Self::Value,
other_map_like: M,
) -> DataResult<Self::Value>
where
M: MapLike<Value = Self::Value>,
Self::Value: Clone,
{
if matches!(map, Value::Object(_)) || map == self.empty() {
let mut output_map = Map::new();
if let Value::Object(mut m) = map {
output_map.append(&mut m);
}
// Store the missed entries.
let mut missed = vec![];
for entry in other_map_like.iter() {
if Self::is_valid_key(&entry.0) {
output_map.insert(Self::get_as_string(&entry.0).unwrap(), entry.1.clone());
} else {
missed.push(entry.0);
}
}
let object = Value::Object(output_map);
let pretty_missed = serde_json::to_string_pretty(&missed);
if missed.is_empty() {
DataResult::new_success(object)
} else {
DataResult::new_partial_error(
format!(
"Some keys are not strings{}",
pretty_missed.map_or_else(|_| String::new(), |r| format!(": {r}"))
),
object,
)
}
} else {
DataResult::new_partial_error(format!("Not a map: {map}"), map)
}
}
fn remove(&self, input: Self::Value, key: &str) -> Value {
if let Value::Object(m) = input {
Value::Object(m.into_iter().filter(|(k, _)| k != key).collect())
} else {
input
}
}
fn convert_to<U>(&self, out_ops: &impl DynamicOps<Value = U>, input: Self::Value) -> U {
match input {
Value::Null => out_ops.empty(),
Value::Bool(b) => out_ops.create_bool(b),
Value::String(s) => out_ops.create_string(&s),
Value::Array(_) => self.convert_list(out_ops, input),
Value::Object(_) => self.convert_map(out_ops, input),
Value::Number(n) => {
// First, check for possible integers.
if let Some(l) = n.as_i64() {
if (l as i8) as i64 == l {
return out_ops.create_byte(l as i8);
} else if (l as i16) as i64 == l {
return out_ops.create_short(l as i16);
} else if (l as i32) as i64 == l {
return out_ops.create_int(l as i32);
}
out_ops.create_long(l)
// If no integer is possible, check for possible floating-point values.
} else if let Some(f) = n.as_f64() {
if (f as f32) as f64 == f {
return out_ops.create_float(f as f32);
}
out_ops.create_double(f)
} else {
// Just in case.
warn!("Number could not be placed in JSON while converting: {n}");
out_ops.create_double(0.0)
}
}
}
}
fn map_builder(&'static self) -> Self::StructBuilder {
JsonStructBuilder {
builder: DataResult::new_success_with_lifecycle(
Value::Object(Map::new()),
Lifecycle::Stable,
),
}
}
}
/// An implementation of [`MapLike`] for JSON objects.
/// The lifetime is that of the referenced map.
struct JsonMapLike<'a> {
map: &'a Map<String, Value>,
}
impl MapLike for JsonMapLike<'_> {
type Value = Value;
fn get(&self, key: &Self::Value) -> Option<&Self::Value> {
JsonOps::get_as_string(key).and_then(|s| self.get_str(&s))
}
fn get_str(&self, key: &str) -> Option<&Self::Value> {
self.map.get(key)
}
fn iter(&self) -> impl Iterator<Item = (Self::Value, &Self::Value)> + '_ {
self.map.iter().map(|(k, v)| (Value::String(k.clone()), v))
}
}
impl Display for JsonMapLike<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.map.fmt(f)
}
}
/// An implementation of [`StructBuilder`] for JSON objects.
pub struct JsonStructBuilder {
builder: DataResult<Value>,
}
impl ResultStructBuilder for JsonStructBuilder {
type Result = Value;
fn build_with_builder(
self,
builder: Self::Result,
prefix: Self::Value,
) -> DataResult<Self::Value> {
match prefix {
Value::Null => DataResult::new_success(builder),
Value::Object(mut map) => {
match builder {
Value::Object(builder_map) => {
for (k, v) in builder_map {
map.insert(k, v);
}
}
// This shouldn't happen, but just in case.
_ => {
return DataResult::new_error(format!(
"Expected object in builder, found {builder}"
));
}
}
DataResult::new_success(Value::Object(map))
}
_ => DataResult::new_partial_error(format!("Prefix is not a map: {prefix}"), prefix),
}
}
}
impl StructBuilder for JsonStructBuilder {
type Value = Value;
impl_struct_builder!(builder);
impl_string_struct_builder!(builder, JsonOps);
}
impl StringStructBuilder for JsonStructBuilder {
fn append(&self, key: &str, value: Self::Value, mut builder: Self::Result) -> Self::Result {
builder
.as_object_mut()
.unwrap()
.insert(key.to_string(), value);
builder
}
}
+27
View File
@@ -0,0 +1,27 @@
mod data_result;
mod dynamic_ops;
pub mod json_ops;
mod lifecycle;
mod list_builder;
mod map_like;
pub mod struct_builder;
pub mod codec;
mod number;
pub use crate::data_result::DataResult;
pub use crate::data_result::FlatTryFrom;
pub use crate::data_result::FlatTryInto;
pub use crate::dynamic_ops::DynamicOps;
pub use crate::lifecycle::Lifecycle;
pub use crate::list_builder::ListBuilder;
pub use crate::map_like::MapLike;
pub use number::Number;
pub use crate::codec::Decode;
pub use crate::codec::Encode;
pub use crate::codec::either::Either;
pub use crate::codec::primitive::ByteBuffer;
pub use crate::codec::primitive::IntStream;
pub use crate::codec::primitive::LongStream;
+61
View File
@@ -0,0 +1,61 @@
/// A marker to convey the lifecycle of some object.
/// It could be stable, experimental or deprecated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lifecycle {
/// Represents something stable.
Stable,
/// Represents something experimental.
Experimental,
/// Represents something deprecated. The `u32` with this lifecycle represents the *date* from which it was marked to be deprecated.
///
/// If the number is smaller, it was deprecated earlier, whereas if it is bigger, it was deprecated later.
Deprecated(u32),
}
impl Lifecycle {
/// Adds a lifecycle to another, returning a resultant lifecycle which matches the more restrictive of the two.
///
/// This function follows this order:
/// - If at least one of the lifecycles is *experimental*, [`Lifecycle::Experimental`] is returned.
/// - If both lifecycles are *deprecated*, this returns the earlier-deprecated one (where the *date* is lower).
/// - If exactly one lifecycle is *deprecated*, that lifecycle is returned.
/// - If nothing above matches, [`Lifecycle::Stable`] is returned.
#[must_use]
pub const fn add(self, other: Self) -> Self {
match (self, other) {
(Self::Experimental, _) | (_, Self::Experimental) => Self::Experimental,
(d1 @ Self::Deprecated(s1), d2 @ Self::Deprecated(s2)) => {
if s1 < s2 {
d1
} else {
d2
}
}
(d @ Self::Deprecated(_), _) | (_, d @ Self::Deprecated(_)) => d,
_ => Self::Stable,
}
}
}
#[cfg(test)]
mod test {
use crate::lifecycle::Lifecycle;
#[test]
fn add_lifecycles() {
assert_eq!(Lifecycle::Stable.add(Lifecycle::Stable), Lifecycle::Stable);
assert_eq!(
Lifecycle::Experimental.add(Lifecycle::Deprecated(10)),
Lifecycle::Experimental
);
assert_eq!(
Lifecycle::Deprecated(10).add(Lifecycle::Deprecated(15)),
Lifecycle::Deprecated(10)
);
}
}
+65
View File
@@ -0,0 +1,65 @@
use crate::data_result::DataResult;
use crate::dynamic_ops::DynamicOps;
/// A trait for building lists.
#[must_use]
pub trait ListBuilder {
type Value;
/// Builds the final list and returns the result.
fn build(self, prefix: Self::Value) -> DataResult<Self::Value>;
/// Adds a direct value to this [`ListBuilder`].
#[must_use]
fn add(self, value: Self::Value) -> Self;
/// Adds a [`DataResult`] to this [`ListBuilder`].
#[must_use]
fn add_data_result(self, value: DataResult<Self::Value>) -> Self;
}
/// An implementation of [`ListBuilder`].
pub struct ListBuilderImpl<T, O: 'static> {
elements: DataResult<Vec<T>>,
ops: &'static O,
}
pub fn new_list_builder_impl<T>(
ops: &'static impl DynamicOps<Value = T>,
) -> impl ListBuilder<Value = T> {
ListBuilderImpl {
elements: DataResult::new_success(vec![]),
ops,
}
}
impl<T, O> ListBuilder for ListBuilderImpl<T, O>
where
O: DynamicOps<Value = T>,
{
type Value = T;
fn build(self, prefix: Self::Value) -> DataResult<Self::Value> {
self.elements
.flat_map(|e| self.ops.merge_values_into_list(prefix, e))
}
fn add(mut self, value: Self::Value) -> Self {
self.elements = self.elements.map(|mut e: Vec<T>| {
e.push(value);
e
});
self
}
fn add_data_result(mut self, value: DataResult<T>) -> Self {
self.elements = self.elements.apply_2_and_make_stable(
|mut e, v| {
e.push(v);
e
},
value,
);
self
}
}
+14
View File
@@ -0,0 +1,14 @@
/// A trait that can be used to treat something as a map view of a dynamic type.
/// The [`Value`] of this trait is the *dynamic type* of this map-like.
pub trait MapLike {
type Value;
/// Gets the value of this map view with a key of the *dynamic type* of this map-like.
fn get(&self, key: &Self::Value) -> Option<&Self::Value>;
/// Gets the value of this map view with a `&str` key of the *dynamic type* of this map-like with the provided [`DynamicOps`] of this map-like's *dynamic type*.
fn get_str(&self, key: &str) -> Option<&Self::Value>;
/// Returns an `Iterator` to each key-value pair in this map-like, both of its *dynamic type*.
fn iter(&self) -> impl Iterator<Item = (Self::Value, &Self::Value)> + '_;
}
+150
View File
@@ -0,0 +1,150 @@
use core::fmt;
use std::fmt::{Display, Formatter};
/// Represents a generic number in Java.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Number {
Byte(i8),
Short(i16),
Int(i32),
Long(i64),
Float(f32),
Double(f64),
}
impl From<Number> for i64 {
fn from(num: Number) -> Self {
match num {
Number::Byte(b) => b as Self,
Number::Short(s) => s as Self,
Number::Int(i) => i as Self,
Number::Long(l) => l,
Number::Float(f) => f as Self,
Number::Double(d) => d as Self,
}
}
}
impl From<Number> for i32 {
fn from(num: Number) -> Self {
match num {
Number::Byte(b) => b as Self,
Number::Short(s) => s as Self,
Number::Int(i) => i,
Number::Long(l) => l as Self,
Number::Float(f) => f as Self,
Number::Double(d) => d as Self,
}
}
}
impl From<Number> for i16 {
fn from(num: Number) -> Self {
// Similar to Java, we will first convert the number to an `i16`, and then to an `i8`.
i32::from(num) as Self
}
}
impl From<Number> for i8 {
fn from(num: Number) -> Self {
// Similar to Java, we will first convert the number to an `i32`, and then to an `i8`.
i32::from(num) as Self
}
}
impl From<Number> for u8 {
fn from(num: Number) -> Self {
i32::from(num) as Self
}
}
impl From<Number> for f32 {
fn from(num: Number) -> Self {
match num {
Number::Byte(b) => b as Self,
Number::Short(s) => s as Self,
Number::Int(i) => i as Self,
Number::Long(l) => l as Self,
Number::Float(f) => f,
Number::Double(d) => d as Self,
}
}
}
impl From<Number> for f64 {
fn from(num: Number) -> Self {
match num {
Number::Byte(b) => b as Self,
Number::Short(s) => s as Self,
Number::Int(i) => i as Self,
Number::Long(l) => l as Self,
Number::Float(f) => f as Self,
Number::Double(d) => d,
}
}
}
impl Display for Number {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Byte(v) => write!(f, "{v}"),
Self::Short(v) => write!(f, "{v}"),
Self::Int(v) => write!(f, "{v}"),
Self::Long(v) => write!(f, "{v}"),
Self::Float(v) => write!(f, "{v}"),
Self::Double(v) => write!(f, "{v}"),
}
}
}
impl From<Number> for serde_json::Value {
fn from(num: Number) -> Self {
match num {
Number::Byte(n) => n.into(),
Number::Short(n) => n.into(),
Number::Int(n) => n.into(),
Number::Long(n) => n.into(),
Number::Float(n) => n.into(),
Number::Double(n) => n.into(),
}
}
}
/// An error struct returned for an invalid conversion to [`Number`] from a [`serde_json::Value`].
pub struct FromJsonValueError;
impl TryFrom<&serde_json::Value> for Number {
type Error = FromJsonValueError;
fn try_from(num: &serde_json::Value) -> Result<Self, Self::Error> {
num.clone().try_into()
}
}
impl TryFrom<serde_json::Value> for Number {
type Error = FromJsonValueError;
fn try_from(num: serde_json::Value) -> Result<Self, Self::Error> {
match num {
serde_json::Value::Number(n) => n.try_into(),
_ => Err(FromJsonValueError),
}
}
}
impl TryFrom<serde_json::Number> for Number {
type Error = FromJsonValueError;
fn try_from(num: serde_json::Number) -> Result<Self, Self::Error> {
// Try converting the number to an integer first.
num.as_i64().map_or_else(
// Try the float conversion.
|| {
num.as_f64()
.map_or(Err(FromJsonValueError), |f| Ok(Self::Double(f)))
},
// Do the integer conversion.
|n| Ok(Self::Long(n)),
)
}
}
+292
View File
@@ -0,0 +1,292 @@
use crate::data_result::DataResult;
use crate::dynamic_ops::DynamicOps;
use crate::lifecycle::Lifecycle;
/// A trait specifying a builder to add key-value pairs in order to create a composite type.
///
/// `Value` is the dynamic type for this builder.
/// For a struct, some methods here can be implemented via the `impl_struct_builder` macro.
pub trait StructBuilder {
type Value;
/// Adds a single key-value pair to this builder and returns the builder.
#[must_use]
fn add_key_value(self, key: Self::Value, value: Self::Value) -> Self;
/// Adds a single key-'value result' pair to this builder and returns the builder.
#[must_use]
fn add_key_value_result(self, key: Self::Value, value: DataResult<Self::Value>) -> Self;
/// Adds a single 'key result'-'value result' pair to this builder and returns the builder.
#[must_use]
fn add_key_result_value_result(
self,
key: DataResult<Self::Value>,
value: DataResult<Self::Value>,
) -> Self;
/// Adds the error message from a provided `DataResult` (if any) to this builder and returns the builder.
#[must_use]
fn with_errors_from<T>(self, result: &DataResult<T>) -> Self;
/// Adds a string key-value pair to this builder and returns the builder.
#[must_use]
fn add_string_key_value(self, key: &str, value: Self::Value) -> Self;
/// Adds a string key-'value result' pair to this builder and returns the builder.
#[must_use]
fn add_string_key_value_result(self, key: &str, value: DataResult<Self::Value>) -> Self;
/// Sets the lifecycle of this builder and returns the builder.
#[must_use]
fn set_lifecycle(self, lifecycle: Lifecycle) -> Self;
/// Maps the error from the internal builder to the function `f` and returns the builder.
#[must_use]
fn map_error(self, f: impl FnOnce(String) -> String) -> Self;
/// Builds the map stored in this builder along with a prefix and returns the result.
fn build(self, prefix: Self::Value) -> DataResult<Self::Value>;
/// Builds the map stored in this builder along with a `DataResult` prefix and returns the result.
fn build_with_result_prefix(self, prefix: DataResult<Self::Value>) -> DataResult<Self::Value>
where
Self: Sized,
{
prefix.flat_map(|p| self.build(p))
}
}
/// A [`StructBuilder`] with a specified `Result` type for builders.
pub trait ResultStructBuilder: StructBuilder {
type Result;
/// Builds the map stored in `builder` along with a prefix and returns the result.
fn build_with_builder(
self,
builder: Self::Result,
prefix: Self::Value,
) -> DataResult<Self::Value>;
}
/// A subtrait of [`StructBuilder`] for appending string keys instead of dynamic type keys.
/// The methods in `StructBuilder` can also be implemented via the `impl_string_struct_builder` macro.
pub trait StringStructBuilder: ResultStructBuilder {
/// Appends a string key-value pair to `builder`, mutating it.
fn append(&self, key: &str, value: Self::Value, builder: Self::Result) -> Self::Result;
}
/// A subtrait of [`StructBuilder`] for appending dynamic keys. The methods in `StructBuilder`
/// can also be implemented via the `impl_universal_struct_builder` macro.
pub trait UniversalStructBuilder: ResultStructBuilder {
/// Appends a key-value pair to `builder`, mutating it.
fn append(&self, key: Self::Value, value: Self::Value, builder: Self::Result) -> Self::Result;
}
/// A macro to be placed inside an `impl` block of a struct implementing [`StructBuilder`].
///
/// Place this in a `impl StructBuilder for ...` block.
/// This automatically implements the methods to add key-value pairs to the builder.
/// Make sure to have a struct field of type [`DataResult<Self::Value>`] of name `$builder`.
#[macro_export]
macro_rules! impl_struct_builder {
($builder:ident) => {
fn set_lifecycle(mut self, lifecycle: Lifecycle) -> Self {
self.$builder = self.$builder.with_lifecycle(lifecycle);
self
}
fn map_error(mut self, f: impl FnOnce(String) -> String) -> Self {
self.$builder = self.$builder.map_error(f);
self
}
fn with_errors_from<U>(mut self, result: &DataResult<U>) -> Self {
self.$builder = self.$builder.with_errors_from(result);
self
}
fn build(self, prefix: Self::Value) -> DataResult<Self::Value> {
self.$builder
.clone()
.flat_map(|b| self.build_with_builder(b, prefix))
}
};
}
/// A macro to be placed inside an `impl` block of a struct implementing [`StringStructBuilder`].
///
/// Place this in a `impl StructBuilder for ...` block.
/// This automatically implements the methods to add key-value pairs to the builder.
#[macro_export]
macro_rules! impl_string_struct_builder {
(@internal $builder:ident) => {
fn add_string_key_value(mut self, key: &str, value: Self::Value) -> Self {
self.$builder = std::mem::take(&mut self.$builder).map(|r| self.append(key, value, r));
self
}
fn add_string_key_value_result(mut self, key: &str, value: DataResult<Self::Value>) -> Self {
self.$builder = std::mem::take(&mut self.$builder).apply_2_and_make_stable(|r, v| self.append(key, v, r), value);
self
}
};
// For constant ops
($builder:ident, $ops:ident) => {
impl_string_struct_builder!(@internal $builder);
fn add_key_value(mut self, key: Self::Value, value: Self::Value) -> Self {
self.$builder = $ops.get_string(&key).flat_map(
|s| std::mem::take(&mut self.$builder).map(|r| self.append(&s, value, r))
);
self
}
fn add_key_value_result(mut self, key: Self::Value, value: DataResult<Self::Value>) -> Self {
self.$builder = $ops.get_string(&key).flat_map(
|s| std::mem::take(&mut self.$builder).apply_2_and_make_stable(|r, v| self.append(&s, v, r), value)
);
self
}
fn add_key_result_value_result(
mut self,
key: DataResult<Self::Value>,
value: DataResult<Self::Value>,
) -> Self {
self.$builder = key.flat_map(|v| $ops.get_string(&v)).flat_map(|s| {
std::mem::take(&mut self.$builder).apply_2_and_make_stable(|r, v| self.append(&s, v, r), value)
});
self
}
};
// For stored ops
($builder:ident, self. $ops:ident) => {
impl_string_struct_builder!(@internal $builder);
fn add_key_value(mut self, key: Self::Value, value: Self::Value) -> Self {
self.$builder = self.$ops.get_string(&key).flat_map(
|s| std::mem::take(&mut self.$builder).map(|r| self.append(&s, value, r))
);
self
}
fn add_key_value_result(mut self, key: Self::Value, value: DataResult<Self::Value>) -> Self {
self.$builder = self.$ops.get_string(&key).flat_map(
|s| std::mem::take(&mut self.$builder).apply_2_and_make_stable(|r, v| self.append(&s, v, r), value)
);
self
}
fn add_key_result_value_result(
mut self,
key: DataResult<Self::Value>,
value: DataResult<Self::Value>,
) -> Self {
self.$builder = key.flat_map(|v| self.$ops.get_string(&v)).flat_map(|s| {
std::mem::take(&mut self.$builder).apply_2_and_make_stable(|r, v| self.append(&s, v, r), value)
});
self
}
};
}
/// A macro to be placed inside an `impl` block of a struct implementing `UniversalStructBuilder`.
///
/// Place this in a `impl StructBuilder for ...` block.
/// This automatically implements the methods to add key-value pairs to the builder.
#[macro_export]
macro_rules! impl_universal_struct_builder {
(@internal $builder:ident) => {
fn add_key_value(mut self, key: Self::Value, value: Self::Value) -> Self {
self.$builder = std::mem::take(&mut self.$builder).map(|b| self.append(key, value, b));
self
}
fn add_key_value_result(mut self, key: Self::Value, value: DataResult<Self::Value>) -> Self {
self.$builder = std::mem::take(&mut self.$builder)
.apply_2_and_make_stable(|b, v| self.append(key, v, b), value);
self
}
fn add_key_result_value_result(
mut self,
key: DataResult<Self::Value>,
value: DataResult<Self::Value>,
) -> Self {
self.$builder = self
.$builder
.clone()
.apply(key.apply_2_and_make_stable(|k, v| (|b| self.append(k, v, b)), value));
self
}
};
// For constant ops
($builder:ident, $ops:ident) => {
impl_universal_struct_builder!(@internal $builder);
fn add_string_key_value(self, key: &str, value: Self::Value) -> Self {
self.add_key_value($ops.create_string(key), value)
}
fn add_string_key_value_result(self, key: &str, value: DataResult<Self::Value>) -> Self {
self.add_key_value_result($ops.create_string(key), value)
}
};
// For stored ops
($builder:ident, self. $ops:ident) => {
impl_universal_struct_builder!(@internal $builder);
fn add_string_key_value(self, key: &str, value: Self::Value) -> Self {
let string = self.$ops.create_string(key);
self.add_key_value(string, value)
}
fn add_string_key_value_result(self, key: &str, value: DataResult<Self::Value>) -> Self {
let string = self.$ops.create_string(key);
self.add_key_value_result(string, value)
}
};
}
pub struct MapBuilder<T, O: DynamicOps<Value = T> + 'static> {
builder: DataResult<Vec<(T, T)>>,
ops: &'static O,
}
impl<T: Clone, O: DynamicOps<Value = T>> StructBuilder for MapBuilder<T, O> {
type Value = T;
impl_struct_builder!(builder);
impl_universal_struct_builder!(builder, self.ops);
}
impl<T: Clone, O: DynamicOps<Value = T>> ResultStructBuilder for MapBuilder<T, O> {
type Result = Vec<(T, T)>;
fn build_with_builder(
self,
builder: Self::Result,
prefix: Self::Value,
) -> DataResult<Self::Value> {
self.ops.merge_entries_into_map(prefix, builder)
}
}
impl<T: Clone, O: DynamicOps<Value = T>> UniversalStructBuilder for MapBuilder<T, O> {
fn append(
&self,
key: Self::Value,
value: Self::Value,
mut builder: Self::Result,
) -> Self::Result {
builder.push((key, value));
builder
}
}