gc_value 0.1.0

Generic value type, capturing the data model of common formats such as JSON, YAML and CBOR, based on Arc for cheap cloning.
Documentation
//! I provide [`Serialize`] and [`Deserialize`] impl for [`GcValue`].
//!
//! Note that [`GcValue::Tag`] has no portable equivalent in the data model assumed by
//! [`serde`], so attempting to serialize a [`GcValue::Tag`] will fail
//! (deserialization is unaffected, as no format produces a "tag" out of thin
//! air).

use std::fmt;

use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};

use crate::GcValue;

impl Serialize for GcValue {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            GcValue::Text(t) => serializer.serialize_str(t),
            GcValue::Int(i) => serializer.serialize_i128(*i),
            GcValue::Float(f) => serializer.serialize_f64(*f),
            GcValue::Boolean(b) => serializer.serialize_bool(*b),
            GcValue::Array(items) => {
                let mut seq = serializer.serialize_seq(Some(items.len()))?;
                for item in items.iter() {
                    seq.serialize_element(item)?;
                }
                seq.end()
            }
            GcValue::Map(map) => {
                let mut ser_map = serializer.serialize_map(Some(map.len()))?;
                for (k, v) in map.iter() {
                    ser_map.serialize_entry(k, v)?;
                }
                ser_map.end()
            }
            GcValue::Tag(_) => Err(<S::Error as serde::ser::Error>::custom(
                "GcValue::Tag has no equivalent in serde's data model, and cannot be serialized",
            )),
            GcValue::Bytes(b) => serializer.serialize_bytes(b),
            GcValue::Null => serializer.serialize_unit(),
        }
    }
}

struct GcValueVisitor;

impl<'de> Visitor<'de> for GcValueVisitor {
    type Value = GcValue;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a value representable as a GcValue")
    }

    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> {
        Ok(GcValue::Boolean(v))
    }

    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> {
        Ok(GcValue::Int(v.into()))
    }

    fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E> {
        Ok(GcValue::Int(v))
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> {
        Ok(GcValue::Int(v.into()))
    }

    fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        i128::try_from(v)
            .map(GcValue::Int)
            .map_err(|_| de::Error::custom("integer too large to fit in a GcValue::Int (i128)"))
    }

    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> {
        Ok(GcValue::Float(v))
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> {
        Ok(GcValue::new_text(v))
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E> {
        Ok(GcValue::new_text(v))
    }

    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> {
        Ok(GcValue::new_bytes(v.to_vec()))
    }

    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> {
        Ok(GcValue::new_bytes(v))
    }

    fn visit_none<E>(self) -> Result<Self::Value, E> {
        Ok(GcValue::Null)
    }

    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        Deserialize::deserialize(deserializer)
    }

    fn visit_unit<E>(self) -> Result<Self::Value, E> {
        Ok(GcValue::Null)
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        let mut items: Vec<GcValue> = Vec::with_capacity(seq.size_hint().unwrap_or(0));
        while let Some(item) = seq.next_element()? {
            items.push(item);
        }
        Ok(GcValue::new_array(items))
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut pairs: Vec<(GcValue, GcValue)> = Vec::with_capacity(map.size_hint().unwrap_or(0));
        while let Some(entry) = map.next_entry()? {
            pairs.push(entry);
        }
        Ok(GcValue::collect_map(pairs))
    }
}

impl<'de> Deserialize<'de> for GcValue {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(GcValueVisitor)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn roundtrip(v: GcValue) {
        let cbor = serde_cbor::to_vec(&v).unwrap();
        let back: GcValue = serde_cbor::from_slice(&cbor).unwrap();
        assert_eq!(v, back);
    }

    #[test]
    fn text() {
        roundtrip(GcValue::new_text("hello"));
    }

    #[test]
    fn int() {
        roundtrip(GcValue::new_int(42i64));
        roundtrip(GcValue::new_int(-42i64));
    }

    #[test]
    fn float() {
        roundtrip(GcValue::new_float(1.5));
    }

    #[test]
    fn boolean() {
        roundtrip(GcValue::new_boolean(true));
        roundtrip(GcValue::new_boolean(false));
    }

    #[test]
    fn array() {
        roundtrip(GcValue::collect_array([1, 2, 3]));
    }

    #[test]
    fn map() {
        roundtrip(GcValue::collect_map([("a", 1), ("b", 2)]));
    }

    #[test]
    fn bytes() {
        roundtrip(GcValue::collect_bytes("abcd".bytes()));
    }

    #[test]
    fn null() {
        roundtrip(GcValue::new_null());
    }

    #[test]
    fn tag_fails_to_serialize() {
        let tag = GcValue::collect_tag("a-tag", 1);
        assert!(serde_cbor::to_vec(&tag).is_err());
    }
}