noyalib 0.0.5

A pure Rust YAML library with zero unsafe code and full serde integration
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
//! Property-based tests for noyalib using proptest.
//!
//! These tests verify invariants and properties that should hold for all
//! inputs.

// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Noyalib. All rights reserved.

use noyalib::{Mapping, Number, Value, from_str, from_value, to_string, to_value};
use proptest::prelude::*;

// ============================================================================
// Value Generators
// ============================================================================

/// Generate arbitrary Number values
fn arb_number() -> impl Strategy<Value = Number> {
    prop_oneof![
        any::<i64>().prop_map(Number::Integer),
        // Use finite floats to avoid NaN comparison issues
        any::<f64>()
            .prop_filter("finite floats only", |f| f.is_finite())
            .prop_map(Number::Float),
    ]
}

/// Generate arbitrary scalar Value (non-recursive)
fn arb_scalar_value() -> impl Strategy<Value = Value> {
    prop_oneof![
        Just(Value::Null),
        any::<bool>().prop_map(Value::Bool),
        arb_number().prop_map(Value::Number),
        // Use simple strings without special YAML characters for roundtrip
        "[a-zA-Z0-9_]{0,20}".prop_map(Value::String),
    ]
}

/// Generate arbitrary Value (recursive, with depth limit)
fn arb_value() -> impl Strategy<Value = Value> {
    arb_scalar_value().prop_recursive(
        3,  // depth
        64, // desired size
        10, // items per collection
        |inner| {
            prop_oneof![
                // Sequence of values
                prop::collection::vec(inner.clone(), 0..5).prop_map(Value::Sequence),
                // Mapping with string keys
                prop::collection::vec(
                    ("[a-zA-Z][a-zA-Z0-9_]{0,10}".prop_map(String::from), inner),
                    0..5
                )
                .prop_map(|pairs| {
                    let mut map = Mapping::new();
                    for (k, v) in pairs {
                        let _ = map.insert(k, v);
                    }
                    Value::Mapping(map)
                }),
            ]
        },
    )
}

// ============================================================================
// Roundtrip Properties
// ============================================================================

proptest! {
    /// Serialization followed by deserialization should preserve the value
    #[test]
    fn roundtrip_value(value in arb_value()) {
        let yaml = to_string(&value).expect("serialization should succeed");
        let parsed: Value = from_str(&yaml).expect("deserialization should succeed");

        // Compare structurally (ignore exact float representation)
        prop_assert!(values_equal(&value, &parsed),
            "Roundtrip failed:\nOriginal: {:?}\nYAML: {}\nParsed: {:?}",
            value, yaml, parsed);
    }

    /// to_value followed by from_value should preserve the value
    #[test]
    fn roundtrip_to_from_value(value in arb_value()) {
        let serialized = to_value(&value).expect("to_value should succeed");
        let deserialized: Value = from_value(&serialized).expect("from_value should succeed");

        prop_assert!(values_equal(&value, &deserialized),
            "to_value/from_value roundtrip failed:\nOriginal: {:?}\nSerialized: {:?}\nDeserialized: {:?}",
            value, serialized, deserialized);
    }

    /// Integers should roundtrip exactly
    #[test]
    fn roundtrip_integer(n in any::<i64>()) {
        let value = Value::Number(Number::Integer(n));
        let yaml = to_string(&value).expect("serialization should succeed");
        let parsed: Value = from_str(&yaml).expect("deserialization should succeed");

        prop_assert_eq!(parsed.as_i64(), Some(n));
    }

    /// Booleans should roundtrip exactly
    #[test]
    fn roundtrip_bool(b in any::<bool>()) {
        let value = Value::Bool(b);
        let yaml = to_string(&value).expect("serialization should succeed");
        let parsed: Value = from_str(&yaml).expect("deserialization should succeed");

        prop_assert_eq!(parsed.as_bool(), Some(b));
    }

    /// Simple strings should roundtrip exactly
    #[test]
    fn roundtrip_simple_string(s in "[a-zA-Z0-9_]{1,50}") {
        let value = Value::String(s.clone());
        let yaml = to_string(&value).expect("serialization should succeed");
        let parsed: Value = from_str(&yaml).expect("deserialization should succeed");

        prop_assert_eq!(parsed.as_str(), Some(s.as_str()));
    }

    /// Null should always roundtrip
    #[test]
    fn roundtrip_null(_dummy in Just(())) {
        let value = Value::Null;
        let yaml = to_string(&value).expect("serialization should succeed");
        let parsed: Value = from_str(&yaml).expect("deserialization should succeed");

        prop_assert!(parsed.is_null());
    }
}

// ============================================================================
// Number Properties
// ============================================================================

proptest! {
    /// Number::Integer should always return the same value via as_i64
    #[test]
    fn number_integer_as_i64(n in any::<i64>()) {
        let num = Number::Integer(n);
        prop_assert_eq!(num.as_i64(), Some(n));
    }

    /// Number::Integer with non-negative values should work with as_u64
    #[test]
    fn number_integer_as_u64(n in 0i64..=i64::MAX) {
        let num = Number::Integer(n);
        prop_assert_eq!(num.as_u64(), Some(n as u64));
    }

    /// Number::Float should always return the same value via as_f64
    #[test]
    fn number_float_as_f64(f in any::<f64>().prop_filter("finite", |f| f.is_finite())) {
        let num = Number::Float(f);
        prop_assert!((num.as_f64() - f).abs() < f64::EPSILON || num.as_f64() == f);
    }

    /// Number comparison should be reflexive
    #[test]
    fn number_cmp_reflexive(n in arb_number()) {
        prop_assert_eq!(n.cmp(&n), std::cmp::Ordering::Equal);
    }

    /// Number hash should be consistent with equality (for integers)
    #[test]
    fn number_hash_consistent_integers(a in any::<i64>(), b in any::<i64>()) {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let na = Number::Integer(a);
        let nb = Number::Integer(b);

        if na == nb {
            let mut ha = DefaultHasher::new();
            let mut hb = DefaultHasher::new();
            na.hash(&mut ha);
            nb.hash(&mut hb);
            prop_assert_eq!(ha.finish(), hb.finish());
        }
    }

    /// Number hash for identical floats should be consistent
    #[test]
    fn number_hash_identical_floats(f in any::<f64>().prop_filter("finite", |f| f.is_finite())) {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let n1 = Number::Float(f);
        let n2 = Number::Float(f);

        let mut h1 = DefaultHasher::new();
        let mut h2 = DefaultHasher::new();
        n1.hash(&mut h1);
        n2.hash(&mut h2);

        // Same float value should hash the same
        prop_assert_eq!(h1.finish(), h2.finish());
    }
}

// ============================================================================
// Value Properties
// ============================================================================

proptest! {
    /// Value equality should be reflexive
    #[test]
    fn value_eq_reflexive(value in arb_value()) {
        let cloned = value.clone();
        prop_assert_eq!(value, cloned);
    }

    /// Value comparison should be reflexive
    #[test]
    fn value_cmp_reflexive(value in arb_value()) {
        prop_assert_eq!(value.cmp(&value), std::cmp::Ordering::Equal);
    }

    /// Value hash should be consistent with equality
    #[test]
    fn value_hash_consistent(a in arb_value(), b in arb_value()) {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        if a == b {
            let mut ha = DefaultHasher::new();
            let mut hb = DefaultHasher::new();
            a.hash(&mut ha);
            b.hash(&mut hb);
            prop_assert_eq!(ha.finish(), hb.finish());
        }
    }

    /// Cloning a Value should produce an equal value
    #[test]
    fn value_clone_equals(value in arb_value()) {
        let cloned = value.clone();
        prop_assert_eq!(value, cloned);
    }
}

// ============================================================================
// Eq/Hash invariant — explicit regressions
// ============================================================================
//
// These pin the historical edge cases for `Number`'s Eq/Hash contract
// so they are always replayed regardless of proptest seed:
//   - `+0.0 == -0.0` (IEEE 754) — must hash to the same value.
//   - `NaN == NaN` (we make `Eq` reflexive) — must hash to the same value.
//   - `Float(1.0)` and `Integer(1)` are NOT equal — they may hash to
//     different values, but the variant tag in the hasher must keep
//     them apart in practice.

fn hash_one<T: std::hash::Hash>(t: &T) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::Hasher;
    let mut h = DefaultHasher::new();
    t.hash(&mut h);
    h.finish()
}

#[test]
fn number_zero_negative_zero_eq_hash() {
    let p = Number::Float(0.0);
    let n = Number::Float(-0.0);
    assert_eq!(p, n, "+0.0 == -0.0 by IEEE 754");
    assert_eq!(hash_one(&p), hash_one(&n), "Eq/Hash invariant");
}

#[test]
fn number_nan_eq_hash() {
    let a = Number::Float(f64::NAN);
    let b = Number::Float(f64::from_bits(0x7FF8_0000_0000_0042));
    assert_eq!(a, b, "all NaNs compare equal under our reflexive-Eq policy");
    assert_eq!(hash_one(&a), hash_one(&b), "Eq/Hash invariant");
}

#[test]
fn value_zero_negative_zero_eq_hash() {
    let p = Value::Number(Number::Float(0.0));
    let n = Value::Number(Number::Float(-0.0));
    assert_eq!(p, n);
    assert_eq!(hash_one(&p), hash_one(&n));
}

// ============================================================================
// Mapping Properties
// ============================================================================

proptest! {
    /// Inserting a key should make it retrievable
    #[test]
    fn mapping_insert_get(
        key in "[a-zA-Z][a-zA-Z0-9_]{0,10}",
        value in arb_scalar_value()
    ) {
        let mut map = Mapping::new();
        let _ = map.insert(key.clone(), value.clone());

        prop_assert_eq!(map.get(&key), Some(&value));
    }

    /// Removing a key should make it unretrievable
    #[test]
    fn mapping_remove(
        key in "[a-zA-Z][a-zA-Z0-9_]{0,10}",
        value in arb_scalar_value()
    ) {
        let mut map = Mapping::new();
        let _ = map.insert(key.clone(), value);
        let _ = map.shift_remove(&key);

        prop_assert!(map.get(&key).is_none());
    }

    /// Mapping length should match number of unique keys inserted
    #[test]
    fn mapping_length(
        pairs in prop::collection::vec(
            ("[a-zA-Z][a-zA-Z0-9]{0,5}".prop_map(String::from), arb_scalar_value()),
            0..10
        )
    ) {
        let mut map = Mapping::new();
        let mut unique_keys = std::collections::HashSet::new();

        for (k, v) in pairs {
            let _ = map.insert(k.clone(), v);
            let _ = unique_keys.insert(k);
        }

        prop_assert_eq!(map.len(), unique_keys.len());
    }
}

// ============================================================================
// Merge Properties
// ============================================================================

proptest! {
    /// Merging with an empty mapping should not change the base
    #[test]
    fn merge_with_empty(base in arb_value()) {
        let mut merged = base.clone();
        merged.merge(Value::Mapping(Mapping::new()));

        // If base was a mapping, it should be unchanged
        if base.is_mapping() {
            prop_assert!(values_equal(&merged, &base));
        }
    }

    /// Merging into an empty mapping should produce the other mapping
    #[test]
    fn merge_into_empty(
        pairs in prop::collection::vec(
            ("[a-zA-Z][a-zA-Z0-9]{0,5}".prop_map(String::from), arb_scalar_value()),
            1..5
        )
    ) {
        let mut base = Value::Mapping(Mapping::new());

        let mut other = Mapping::new();
        for (k, v) in pairs.iter() {
            let _ = other.insert(k.clone(), v.clone());
        }

        let other_clone = other.clone();
        base.merge(Value::Mapping(other));

        // Base should now contain all keys from other with their final values
        for (k, v) in other_clone.iter() {
            prop_assert_eq!(base.get(k.as_str()), Some(v));
        }
    }
}

// ============================================================================
// Path Access Properties
// ============================================================================

proptest! {
    /// get_path on a simple mapping should work like get
    #[test]
    fn get_path_simple(
        key in "[a-zA-Z][a-zA-Z0-9_]{0,10}",
        value in arb_scalar_value()
    ) {
        let mut map = Mapping::new();
        let _ = map.insert(key.clone(), value.clone());
        let v = Value::Mapping(map);

        prop_assert_eq!(v.get_path(&key), Some(&value));
    }

    /// get_path with invalid path should return None
    #[test]
    fn get_path_nonexistent(
        key in "[a-zA-Z][a-zA-Z0-9_]{0,10}",
        value in arb_scalar_value()
    ) {
        let mut map = Mapping::new();
        let _ = map.insert(key, value);
        let v = Value::Mapping(map);

        prop_assert!(v.get_path("nonexistent_key_xyz").is_none());
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Compare two Values for structural equality, handling float comparison
fn values_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Null, Value::Null) => true,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Number(Number::Integer(a)), Value::Number(Number::Integer(b))) => a == b,
        (Value::Number(Number::Float(a)), Value::Number(Number::Float(b))) => {
            (a - b).abs() < 1e-10 || (a.is_nan() && b.is_nan())
        }
        (Value::Number(Number::Integer(a)), Value::Number(Number::Float(b))) => {
            (*a as f64 - b).abs() < 1e-10
        }
        (Value::Number(Number::Float(a)), Value::Number(Number::Integer(b))) => {
            (a - *b as f64).abs() < 1e-10
        }
        (Value::String(a), Value::String(b)) => a == b,
        (Value::Sequence(a), Value::Sequence(b)) => {
            a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| values_equal(a, b))
        }
        (Value::Mapping(a), Value::Mapping(b)) => {
            a.len() == b.len()
                && a.iter()
                    .all(|(k, v)| b.get(k).is_some_and(|bv| values_equal(v, bv)))
        }
        (Value::Tagged(a), Value::Tagged(b)) => {
            a.tag() == b.tag() && values_equal(a.value(), b.value())
        }
        _ => false,
    }
}