ayaml 0.1.0

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, and emitter
Documentation
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! An insertion-ordered YAML mapping backed by `indexmap`.

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};

/// A YAML mapping with insertion-order iteration and swap-remove semantics.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Mapping {
    map: IndexMap<Value, Value>,
}

/// A borrowed or owned key accepted by [`Mapping`] lookup operations.
///
/// This is sealed by the set of implementations below: YAML keys may be full
/// [`Value`]s, while string keys are the common ergonomic case. References to
/// either form are accepted without forcing callers to match one ownership
/// convention.
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 {
    /// Create an empty mapping.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create an empty mapping with capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            map: IndexMap::with_capacity(capacity),
        }
    }

    /// Number of entries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Whether the mapping is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Remove all entries.
    pub fn clear(&mut self) {
        self.map.clear();
    }

    /// Insert or replace a value, returning the previous value.
    pub fn insert(&mut self, key: Value, value: Value) -> Option<Value> {
        self.map.insert(key, value)
    }

    /// Get a mutable entry for `key`, inserting lazily through [`Entry`].
    pub fn entry(&mut self, key: Value) -> Entry<'_> {
        Entry {
            inner: self.map.entry(key),
        }
    }

    /// Look up a value by key.
    #[must_use]
    pub fn get<I: Index>(&self, key: I) -> Option<&Value> {
        Index::get(&key, self)
    }

    /// Look up a value by string key.
    #[must_use]
    pub fn get_str(&self, key: &str) -> Option<&Value> {
        self.map.get(&Value::String(key.to_owned()))
    }

    /// Mutably look up a value by key.
    #[must_use]
    pub fn get_mut<I: Index>(&mut self, key: I) -> Option<&mut Value> {
        Index::get_mut(&key, self)
    }

    /// Mutably look up a value by string key.
    #[must_use]
    pub fn get_str_mut(&mut self, key: &str) -> Option<&mut Value> {
        self.map.get_mut(&Value::String(key.to_owned()))
    }

    /// Whether the mapping contains a key.
    #[must_use]
    pub fn contains_key<I: Index>(&self, key: I) -> bool {
        Index::contains_key(&key, self)
    }

    /// Remove a key, swapping the last entry into its place.
    pub fn remove<I: Index>(&mut self, key: I) -> Option<Value> {
        Index::swap_remove(&key, self)
    }

    /// Remove a key, preserving the relative order of the remaining entries.
    pub fn shift_remove<I: Index>(&mut self, key: I) -> Option<Value> {
        Index::shift_remove(&key, self)
    }

    /// Iterate over entries in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (&Value, &Value)> + '_ {
        self.map.iter()
    }

    /// Mutably iterate over entries in insertion order.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Value, &mut Value)> + '_ {
        self.map.iter_mut()
    }

    /// Iterate over keys in insertion order.
    pub fn keys(&self) -> impl Iterator<Item = &Value> + '_ {
        self.map.keys()
    }

    /// Iterate over values in insertion order.
    pub fn values(&self) -> impl Iterator<Item = &Value> + '_ {
        self.map.values()
    }

    /// Mutably iterate over values in insertion order.
    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut Value> + '_ {
        self.map.values_mut()
    }

    /// Get an entry by insertion index.
    #[must_use]
    pub fn get_index(&self, index: usize) -> Option<(&Value, &Value)> {
        self.map.get_index(index)
    }
}

/// A view into one mapping slot, mirroring the `indexmap`/yaml_serde entry API.
pub struct Entry<'a> {
    inner: indexmap::map::Entry<'a, Value, Value>,
}

impl<'a> Entry<'a> {
    /// Insert `default` if the key is absent, and return the slot.
    pub fn or_insert(self, default: Value) -> &'a mut Value {
        self.inner.or_insert(default)
    }

    /// Insert the result of `default` if the key is absent, and return the slot.
    pub fn or_insert_with<F: FnOnce() -> Value>(self, default: F) -> &'a mut Value {
        self.inner.or_insert_with(default)
    }

    /// Mutate the value if the key is present, and return the entry.
    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) {
        // Eq is order-insensitive for a YAML mapping, so Hash must be too.
        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);
    }
}