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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use crate::maybe_owned::MaybeOwned;
use crate::value::primitive::Primitive;
use crate::value::{UntaggedValue, Value};
use derive_new::new;
use getset::Getters;
use indexmap::IndexMap;
use nu_source::{DbgDocBldr, DebugDocBuilder, PrettyDebug, Spanned, SpannedItem, Tag};
use serde::{Deserialize, Serialize};
use std::cmp::{Ord, Ordering, PartialOrd};
use std::hash::{Hash, Hasher};

/// A dictionary that can hold a mapping from names to Values
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq, Clone, Getters, new)]
pub struct Dictionary {
    #[get = "pub"]
    pub entries: IndexMap<String, Value>,
}

#[allow(clippy::derive_hash_xor_eq)]
impl Hash for Dictionary {
    /// Create the hash function to allow the Hash trait for dictionaries
    fn hash<H: Hasher>(&self, state: &mut H) {
        let mut entries = self.entries.clone();
        entries.sort_keys();
        entries.keys().collect::<Vec<&String>>().hash(state);
        entries.values().collect::<Vec<&Value>>().hash(state);
    }
}

impl PartialOrd for Dictionary {
    /// Compare two dictionaries for sort ordering
    fn partial_cmp(&self, other: &Dictionary) -> Option<Ordering> {
        let this: Vec<&String> = self.entries.keys().collect();
        let that: Vec<&String> = other.entries.keys().collect();

        if this != that {
            return this.partial_cmp(&that);
        }

        let this: Vec<&Value> = self.entries.values().collect();
        let that: Vec<&Value> = self.entries.values().collect();

        this.partial_cmp(&that)
    }
}

impl Ord for Dictionary {
    /// Compare two dictionaries for ordering
    fn cmp(&self, other: &Dictionary) -> Ordering {
        let this: Vec<&String> = self.entries.keys().collect();
        let that: Vec<&String> = other.entries.keys().collect();

        if this != that {
            return this.cmp(&that);
        }

        let this: Vec<&Value> = self.entries.values().collect();
        let that: Vec<&Value> = self.entries.values().collect();

        this.cmp(&that)
    }
}

impl PartialEq<Value> for Dictionary {
    /// Test a dictionary against a Value for equality
    fn eq(&self, other: &Value) -> bool {
        matches!(&other.value, UntaggedValue::Row(d) if self == d)
    }
}

/// A key-value pair specifically meant to be used in debug and pretty-printing
#[derive(Debug, new)]
struct DebugEntry<'a> {
    key: &'a str,
    value: &'a Value,
}

impl<'a> PrettyDebug for DebugEntry<'a> {
    /// Build the the information to pretty-print the DebugEntry
    fn pretty(&self) -> DebugDocBuilder {
        (DbgDocBldr::key(self.key.to_string())
            + DbgDocBldr::equals()
            + self.value.pretty().into_value())
        .group()
    }
}

impl PrettyDebug for Dictionary {
    /// Get a Dictionary ready to be pretty-printed
    fn pretty(&self) -> DebugDocBuilder {
        DbgDocBldr::delimit(
            "(",
            DbgDocBldr::intersperse(
                self.entries()
                    .iter()
                    .map(|(key, value)| DebugEntry::new(key, value)),
                DbgDocBldr::space(),
            ),
            ")",
        )
    }
}

impl From<IndexMap<String, Value>> for Dictionary {
    /// Create a dictionary from a map of strings to Values
    fn from(input: IndexMap<String, Value>) -> Dictionary {
        let mut out = IndexMap::default();

        for (key, value) in input {
            out.insert(key, value);
        }

        Dictionary::new(out)
    }
}

impl Dictionary {
    /// Find the matching Value for a given key, if possible. If not, return a Primitive::Nothing
    pub fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value> {
        match self.entries.get(desc) {
            Some(v) => MaybeOwned::Borrowed(v),
            None => MaybeOwned::Owned(
                UntaggedValue::Primitive(Primitive::Nothing).into_untagged_value(),
            ),
        }
    }

    pub fn insert(&mut self, key: String, value: Value) -> Option<Value> {
        self.entries.insert_full(key, value).1
    }

    pub fn merge_from(&self, other: &Dictionary) -> Dictionary {
        let mut obj = self.clone();

        for column in other.keys() {
            let key = column.clone();
            let value_key = key.as_str();
            let value_spanned_key = value_key.spanned_unknown();

            let other_column = match other.get_data_by_key(value_spanned_key) {
                Some(value) => value,
                None => UntaggedValue::Primitive(Primitive::Nothing).into_untagged_value(),
            };

            obj.entries.insert(key, other_column);
        }

        obj
    }

    /// Iterate the keys in the Dictionary
    pub fn keys(&self) -> impl Iterator<Item = &String> {
        self.entries.keys()
    }

    /// Iterate the values in the Dictionary
    pub fn values(&self) -> impl Iterator<Item = &Value> {
        self.entries.values()
    }

    /// Checks if given key exists
    pub fn contains_key(&self, key: &str) -> bool {
        self.entries.contains_key(key)
    }

    /// Find the matching Value for a key, if possible
    pub fn get_data_by_key(&self, name: Spanned<&str>) -> Option<Value> {
        let result = self
            .entries
            .iter()
            .find(|(desc_name, _)| *desc_name == name.item)?
            .1;

        Some(
            result
                .value
                .clone()
                .into_value(Tag::new(result.tag.anchor(), name.span)),
        )
    }

    /// Get a mutable entry that matches a key, if possible
    pub fn get_mut_data_by_key(&mut self, name: &str) -> Option<&mut Value> {
        match self
            .entries
            .iter_mut()
            .find(|(desc_name, _)| *desc_name == name)
        {
            Some((_, v)) => Some(v),
            None => None,
        }
    }

    /// Insert a new key/value pair into the dictionary
    pub fn insert_data_at_key(&mut self, name: &str, value: Value) {
        self.entries.insert(name.to_string(), value);
    }

    /// Return size of dictionary
    pub fn length(&self) -> usize {
        self.entries.len()
    }
}

/// A helper to help create dictionaries for you. It has the ability to insert values into the dictionary while maintaining the tags that need to be applied to the individual members
#[derive(Debug, Clone)]
pub struct TaggedDictBuilder {
    tag: Tag,
    dict: IndexMap<String, Value>,
}

impl TaggedDictBuilder {
    /// Create a new builder
    pub fn new(tag: impl Into<Tag>) -> TaggedDictBuilder {
        TaggedDictBuilder {
            tag: tag.into(),
            dict: IndexMap::default(),
        }
    }

    /// Build the contents of the builder into a Value
    pub fn build(tag: impl Into<Tag>, block: impl FnOnce(&mut TaggedDictBuilder)) -> Value {
        let mut builder = TaggedDictBuilder::new(tag);
        block(&mut builder);
        builder.into_value()
    }

    /// Create a new builder with a pre-defined capacity
    pub fn with_capacity(tag: impl Into<Tag>, n: usize) -> TaggedDictBuilder {
        TaggedDictBuilder {
            tag: tag.into(),
            dict: IndexMap::with_capacity(n),
        }
    }

    /// Insert an untagged key/value pair into the dictionary, to later be tagged when built
    pub fn insert_untagged(&mut self, key: impl Into<String>, value: impl Into<UntaggedValue>) {
        self.dict
            .insert(key.into(), value.into().into_value(&self.tag));
    }

    ///  Insert a key/value pair into the dictionary
    pub fn insert_value(&mut self, key: impl Into<String>, value: impl Into<Value>) {
        self.dict.insert(key.into(), value.into());
    }

    /// Convert the dictionary into a tagged Value using the original tag
    pub fn into_value(self) -> Value {
        let tag = self.tag.clone();
        self.into_untagged_value().into_value(tag)
    }

    /// Convert the dictionary into an UntaggedValue
    pub fn into_untagged_value(self) -> UntaggedValue {
        UntaggedValue::Row(Dictionary { entries: self.dict })
    }

    /// Returns true if the dictionary is empty, false otherwise
    pub fn is_empty(&self) -> bool {
        self.dict.is_empty()
    }

    /// Checks if given key exists
    pub fn contains_key(&self, key: &str) -> bool {
        self.dict.contains_key(key)
    }
}

impl From<TaggedDictBuilder> for Value {
    /// Convert a builder into a tagged Value
    fn from(input: TaggedDictBuilder) -> Value {
        input.into_value()
    }
}