nushell/src/object/dict.rs

94 lines
2.4 KiB
Rust
Raw Normal View History

2019-05-16 00:58:44 +02:00
use crate::prelude::*;
2019-05-24 21:35:22 +02:00
use crate::object::DataDescriptor;
2019-05-10 18:59:12 +02:00
use crate::object::{Primitive, Value};
use indexmap::IndexMap;
2019-05-28 04:01:37 +02:00
use serde::ser::{Serialize, Serializer, SerializeMap};
2019-05-17 17:55:50 +02:00
use std::cmp::{Ordering, PartialOrd};
2019-05-10 18:59:12 +02:00
2019-05-26 08:54:41 +02:00
#[derive(Debug, Default, Eq, PartialEq, Clone)]
2019-05-10 18:59:12 +02:00
pub struct Dictionary {
entries: IndexMap<DataDescriptor, Value>,
2019-05-10 18:59:12 +02:00
}
2019-05-28 04:01:37 +02:00
impl Serialize for Dictionary {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(self.entries.len()))?;
for (k, v) in &self.entries {
map.serialize_entry(&k, &v)?;
}
map.end()
}
}
2019-05-17 17:55:50 +02:00
impl PartialOrd for Dictionary {
// TODO: FIXME
fn partial_cmp(&self, _other: &Dictionary) -> Option<Ordering> {
Some(Ordering::Less)
}
}
impl Ord for Dictionary {
// TODO: FIXME
fn cmp(&self, _other: &Dictionary) -> Ordering {
Ordering::Less
}
}
impl PartialOrd<Value> for Dictionary {
fn partial_cmp(&self, _other: &Value) -> Option<Ordering> {
Some(Ordering::Less)
}
}
impl PartialEq<Value> for Dictionary {
// TODO: FIXME
fn eq(&self, other: &Value) -> bool {
match other {
Value::Object(d) => self == d,
_ => false,
}
}
}
2019-05-10 18:59:12 +02:00
impl Dictionary {
crate fn add(&mut self, name: impl Into<DataDescriptor>, value: Value) {
2019-05-10 18:59:12 +02:00
self.entries.insert(name.into(), value);
}
crate fn copy_dict(&self) -> Dictionary {
let mut out = Dictionary::default();
2019-05-10 18:59:12 +02:00
for (key, value) in self.entries.iter() {
out.add(key.copy(), value.copy());
2019-05-10 18:59:12 +02:00
}
out
2019-05-10 18:59:12 +02:00
}
2019-05-16 00:23:36 +02:00
crate fn data_descriptors(&self) -> Vec<DataDescriptor> {
self.entries.iter().map(|(name, _)| name.copy()).collect()
2019-05-10 18:59:12 +02:00
}
2019-05-16 00:23:36 +02:00
crate fn get_data(&'a self, desc: &DataDescriptor) -> MaybeOwned<'a, Value> {
match self.entries.get(desc) {
Some(v) => MaybeOwned::Borrowed(v),
2019-05-10 18:59:12 +02:00
None => MaybeOwned::Owned(Value::Primitive(Primitive::Nothing)),
}
}
2019-05-17 17:55:50 +02:00
crate fn get_data_by_key(&self, name: &str) -> MaybeOwned<'_, Value> {
match self
.entries
.iter()
.find(|(desc_name, _)| desc_name.name.is_string(name))
{
Some((_, v)) => MaybeOwned::Borrowed(v),
2019-05-17 17:55:50 +02:00
None => MaybeOwned::Owned(Value::Primitive(Primitive::Nothing)),
}
}
2019-05-10 18:59:12 +02:00
}