1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
use crate::Identifiable;

/// A Dex is used to hold types with an identifiable value (see [Identifiable]).
pub trait Dex<I: Identifiable> {
    /// Inserts a value to the Dex.
    fn insert(&mut self, v: I) -> Option<I>;

    /// Try to get an identifiable value from the Dex.
    fn try_get(&self, id: &I::Id) -> Option<&I>;

    /// Get the unknown value from the Dex.
    fn unknown(&self) -> &I;

    /// Get the identifiable value from the Dex, or return the unknown value.
    fn get(&self, id: &I::Id) -> &I {
        self.try_get(id).unwrap_or_else(|| self.unknown())
    }

    /// Get the length of the Dex.
    fn len(&self) -> usize;
}

#[cfg(feature = "dex_types")]
pub use defaults::BasicDex;

#[cfg(feature = "dex_types")]
mod defaults {

    use core::hash::Hash;

    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    use crate::Identifiable;

    use super::Dex;

    fn name<T: ?Sized>() -> &'static str {
        let name = core::any::type_name::<T>();
        name.split("::").last().unwrap_or(name)
    }

    /// Basic Dex implementation using hashbrown crate.
    #[repr(transparent)]
    #[derive(Debug, Clone)]
    pub struct BasicDex<I: Identifiable>(hashbrown::HashMap<I::Id, I>)
    where
        I::Id: Hash + Eq;

    impl<I: Identifiable> BasicDex<I>
    where
        I::Id: Hash + Eq,
    {
        pub fn new(inner: hashbrown::HashMap<I::Id, I>) -> Self {
            Self(inner)
        }
    }

    impl<I: Identifiable> Dex<I> for BasicDex<I>
    where
        I::Id: Hash + Eq,
    {
        fn insert(&mut self, v: I) -> Option<I> {
            self.0.insert(v.id().clone(), v)
        }

        fn try_get(&self, id: &I::Id) -> Option<&I> {
            self.0.get(id)
        }

        fn unknown<'a>(&'a self) -> &I {
            self.try_get(&I::UNKNOWN).unwrap_or_else(|| {
                panic!(
                    "Could not get unknown {} for \"{}\"",
                    name::<I>(),
                    name::<Self>()
                )
            })
        }

        fn len(&self) -> usize {
            self.0.len()
        }
    }

    impl<I: Identifiable> Default for BasicDex<I>
    where
        I::Id: Hash + Eq {
        fn default() -> Self {
            Self(Default::default())
        }
    }

    /// Serialize Dex as a Vec
    impl<I: Identifiable + Serialize> Serialize for BasicDex<I>
    where
        I::Id: Hash + Eq {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.collect_seq(self.0.values())
        }
    }

    /// Deserialize Dex from a Vec
    impl<'de, I: Identifiable + Deserialize<'de>> Deserialize<'de> for BasicDex<I>
    where
        I::Id: Hash + Eq {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            Vec::<I>::deserialize(deserializer)
                .map(|i| Self(i.into_iter().map(|i| (i.id().clone(), i)).collect()))
        }
    }
}