alloy_serde/other/
arbitrary_.rs

1use crate::OtherFields;
2use alloc::{collections::BTreeMap, string::String, vec::Vec};
3
4impl arbitrary::Arbitrary<'_> for OtherFields {
5    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
6        let mut inner = BTreeMap::new();
7        for _ in 0usize..u.int_in_range(0usize..=15)? {
8            inner.insert(u.arbitrary()?, u.arbitrary::<ArbitraryValue>()?.into_json_value());
9        }
10        Ok(Self { inner })
11    }
12}
13
14/// Redefinition of `serde_json::Value` for the purpose of implementing `Arbitrary`.
15#[derive(Clone, Debug, arbitrary::Arbitrary)]
16enum ArbitraryValue {
17    Null,
18    Bool(bool),
19    Number(u64),
20    String(String),
21    Array(Vec<ArbitraryValue>),
22    Object(BTreeMap<String, ArbitraryValue>),
23}
24
25impl ArbitraryValue {
26    fn into_json_value(self) -> serde_json::Value {
27        match self {
28            Self::Null => serde_json::Value::Null,
29            Self::Bool(b) => serde_json::Value::Bool(b),
30            Self::Number(n) => serde_json::Value::Number(n.into()),
31            Self::String(s) => serde_json::Value::String(s),
32            Self::Array(a) => {
33                serde_json::Value::Array(a.into_iter().map(Self::into_json_value).collect())
34            }
35            Self::Object(o) => serde_json::Value::Object(
36                o.into_iter().map(|(k, v)| (k, v.into_json_value())).collect(),
37            ),
38        }
39    }
40}