use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::Typwire;
#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Debug)]
#[serde(transparent)]
pub struct Dictionary<T>(BTreeMap<String, T>);
impl<T> Dictionary<T> {
pub const fn new(entries: BTreeMap<String, T>) -> Self {
Self(entries)
}
pub fn into_inner(self) -> BTreeMap<String, T> {
self.0
}
}
impl<T: Typwire> Typwire for Dictionary<T> {}
impl<T> From<BTreeMap<String, T>> for Dictionary<T> {
fn from(value: BTreeMap<String, T>) -> Self {
Self::new(value)
}
}
impl<T> From<Dictionary<T>> for BTreeMap<String, T> {
fn from(value: Dictionary<T>) -> Self {
value.into_inner()
}
}
impl<T> std::ops::Deref for Dictionary<T> {
type Target = BTreeMap<String, T>;
fn deref(&self) -> &BTreeMap<String, T> {
&self.0
}
}
impl<T> std::ops::DerefMut for Dictionary<T> {
fn deref_mut(&mut self) -> &mut BTreeMap<String, T> {
&mut self.0
}
}
#[cfg(test)]
mod tests {
use crate::{decode, encode};
use super::*;
#[test]
fn wire_shape_is_identical_to_a_bare_btree_map() {
let value = Dictionary::new(BTreeMap::from([("a".to_owned(), 1_i64)]));
let raw = BTreeMap::from([("a".to_owned(), 1_i64)]);
assert_eq!(encode(&value).unwrap(), encode(&raw).unwrap());
assert_eq!(
decode::<BTreeMap<String, i64>>(&encode(&value).unwrap()).unwrap(),
raw
);
assert_eq!(
decode::<Dictionary<i64>>(&encode(&raw).unwrap()).unwrap(),
value
);
}
}