esexpr/codecs/
mod.rs

1mod boxed;
2mod btreemap;
3#[cfg(feature = "std")]
4mod hashmap;
5mod option;
6mod scalar;
7mod vec;
8
9use alloc::collections::{BTreeMap, VecDeque};
10use alloc::vec::Vec;
11
12use crate::cowstr::CowStr;
13use crate::{DecodeError, ESExpr, ESExprTagSet};
14
15/// Equality for the encoded ESExpr representation.
16pub trait ESExprEncodedEq {
17	/// Determines whether two values are equal when encoded as `ESExpr`.
18	fn is_encoded_eq(&self, other: &Self) -> bool;
19}
20
21/// A codec that encodes and decodes `ESExpr` values.
22pub trait ESExprCodec<'a>: ESExprEncodedEq + Sized + 'a {
23	/// The tags of the encoded expressions that this type can produce.
24	const TAGS: ESExprTagSet;
25
26	/// Encode this value into an expression.
27	fn encode_esexpr(&'a self) -> ESExpr<'a>;
28
29	/// Decode an expression into a value.
30	///
31	/// # Errors
32	/// Will return `Err` if decoding fails.
33	fn decode_esexpr(expr: ESExpr<'a>) -> Result<Self, DecodeError>;
34}
35
36/// A field codec for optional fields.
37pub trait ESExprOptionalFieldCodec<'a>: ESExprEncodedEq + Sized + 'a {
38	/// The element type.
39	type Element: ESExprCodec<'a> + 'a;
40
41	/// Encode an optional field or None when the value should be excluded.
42	fn encode_optional_field(&'a self) -> Option<ESExpr<'a>>;
43
44	/// Decode an optional field value.
45	///
46	/// # Errors
47	/// Will return `Err` if decoding fails.
48	fn decode_optional_field(value: Option<ESExpr<'a>>) -> Result<Self, DecodeError>;
49}
50
51/// A field codec for variable arguments.
52pub trait ESExprVarArgCodec<'a>: ESExprEncodedEq + Sized + 'a {
53	/// The element type.
54	type Element: ESExprCodec<'a> + 'a;
55
56	/// Encode variable arguments
57	fn encode_vararg_element(&'a self, args: &mut Vec<ESExpr<'a>>);
58
59	/// Decode variable arguments.
60	///
61	/// # Errors
62	/// Will return `Err` if decoding fails.
63	fn decode_vararg_element(
64		args: &mut VecDeque<ESExpr<'a>>,
65		constructor_name: &str,
66		start_index: &mut usize,
67	) -> Result<Self, DecodeError>;
68}
69
70/// A field codec for dictionary arguments.
71pub trait ESExprDictCodec<'a>
72where
73	Self: Sized + 'a,
74{
75	/// The element type.
76	type Element: ESExprCodec<'a> + 'a;
77
78	/// Encode dictionary arguments.
79	fn encode_dict_element(&'a self, kwargs: &mut BTreeMap<CowStr<'a>, ESExpr<'a>>);
80
81	/// Decode dictionary arguments.
82	///
83	/// # Errors
84	/// Will return `Err` if decoding fails.
85	fn decode_dict_element(
86		kwargs: &mut BTreeMap<CowStr<'a>, ESExpr<'a>>,
87		constructor_name: &str,
88	) -> Result<Self, DecodeError>;
89}