noyalib 0.0.13

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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! YAML tag types (`Tag`, `TaggedValue`) and tag utilities.

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

use super::Value;
use crate::prelude::*;
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
use serde::{Deserialize, Serialize};

// ============================================================================
// Tag utilities
// ============================================================================

/// Strips a leading `!` from a string, if present.
///
/// # Examples
///
/// ```rust
/// use noyalib::nobang;
///
/// assert_eq!(nobang("!foo"), "foo");
/// assert_eq!(nobang("foo"), "foo");
/// assert_eq!(nobang("!!int"), "!int");
/// ```
#[must_use]
pub fn nobang(s: &str) -> &str {
    s.strip_prefix('!').unwrap_or(s)
}

/// Result of checking whether a value looks like a YAML tag.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MaybeTag<T> {
    /// The value is a tag (starts with `!`).
    Tag(String),
    /// The value is not a tag.
    NotTag(T),
}

/// Checks whether a value's display representation looks like a YAML tag.
///
/// A value is considered a tag if its string representation starts with `!`.
///
/// # Examples
///
/// ```rust
/// use noyalib::{check_for_tag, MaybeTag};
///
/// let result = check_for_tag(&"!mytag");
/// assert!(matches!(result, MaybeTag::Tag(_)));
///
/// let result = check_for_tag(&"plain");
/// assert!(matches!(result, MaybeTag::NotTag(_)));
/// ```
pub fn check_for_tag<T: fmt::Display>(value: &T) -> MaybeTag<String> {
    let s = value.to_string();
    if s.starts_with('!') {
        MaybeTag::Tag(s)
    } else {
        MaybeTag::NotTag(s)
    }
}

/// Magic key in the [`TagPreservingMapAccess`] map shape that
/// signals "the next entry is the tag string". Recognised by
/// `Value::deserialize`'s visitor on the tag-preserving path
/// driven by [`crate::de::Deserializer::preserve_tags`].
pub(crate) const TAGGED_VALUE_FIELD_TAG: &str = "$__noyalib_tag";

/// Magic key in the [`TagPreservingMapAccess`] map shape that
/// signals "the next entry is the inner [`Value`]".
pub(crate) const TAGGED_VALUE_FIELD_VALUE: &str = "$__noyalib_value";

/// A YAML tag.
///
/// Tags are used in YAML to denote the type of a value.
/// For example, `!custom_type value` has the tag `!custom_type`.
///
/// Tag comparison ignores a leading `!` prefix, so `Tag::new("!foo") ==
/// Tag::new("foo")`.
///
/// # Examples
///
/// ```rust
/// use noyalib::Tag;
///
/// let tag = Tag::new("!custom");
/// assert_eq!(tag.as_str(), "!custom");
/// assert_eq!(Tag::new("!foo"), Tag::new("foo"));
/// ```
#[derive(Debug, Clone)]
pub struct Tag(String);

impl Tag {
    /// Creates a new tag from a string.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::Tag;
    /// let t = Tag::new("!Custom");
    /// assert_eq!(t.as_str(), "!Custom");
    /// ```
    #[must_use]
    pub fn new(tag: impl Into<String>) -> Self {
        Self(tag.into())
    }

    /// Returns the tag as a string slice.
    ///
    /// The leading `!` (or `!!`) is included; use [`Tag::nobang`]
    /// for the unprefixed form.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::Tag;
    /// assert_eq!(Tag::new("!Custom").as_str(), "!Custom");
    /// assert_eq!(Tag::new("!!str").as_str(), "!!str");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the tag and returns the inner string.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::Tag;
    /// let s: String = Tag::new("!Custom").into_string();
    /// assert_eq!(s, "!Custom");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// Returns the tag string with a single leading `!` stripped.
    ///
    /// Strips at most one `!` — the YAML 1.2 *primary* tag
    /// handle. The secondary `!!` handle keeps one `!` after the
    /// strip (`!!str` → `!str`); use `Tag::as_str().trim_start_matches('!')`
    /// if you want every `!` removed.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::Tag;
    /// assert_eq!(Tag::new("!Custom").nobang(), "Custom");
    /// assert_eq!(Tag::new("!!str").nobang(), "!str");
    /// assert_eq!(Tag::new("plain").nobang(), "plain");
    /// ```
    #[must_use]
    pub fn nobang(&self) -> &str {
        nobang(&self.0)
    }
}

impl fmt::Display for Tag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<&str> for Tag {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl From<String> for Tag {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl AsRef<str> for Tag {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq for Tag {
    fn eq(&self, other: &Self) -> bool {
        nobang(&self.0) == nobang(&other.0)
    }
}

impl Eq for Tag {}

impl Hash for Tag {
    fn hash<H: Hasher>(&self, state: &mut H) {
        nobang(&self.0).hash(state);
    }
}

impl PartialOrd for Tag {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Tag {
    fn cmp(&self, other: &Self) -> Ordering {
        nobang(&self.0).cmp(nobang(&other.0))
    }
}

impl TryFrom<&[u8]> for Tag {
    type Error = core::str::Utf8Error;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        core::str::from_utf8(bytes).map(Tag::new)
    }
}

/// A tagged YAML value.
///
/// Represents a value with an explicit YAML tag, such as `!custom_type value`.
/// Tags are used to specify the type or interpretation of a value.
///
/// # Examples
///
/// ```rust
/// use noyalib::{Tag, TaggedValue, Value};
///
/// let tagged = TaggedValue::new(
///     Tag::new("!timestamp"),
///     Value::String("2024-01-01".to_string()),
/// );
/// assert_eq!(tagged.tag().as_str(), "!timestamp");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct TaggedValue {
    /// The tag.
    tag: Tag,
    /// The value. `pub(crate)` so the parent module's `Value` impls can
    /// move the inner value out (e.g. `Value::untag`).
    pub(crate) value: Box<Value>,
}

impl TaggedValue {
    /// Creates a new tagged value.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::{Tag, TaggedValue, Value};
    /// let tv = TaggedValue::new(Tag::new("!Custom"), Value::from("hello"));
    /// assert_eq!(tv.tag().as_str(), "!Custom");
    /// assert_eq!(tv.value().as_str(), Some("hello"));
    /// ```
    #[must_use]
    pub fn new(tag: Tag, value: Value) -> Self {
        Self {
            tag,
            value: Box::new(value),
        }
    }

    /// Returns a reference to the tag.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::{Tag, TaggedValue, Value};
    /// let tv = TaggedValue::new(Tag::new("!Color"), Value::from("#ff8800"));
    /// assert_eq!(tv.tag().as_str(), "!Color");
    /// ```
    #[must_use]
    pub fn tag(&self) -> &Tag {
        &self.tag
    }

    /// Returns a reference to the inner value.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::{Tag, TaggedValue, Value};
    /// let tv = TaggedValue::new(Tag::new("!Color"), Value::from("#ff8800"));
    /// assert_eq!(tv.value().as_str(), Some("#ff8800"));
    /// ```
    #[must_use]
    pub fn value(&self) -> &Value {
        &self.value
    }

    /// Returns a mutable reference to the inner value.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::{Tag, TaggedValue, Value};
    /// let mut tv = TaggedValue::new(Tag::new("!Color"), Value::from("#000"));
    /// *tv.value_mut() = Value::from("#ff8800");
    /// assert_eq!(tv.value().as_str(), Some("#ff8800"));
    /// ```
    #[must_use]
    pub fn value_mut(&mut self) -> &mut Value {
        &mut self.value
    }

    /// Consumes the tagged value and returns the tag and value
    /// as separate owned components.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::{Tag, TaggedValue, Value};
    /// let tv = TaggedValue::new(Tag::new("!Custom"), Value::from(42_i64));
    /// let (tag, value) = tv.into_parts();
    /// assert_eq!(tag.as_str(), "!Custom");
    /// assert_eq!(value.as_i64(), Some(42));
    /// ```
    #[must_use]
    pub fn into_parts(self) -> (Tag, Value) {
        (self.tag, *self.value)
    }
}

impl fmt::Display for TaggedValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.tag, self.value)
    }
}

impl Serialize for TaggedValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(self.tag.as_str(), self.value())?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for TaggedValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{MapAccess, Visitor};

        struct TaggedValueVisitor;

        impl<'de> Visitor<'de> for TaggedValueVisitor {
            type Value = TaggedValue;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a single-entry map representing a tagged value")
            }

            fn visit_map<A>(self, mut map: A) -> Result<TaggedValue, A::Error>
            where
                A: MapAccess<'de>,
            {
                let (tag, value): (String, Value) = map
                    .next_entry()?
                    .ok_or_else(|| serde::de::Error::custom("expected a single-entry map"))?;
                Ok(TaggedValue::new(Tag::new(tag), value))
            }
        }

        deserializer.deserialize_map(TaggedValueVisitor)
    }
}

impl<'de> serde::Deserializer<'de> for &'de TaggedValue {
    type Error = crate::Error;

    fn deserialize_any<V>(self, visitor: V) -> crate::Result<V::Value>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_map(TaggedValueMapAccess {
            tag: Some(self.tag.as_str()),
            value: Some(self.value()),
        })
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> crate::Result<V::Value>
    where
        V: serde::de::Visitor<'de>,
    {
        visitor.visit_enum(TaggedValueEnumAccess { tagged: self })
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
        byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct identifier ignored_any
    }
}

struct TaggedValueMapAccess<'de> {
    tag: Option<&'de str>,
    value: Option<&'de Value>,
}

impl<'de> serde::de::MapAccess<'de> for TaggedValueMapAccess<'de> {
    type Error = crate::Error;

    fn next_key_seed<K>(&mut self, seed: K) -> crate::Result<Option<K::Value>>
    where
        K: serde::de::DeserializeSeed<'de>,
    {
        match self.tag.take() {
            Some(tag) => seed
                .deserialize(serde::de::value::BorrowedStrDeserializer::new(tag))
                .map(Some),
            None => Ok(None),
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> crate::Result<V::Value>
    where
        V: serde::de::DeserializeSeed<'de>,
    {
        match self.value.take() {
            Some(value) => seed.deserialize(value),
            None => Err(serde::de::Error::custom("value is missing")),
        }
    }
}

/// MapAccess emitted on the [`TAGGED_VALUE_TYPE_NAME`] code path.
///
/// Surfaces a tagged scalar as a two-entry map with magic keys
/// (`$__noyalib_tag` → tag string; `$__noyalib_value` → inner
/// `Value`) so [`Value`]'s own visitor can pattern-match the
/// shape and reconstruct `Value::Tagged(...)` on the
/// data-binding return path. Distinct from the existing
/// [`TaggedValueMapAccess`] (which uses the *real* tag as the
/// map key for typed-enum deserialise) to avoid colliding with
/// user data that legitimately has a key of the same name.
pub(crate) struct TagPreservingMapAccess<'de> {
    state: TagPreservingState<'de>,
}

#[derive(Clone, Copy)]
enum TagPreservingState<'de> {
    EmitTagKey { tag: &'de str, value: &'de Value },
    EmitTagValue { tag: &'de str, value: &'de Value },
    EmitValueKey { value: &'de Value },
    EmitValueValue { value: &'de Value },
    Done,
}

impl<'de> TagPreservingMapAccess<'de> {
    pub(crate) fn new(tag: &'de str, value: &'de Value) -> Self {
        Self {
            state: TagPreservingState::EmitTagKey { tag, value },
        }
    }
}

impl<'de> serde::de::MapAccess<'de> for TagPreservingMapAccess<'de> {
    type Error = crate::Error;

    fn next_key_seed<K>(&mut self, seed: K) -> crate::Result<Option<K::Value>>
    where
        K: serde::de::DeserializeSeed<'de>,
    {
        match self.state {
            TagPreservingState::EmitTagKey { tag, value } => {
                self.state = TagPreservingState::EmitTagValue { tag, value };
                seed.deserialize(
                    serde::de::value::BorrowedStrDeserializer::<crate::Error>::new(
                        TAGGED_VALUE_FIELD_TAG,
                    ),
                )
                .map(Some)
            }
            TagPreservingState::EmitValueKey { value } => {
                self.state = TagPreservingState::EmitValueValue { value };
                seed.deserialize(
                    serde::de::value::BorrowedStrDeserializer::<crate::Error>::new(
                        TAGGED_VALUE_FIELD_VALUE,
                    ),
                )
                .map(Some)
            }
            TagPreservingState::Done => Ok(None),
            // Calling next_key without consuming the previous value
            // is a serde misuse — surface as a custom error rather
            // than panicking.
            TagPreservingState::EmitTagValue { .. } | TagPreservingState::EmitValueValue { .. } => {
                Err(serde::de::Error::custom(
                    "TagPreservingMapAccess: next_key called before next_value",
                ))
            }
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> crate::Result<V::Value>
    where
        V: serde::de::DeserializeSeed<'de>,
    {
        match self.state {
            TagPreservingState::EmitTagValue { tag, value } => {
                self.state = TagPreservingState::EmitValueKey { value };
                seed.deserialize(
                    serde::de::value::BorrowedStrDeserializer::<crate::Error>::new(tag),
                )
            }
            TagPreservingState::EmitValueValue { value } => {
                self.state = TagPreservingState::Done;
                // Route through the preserve-tags-aware Deserializer
                // so any nested `Value::Tagged` inside `value` also
                // survives the round-trip — without this wrapping,
                // a tagged scalar inside a tagged collection would
                // collapse to the single-key `Mapping{"!tag": …}`
                // shape that the standard `&'de Value` Deserializer
                // produces for `Value::Tagged` (BUG: noyalib v0.0.1
                // C4HZ regression — global tags inside a tagged
                // sequence).
                seed.deserialize(crate::de::Deserializer::with_options_preserving_tags(
                    value, None, false,
                ))
            }
            _ => Err(serde::de::Error::custom(
                "TagPreservingMapAccess: next_value called out of order",
            )),
        }
    }
}

struct TaggedValueEnumAccess<'de> {
    tagged: &'de TaggedValue,
}

impl<'de> serde::de::EnumAccess<'de> for TaggedValueEnumAccess<'de> {
    type Error = crate::Error;
    type Variant = TaggedValueVariantAccess<'de>;

    fn variant_seed<V>(self, seed: V) -> crate::Result<(V::Value, Self::Variant)>
    where
        V: serde::de::DeserializeSeed<'de>,
    {
        let variant = seed.deserialize(
            serde::de::value::BorrowedStrDeserializer::<crate::Error>::new(
                self.tagged.tag.nobang(),
            ),
        )?;
        Ok((
            variant,
            TaggedValueVariantAccess {
                value: self.tagged.value(),
            },
        ))
    }
}

struct TaggedValueVariantAccess<'de> {
    value: &'de Value,
}

impl<'de> serde::de::VariantAccess<'de> for TaggedValueVariantAccess<'de> {
    type Error = crate::Error;

    fn unit_variant(self) -> crate::Result<()> {
        Ok(())
    }

    fn newtype_variant_seed<T>(self, seed: T) -> crate::Result<T::Value>
    where
        T: serde::de::DeserializeSeed<'de>,
    {
        seed.deserialize(self.value)
    }

    fn tuple_variant<V>(self, _len: usize, visitor: V) -> crate::Result<V::Value>
    where
        V: serde::de::Visitor<'de>,
    {
        serde::Deserializer::deserialize_seq(self.value, visitor)
    }

    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> crate::Result<V::Value>
    where
        V: serde::de::Visitor<'de>,
    {
        serde::Deserializer::deserialize_map(self.value, visitor)
    }
}