use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::ops::Index as OpsIndex;
use indexmap::IndexMap;
use crate::value::{NULL_VALUE, Value};
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Mapping {
map: IndexMap<Value, Value>,
}
pub trait Index: private::Sealed {
#[doc(hidden)]
fn contains_key(&self, mapping: &Mapping) -> bool;
#[doc(hidden)]
fn get<'a>(&self, mapping: &'a Mapping) -> Option<&'a Value>;
#[doc(hidden)]
fn get_mut<'a>(&self, mapping: &'a mut Mapping) -> Option<&'a mut Value>;
#[doc(hidden)]
fn swap_remove(&self, mapping: &mut Mapping) -> Option<Value>;
#[doc(hidden)]
fn shift_remove(&self, mapping: &mut Mapping) -> Option<Value>;
}
impl Mapping {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
map: IndexMap::with_capacity(capacity),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.map.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn clear(&mut self) {
self.map.clear();
}
pub fn insert(&mut self, key: Value, value: Value) -> Option<Value> {
self.map.insert(key, value)
}
pub fn entry(&mut self, key: Value) -> Entry<'_> {
Entry {
inner: self.map.entry(key),
}
}
#[must_use]
pub fn get<I: Index>(&self, key: I) -> Option<&Value> {
Index::get(&key, self)
}
#[must_use]
pub fn get_str(&self, key: &str) -> Option<&Value> {
self.map.get(&Value::String(key.to_owned()))
}
#[must_use]
pub fn get_mut<I: Index>(&mut self, key: I) -> Option<&mut Value> {
Index::get_mut(&key, self)
}
#[must_use]
pub fn get_str_mut(&mut self, key: &str) -> Option<&mut Value> {
self.map.get_mut(&Value::String(key.to_owned()))
}
#[must_use]
pub fn contains_key<I: Index>(&self, key: I) -> bool {
Index::contains_key(&key, self)
}
pub fn remove<I: Index>(&mut self, key: I) -> Option<Value> {
Index::swap_remove(&key, self)
}
pub fn shift_remove<I: Index>(&mut self, key: I) -> Option<Value> {
Index::shift_remove(&key, self)
}
pub fn iter(&self) -> impl Iterator<Item = (&Value, &Value)> + '_ {
self.map.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Value, &mut Value)> + '_ {
self.map.iter_mut()
}
pub fn keys(&self) -> impl Iterator<Item = &Value> + '_ {
self.map.keys()
}
pub fn values(&self) -> impl Iterator<Item = &Value> + '_ {
self.map.values()
}
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut Value> + '_ {
self.map.values_mut()
}
#[must_use]
pub fn get_index(&self, index: usize) -> Option<(&Value, &Value)> {
self.map.get_index(index)
}
}
pub struct Entry<'a> {
inner: indexmap::map::Entry<'a, Value, Value>,
}
impl<'a> Entry<'a> {
pub fn or_insert(self, default: Value) -> &'a mut Value {
self.inner.or_insert(default)
}
pub fn or_insert_with<F: FnOnce() -> Value>(self, default: F) -> &'a mut Value {
self.inner.or_insert_with(default)
}
pub fn and_modify<F: FnOnce(&mut Value)>(mut self, f: F) -> Self {
if let indexmap::map::Entry::Occupied(entry) = &mut self.inner {
f(entry.get_mut());
}
self
}
}
impl std::fmt::Debug for Mapping {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Mapping ")?;
formatter.debug_map().entries(self.map.iter()).finish()
}
}
impl Hash for Mapping {
fn hash<H: Hasher>(&self, state: &mut H) {
let mut xor = 0_u64;
for (key, value) in &self.map {
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
value.hash(&mut hasher);
xor ^= hasher.finish();
}
xor.hash(state);
}
}
impl OpsIndex<&str> for Mapping {
type Output = Value;
fn index(&self, index: &str) -> &Self::Output {
self.get_str(index).unwrap_or(&NULL_VALUE)
}
}
impl OpsIndex<String> for Mapping {
type Output = Value;
fn index(&self, index: String) -> &Self::Output {
self.get_str(&index).unwrap_or(&NULL_VALUE)
}
}
impl OpsIndex<&String> for Mapping {
type Output = Value;
fn index(&self, index: &String) -> &Self::Output {
self.get_str(index).unwrap_or(&NULL_VALUE)
}
}
impl OpsIndex<&Value> for Mapping {
type Output = Value;
fn index(&self, index: &Value) -> &Self::Output {
self.get(index).unwrap_or(&NULL_VALUE)
}
}
mod private {
pub trait Sealed {}
}
impl private::Sealed for Value {}
impl Index for Value {
fn contains_key(&self, mapping: &Mapping) -> bool {
mapping.map.contains_key(self)
}
fn get<'a>(&self, mapping: &'a Mapping) -> Option<&'a Value> {
mapping.map.get(self)
}
fn get_mut<'a>(&self, mapping: &'a mut Mapping) -> Option<&'a mut Value> {
mapping.map.get_mut(self)
}
fn swap_remove(&self, mapping: &mut Mapping) -> Option<Value> {
mapping.map.swap_remove(self)
}
fn shift_remove(&self, mapping: &mut Mapping) -> Option<Value> {
mapping.map.shift_remove(self)
}
}
impl private::Sealed for str {}
impl Index for str {
fn contains_key(&self, mapping: &Mapping) -> bool {
mapping.map.contains_key(&Value::String(self.to_owned()))
}
fn get<'a>(&self, mapping: &'a Mapping) -> Option<&'a Value> {
mapping.map.get(&Value::String(self.to_owned()))
}
fn get_mut<'a>(&self, mapping: &'a mut Mapping) -> Option<&'a mut Value> {
mapping.map.get_mut(&Value::String(self.to_owned()))
}
fn swap_remove(&self, mapping: &mut Mapping) -> Option<Value> {
mapping.map.swap_remove(&Value::String(self.to_owned()))
}
fn shift_remove(&self, mapping: &mut Mapping) -> Option<Value> {
mapping.map.shift_remove(&Value::String(self.to_owned()))
}
}
impl private::Sealed for String {}
impl Index for String {
fn contains_key(&self, mapping: &Mapping) -> bool {
<str as Index>::contains_key(self.as_str(), mapping)
}
fn get<'a>(&self, mapping: &'a Mapping) -> Option<&'a Value> {
<str as Index>::get(self.as_str(), mapping)
}
fn get_mut<'a>(&self, mapping: &'a mut Mapping) -> Option<&'a mut Value> {
<str as Index>::get_mut(self.as_str(), mapping)
}
fn swap_remove(&self, mapping: &mut Mapping) -> Option<Value> {
<str as Index>::swap_remove(self.as_str(), mapping)
}
fn shift_remove(&self, mapping: &mut Mapping) -> Option<Value> {
<str as Index>::shift_remove(self.as_str(), mapping)
}
}
impl<T> private::Sealed for &T where T: ?Sized + Index {}
impl<T> Index for &T
where
T: ?Sized + Index,
{
fn contains_key(&self, mapping: &Mapping) -> bool {
T::contains_key(*self, mapping)
}
fn get<'a>(&self, mapping: &'a Mapping) -> Option<&'a Value> {
T::get(*self, mapping)
}
fn get_mut<'a>(&self, mapping: &'a mut Mapping) -> Option<&'a mut Value> {
T::get_mut(*self, mapping)
}
fn swap_remove(&self, mapping: &mut Mapping) -> Option<Value> {
T::swap_remove(*self, mapping)
}
fn shift_remove(&self, mapping: &mut Mapping) -> Option<Value> {
T::shift_remove(*self, mapping)
}
}
impl FromIterator<(Value, Value)> for Mapping {
fn from_iter<T: IntoIterator<Item = (Value, Value)>>(iter: T) -> Self {
Self {
map: iter.into_iter().collect(),
}
}
}
impl Extend<(Value, Value)> for Mapping {
fn extend<T: IntoIterator<Item = (Value, Value)>>(&mut self, iter: T) {
self.map.extend(iter);
}
}
impl IntoIterator for Mapping {
type Item = (Value, Value);
type IntoIter = indexmap::map::IntoIter<Value, Value>;
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a> IntoIterator for &'a Mapping {
type Item = (&'a Value, &'a Value);
type IntoIter = indexmap::map::Iter<'a, Value, Value>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<'a> IntoIterator for &'a mut Mapping {
type Item = (&'a Value, &'a mut Value);
type IntoIter = indexmap::map::IterMut<'a, Value, Value>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter_mut()
}
}
#[cfg(test)]
mod tests {
use super::Mapping;
use crate::value::Value;
fn key(name: &str) -> Value {
Value::String(name.to_owned())
}
#[test]
fn insertion_order_is_preserved() {
let mut map = Mapping::new();
map.insert(key("a"), Value::from(1_u64));
map.insert(key("b"), Value::from(2_u64));
map.insert(key("c"), Value::from(3_u64));
let keys: Vec<_> = map.keys().cloned().collect();
assert_eq!(keys, vec![key("a"), key("b"), key("c")]);
}
#[test]
fn replacement_does_not_move_the_key() {
let mut map = Mapping::new();
map.insert(key("a"), Value::from(1_u64));
map.insert(key("b"), Value::from(2_u64));
assert_eq!(
map.insert(key("a"), Value::from(3_u64)),
Some(Value::from(1_u64))
);
let keys: Vec<_> = map.keys().cloned().collect();
assert_eq!(keys, vec![key("a"), key("b")]);
}
#[test]
fn remove_uses_swap_remove() {
let mut map = Mapping::new();
for name in ["a", "b", "c", "d"] {
map.insert(key(name), Value::from(name.len() as u64));
}
map.remove(key("b"));
let keys: Vec<_> = map.keys().cloned().collect();
assert_eq!(keys, vec![key("a"), key("d"), key("c")]);
}
#[test]
fn shift_remove_preserves_order() {
let mut map = Mapping::new();
for name in ["a", "b", "c"] {
map.insert(key(name), Value::Null);
}
map.shift_remove(key("b"));
let keys: Vec<_> = map.keys().cloned().collect();
assert_eq!(keys, vec![key("a"), key("c")]);
}
#[test]
fn mapping_equality_and_hash_are_order_insensitive() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut left = Mapping::new();
left.insert(key("a"), Value::from(1_u64));
left.insert(key("b"), Value::from(2_u64));
let mut right = Mapping::new();
right.insert(key("b"), Value::from(2_u64));
right.insert(key("a"), Value::from(1_u64));
assert_eq!(left, right);
let mut left_hash = DefaultHasher::new();
let mut right_hash = DefaultHasher::new();
left.hash(&mut left_hash);
right.hash(&mut right_hash);
assert_eq!(left_hash.finish(), right_hash.finish());
}
#[test]
fn entry_inserts_lazily_and_mutates_existing() {
let mut map = Mapping::new();
map.entry(key("a")).or_insert(Value::from(1_u64));
map.entry(key("a"))
.and_modify(|value| *value = Value::from(2_u64));
map.entry(key("b")).or_insert_with(|| Value::from(3_u64));
assert_eq!(map.get("a"), Some(&Value::from(2_u64)));
assert_eq!(map.get("b"), Some(&Value::from(3_u64)));
}
#[test]
fn debug_matches_yaml_serde_shape() {
assert_eq!(format!("{:?}", Mapping::new()), "Mapping {}");
let mut map = Mapping::new();
map.insert(key("a"), Value::from(1_u64));
assert_eq!(
format!("{map:?}"),
"Mapping {String(\"a\"): Number(Number(PosInt(1)))}"
);
}
#[test]
fn missing_index_is_null() {
let map = Mapping::new();
assert_eq!(map["missing"], Value::Null);
}
}