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 define the type [`Map`]

use std::sync::Arc;

use crate::GcValue;

/// Internal representation of [`GcValue::Map`],
/// representing an order map where keys and values are [`GcValue`].
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Map {
    pairs: Vec<(GcValue, GcValue)>,
}

impl Map {
    /// Construct an empty map wrapped in an [`Arc`].
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// The number of pairs in this map
    pub fn len(&self) -> usize {
        self.pairs.len()
    }

    /// Whether this map is empty
    pub fn is_empty(&self) -> bool {
        self.pairs.is_empty()
    }

    /// Iter over the (key, value) pairs of this map.
    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
        self.into_iter()
    }

    /// Iter over the keys of this map
    pub fn keys(&self) -> impl Iterator<Item = &GcValue> {
        self.into_iter().map(|(k, _)| k)
    }

    /// Iter over the values of this map
    pub fn values(&self) -> impl Iterator<Item = &GcValue> {
        self.into_iter().map(|(_, v)| v)
    }

    /// Get the value associated to the given key, if any
    pub fn get<K>(&self, key: &K) -> Option<&GcValue>
    where
        K: ?Sized,
        GcValue: PartialEq<K>,
    {
        self.pairs.iter().find(|(k, _)| k.eq(key)).map(|(_, v)| v)
    }

    /// Produce a new [`Map`] with the same content as `self`,
    /// but where `k` is now associated with `v`.
    pub fn with<K, V>(self: &Arc<Self>, key: K, val: V) -> Arc<Self>
    where
        GcValue: From<K> + From<V> + PartialEq<K> + PartialEq<V>,
    {
        if let Some((i, (_, v))) = self.pairs.iter().enumerate().find(|(_, (k, _))| k == &key) {
            if v == &val {
                self.clone()
            } else {
                let mut pairs = self.pairs.clone();
                pairs[i].1 = val.into();
                Arc::new(Self { pairs })
            }
        } else {
            let mut pairs = self.pairs.clone();
            insort(&mut pairs, (key.into(), val.into()));
            Arc::new(Self { pairs })
        }
    }

    /// Produce a new [`Map`] with the same content as `self`,
    /// where `k` is not associated to any value.
    pub fn without<K>(self: &Arc<Self>, key: K) -> Arc<Self>
    where
        GcValue: PartialEq<K>,
    {
        if let Some(i) = self.pairs.iter().position(|(k, _)| k == &key) {
            let mut pairs = self.pairs.clone();
            pairs[i..].rotate_left(1);
            pairs.pop();
            debug_assert!(is_sorted(&pairs));
            Arc::new(Self { pairs })
        } else {
            self.clone()
        }
    }
}

impl<K, V> FromIterator<(K, V)> for Map
where
    GcValue: From<K> + From<V>,
{
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut pairs: Vec<(GcValue, GcValue)> = iter
            .into_iter()
            .map(|(k, v)| (k.into(), v.into()))
            .collect();
        pairs.sort_unstable_by(|p1, p2| p1.0.cmp(&p2.0));
        debug_assert!(is_sorted(&pairs));
        Self { pairs }
    }
}

impl IntoIterator for Map {
    type Item = (GcValue, GcValue);

    type IntoIter = std::vec::IntoIter<(GcValue, GcValue)>;

    fn into_iter(self) -> Self::IntoIter {
        self.pairs.into_iter()
    }
}

impl<'a> IntoIterator for &'a Map {
    type Item = &'a (GcValue, GcValue);

    type IntoIter = std::slice::Iter<'a, (GcValue, GcValue)>;

    fn into_iter(self) -> Self::IntoIter {
        self.pairs.iter()
    }
}

fn insort(a: &mut Vec<(GcValue, GcValue)>, (k, v): (GcValue, GcValue)) {
    a.push((k, v));
    let k1 = &a[a.len() - 1].0;
    if let Some(i) = a.iter().position(|(k2, _)| k2 > k1) {
        a[i..].rotate_right(1);
    }
    debug_assert!(is_sorted(a));
}

fn is_sorted(a: &[(GcValue, GcValue)]) -> bool {
    for i in 1..a.len() {
        if a[i - 1].0 >= a[i].0 {
            return false;
        }
    }
    true
}

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

    #[test]
    fn empty() {
        let m = Map::new();
        dbg!(&m.pairs);
        assert!(m.is_empty());
        assert!(is_sorted(&m.pairs));
    }

    #[test]
    fn one() {
        let m = Map::new().with(1, 2);
        assert_eq!(m.len(), 1);
        assert!(is_sorted(&m.pairs));
    }

    #[test]
    fn one_with_override() {
        let m = Map::new().with(1, 2).with(1, 3);
        assert_eq!(m.len(), 1);
        assert!(is_sorted(&m.pairs));
        assert_eq!(m.get(&1), Some(&3.into()));
        assert!(m.get(&3).is_none())
    }

    #[test]
    fn one_with_duplicate() {
        let m = Map::new().with(1, 2).with(1, 2);
        assert_eq!(m.len(), 1);
        assert!(is_sorted(&m.pairs));
        assert_eq!(m.get(&1), Some(&2.into()));
        assert!(m.get(&2).is_none())
    }

    #[test]
    fn two() {
        let m = Map::new().with(3, 4).with(1, 2);
        assert_eq!(m.len(), 2);
        assert!(is_sorted(&m.pairs));
        assert_eq!(m.get(&1), Some(&2.into()));
        assert_eq!(m.get(&3), Some(&4.into()));
        assert!(m.get(&2).is_none())
    }

    #[test]
    fn one_with_removal() {
        let m = Map::new()
            .with(3, 4)
            .with(1, 2)
            .without(3)
            .without(2)
            .without(2);
        assert_eq!(m.len(), 1);
        assert!(is_sorted(&m.pairs));
        assert_eq!(m.get(&1), Some(&2.into()));
        assert!(m.get(&3).is_none())
    }
}