serde-saphyr 1.3.0

YAML (de)serializer for Serde, emphasizing panic-free parsing, fast builds and good error reporting. Supports properties, include, tag and comment capture
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
use serde_core::de::{self, Deserialize, Deserializer, Visitor};
use std::fmt;
use std::marker::PhantomData;

/// Force a sequence to be emitted in flow style: `[a, b, c]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FlowSeq<T>(pub T);

/// Force a mapping to be emitted in flow style: `{k1: v1, k2: v2}`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FlowMap<T>(pub T);

/// Force a string value to be emitted in double-quoted style.
///
/// This wrapper is transparent during deserialization: the inner value is
/// deserialized normally and placed into `DoubleQuoted<T>`. `DoubleQuoted<T>` implements
/// Serde traits only for string-like `T` values.
///
/// ```rust
/// # #[cfg(feature = "serialize")]
/// # {
/// use serde::Serialize;
/// use serde_saphyr::DoubleQuoted;
///
/// #[derive(Serialize)]
/// struct Config {
///     value: DoubleQuoted<String>,
/// }
///
/// let cfg = Config { value: DoubleQuoted("plain text".to_string()) };
/// let yaml = serde_saphyr::to_string(&cfg).unwrap();
/// assert_eq!(yaml, "value: \"plain text\"\n");
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DoubleQuoted<T>(pub T);

/// Force a string value to be emitted in a single-quoted style. This provides additional
/// safety constraints, as serializer rejects control characters and other values that require
/// double-quoted string escaping.
///
/// This wrapper is transparent during deserialization: the inner value is
/// deserialized normally and placed into `SingleQuoted<T>`. `SingleQuoted<T>` implements
/// Serde traits only for string-like `T` values.
///
/// Serialization fails if the value cannot be represented
/// safely in YAML single-quoted style.
///
/// ```rust
/// # #[cfg(feature = "serialize")]
/// # {
/// use serde::Serialize;
/// use serde_saphyr::SingleQuoted;
///
/// #[derive(Serialize)]
/// struct Config {
///     value: SingleQuoted<String>,
/// }
///
/// let cfg = Config { value: SingleQuoted("plain text".to_string()) };
/// let yaml = serde_saphyr::to_string(&cfg).unwrap();
/// assert_eq!(yaml, "value: 'plain text'\n");
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SingleQuoted<T>(pub T);

/// Add an empty line after the wrapped value when serializing.
///
/// This wrapper is transparent during deserialization and can be nested with
/// other wrappers like `Commented`, `FlowSeq`, etc.
/// ```rust
/// # #[cfg(feature = "serialize")]
/// # {
/// use serde::Serialize;
/// use serde_saphyr::SpaceAfter;
///
/// #[derive(Serialize)]
/// struct Config {
///     first: SpaceAfter<i32>,
///     second: i32,
/// }
///
/// let cfg = Config { first: SpaceAfter(1), second: 2 };
/// let yaml = serde_saphyr::to_string(&cfg).unwrap();
/// // The output will have an empty line after "first: 1"
/// # }
/// ```
/// **Important:** Avoid using this wrapper with `LitStr`/`LitString` as it may add the empty
/// line to the string content. For `FoldStr`/`FoldString` and other YAML values
/// (e.g. `key: value`, quoted scalars), the extra empty line is cosmetic.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpaceAfter<T>(pub T);

/// Serialize `None` as YAML tilde (`~`) while otherwise behaving like `Option<T>`.
///
/// `Some(value)` is serialized transparently as `value`. `None` is serialized
/// as `~` instead of the serializer's regular null spelling. Deserialization
/// delegates to `Option<T>`, so `~`, `null`, and empty YAML values all become
/// `NullableTilde(None)`.
///
/// ```rust
/// # #[cfg(feature = "serialize")]
/// # {
/// use serde::Serialize;
/// use serde_saphyr::NullableTilde;
///
/// #[derive(Serialize)]
/// struct Config {
///     maybe: NullableTilde<String>,
/// }
///
/// let cfg = Config { maybe: NullableTilde(None) };
/// let yaml = serde_saphyr::to_string(&cfg).unwrap();
/// assert_eq!(yaml, "maybe: ~\n");
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NullableTilde<T>(pub Option<T>);

/// Attach an inline YAML comment to a value when serializing.
///
/// This wrapper lets you annotate a scalar with an inline YAML comment that is
/// emitted after the value when using block style. The typical form is:
/// `value # comment`. This is the most useful when deserializing the anchor
/// reference (so a human reader can see what a referenced value represents).
///
/// Comment is also captured into its field when deserializing YAML.
///
/// Behavior
/// - Block style (default): the comment appears after the scalar on the same line.
/// - Flow style (inside `[ ... ]` or `{ ... }`): comments are suppressed to keep
///   the flow representation compact and unambiguous.
/// - Complex values (sequences/maps/structs): the comment is ignored; only the
///   inner value is serialized to preserve indentation and layout.
/// - Newlines in comments are sanitized to spaces so the comment remains on a
///   single line (e.g., "a\nb" becomes "a b").
/// - Deserialization of `Commented<T>` captures nearby source comments when the
///   `serde-saphyr` deserializer can provide them. Other deserializers treat it
///   transparently and produce an empty comment string.
/// - Comment capture is use-site oriented for replayed YAML. Comments from an
///   anchor definition are not copied through aliases or merge keys; a field
///   materialized by `<<: *defaults` does not inherit comments that were written
///   above the field inside `&defaults`.
/// - For container values, comments attached to the parent value itself are
///   captured only by `Commented<Container>` and are not inherited by the first
///   child field or element. A comment inside the container, directly above a
///   child key or element, is captured by that child.
/// - When an alias to a container is used as a nested value, leading comments
///   above the alias follow the same inside-container rule. For example,
///   `root:\n  # comment\n  *defaults` leaves the comment available to the
///   expanded container's first child rather than capturing it on the alias use.
///
/// Examples
///
/// Basic scalar with a comment in block style:
/// ```rust
/// # #[cfg(feature = "serialize")]
/// # {
/// use serde::Serialize;
///
/// // Re-exported from the crate root
/// use serde_saphyr::Commented;
///
/// let out = serde_saphyr::to_string(&Commented(42, "answer".to_string())).unwrap();
/// assert_eq!(out, "42 # answer\n");
/// # }
/// ```
///
/// As a mapping value, still inline:
/// ```rust
/// # #[cfg(feature = "serialize")]
/// # {
/// use serde::Serialize;
/// use serde_saphyr::Commented;
///
/// #[derive(Serialize)]
/// struct S { xn: Commented<i32> }
///
/// let s = S { xn: Commented(5, "send five starships first".into()) };
/// let out = serde_saphyr::to_string(&s).unwrap();
/// assert_eq!(out, "xn: 5 # send five starships first\n");
/// # }
/// ```
///
/// *Important*: Comments are suppressed in flow contexts (no `#` appears), and
/// ignored for complex inner values during serialization. During deserialization,
/// parent-side comments on a container such as `root: # comment` are captured by
/// `Commented<Container>` only; comments inside the container, directly above the
/// first child key or element, remain available to that child. The same applies
/// to leading comments above a nested alias whose target is a container.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Commented<T>(pub T, pub String);

/// Capture and emit the resolved YAML tag attached to a value.
///
/// The first field contains the value and the second contains its resolved tag.
/// `Some(tag)` is how an arbitrary tag is put on a node: the serializer emits it
/// as that node's explicit tag. `None` requests no tag and serializes exactly as
/// the unwrapped `T` would, which is also what deserializing an untagged node
/// produces.
///
/// Resolution deliberately discards source spelling: for example, `!!str` is
/// captured as `Some("tag:yaml.org,2002:str")`, while a local tag such as
/// `!widget` is captured as `Some("!widget")`. Tags resolved through a `%TAG`
/// directive are captured as their complete URI. A present tag always has a
/// non-empty resolved identity; `Some("")` is invalid when serializing rather
/// than an alternative spelling of `None`.
///
/// During serialization, a resolved global tag URI is emitted using YAML's
/// verbatim form (`!<...>`). This preserves the resolved tag identity across a
/// round trip, but does not reproduce tag handles or `%TAG` directives. Local
/// tags are emitted directly. A non-local identity must have valid absolute-URI
/// structure; characters requiring URI escaping are percent-encoded on output.
///
/// `Tagged<Commented<T>>` and `Commented<Tagged<T>>` are both supported. Tag
/// capture remains subject to the deserializer's normal tag semantics and
/// `reject_unsupported_tags` option.
///
/// # Clashing tags
///
/// A YAML node carries at most one tag, and serializing certain values produces
/// a tag without being asked: `!!binary` for a byte buffer, or the variant tag
/// emitted under the `tagged_enums` option. Where such a generated tag meets the
/// wrapper's own on one node, they must match or wrappers' own tag must
/// be `None`. Otherwise, error is reported.
///
/// Deserializers other than serde-saphyr do not provide YAML tag metadata; when
/// used with one of them, `Tagged<T>` behaves transparently and gets `None` as
/// its tag.
///
/// ```rust
/// # #[cfg(all(feature = "serialize", feature = "deserialize"))]
/// # {
/// use serde_saphyr::{Commented, Tagged, from_str, to_string};
///
/// let value: Tagged<String> = from_str("!!str value").unwrap();
/// assert_eq!(
///     value,
///     Tagged("value".into(), Some("tag:yaml.org,2002:str".into())),
/// );
/// assert_eq!(
///     to_string(&value).unwrap(),
///     "!<tag:yaml.org,2002:str> value\n",
/// );
///
/// let tagged_comment: Tagged<Commented<String>> =
///     from_str("!widget value # note").unwrap();
/// assert_eq!(
///     tagged_comment,
///     Tagged(
///         Commented("value".into(), "note".into()),
///         Some("!widget".into()),
///     ),
/// );
///
/// let commented_tag: Commented<Tagged<String>> =
///     from_str("!widget value # note").unwrap();
/// assert_eq!(
///     commented_tag,
///     Commented(
///         Tagged("value".into(), Some("!widget".into())),
///         "note".into(),
///     ),
/// );
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Tagged<T>(pub T, pub Option<String>);

#[cfg(feature = "garde")]
impl<T: garde::Validate> garde::Validate for Commented<T> {
    type Context = T::Context;

    fn validate_into(
        &self,
        ctx: &Self::Context,
        parent: &mut dyn FnMut() -> garde::Path,
        report: &mut garde::Report,
    ) {
        self.0.validate_into(ctx, parent, report);
    }
}

#[cfg(feature = "garde")]
impl<T: garde::Validate> garde::Validate for Tagged<T> {
    type Context = T::Context;

    fn validate_into(
        &self,
        ctx: &Self::Context,
        parent: &mut dyn FnMut() -> garde::Path,
        report: &mut garde::Report,
    ) {
        self.0.validate_into(ctx, parent, report);
    }
}

#[cfg(feature = "validator")]
impl<T: validator::Validate> validator::Validate for Commented<T> {
    fn validate(&self) -> Result<(), validator::ValidationErrors> {
        self.0.validate()
    }
}

#[cfg(feature = "validator")]
impl<T: validator::Validate> validator::Validate for Tagged<T> {
    fn validate(&self) -> Result<(), validator::ValidationErrors> {
        self.0.validate()
    }
}

#[cfg(feature = "validator")]
impl<'v_a, T: validator::ValidateArgs<'v_a>> validator::ValidateArgs<'v_a> for Commented<T> {
    type Args = T::Args;

    fn validate_with_args(&self, args: Self::Args) -> Result<(), validator::ValidationErrors> {
        self.0.validate_with_args(args)
    }
}

#[cfg(feature = "validator")]
impl<'v_a, T: validator::ValidateArgs<'v_a>> validator::ValidateArgs<'v_a> for Tagged<T> {
    type Args = T::Args;

    fn validate_with_args(&self, args: Self::Args) -> Result<(), validator::ValidationErrors> {
        self.0.validate_with_args(args)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for FlowSeq<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        T::deserialize(deserializer).map(FlowSeq)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for FlowMap<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        T::deserialize(deserializer).map(FlowMap)
    }
}

impl<'de, T> Deserialize<'de> for DoubleQuoted<T>
where
    T: Deserialize<'de> + AsRef<str>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        T::deserialize(deserializer).map(DoubleQuoted)
    }
}

impl<'de, T> Deserialize<'de> for SingleQuoted<T>
where
    T: Deserialize<'de> + AsRef<str>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        T::deserialize(deserializer).map(SingleQuoted)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Commented<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        struct CommentedVisitor<T>(PhantomData<T>);

        impl<'de, T: Deserialize<'de>> Visitor<'de> for CommentedVisitor<T> {
            type Value = Commented<T>;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a commented YAML value")
            }

            fn visit_newtype_struct<D>(
                self,
                deserializer: D,
            ) -> std::result::Result<Self::Value, D::Error>
            where
                D: Deserializer<'de>,
            {
                T::deserialize(deserializer).map(|value| Commented(value, String::new()))
            }

            fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
            where
                A: de::SeqAccess<'de>,
            {
                let value = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let comment = seq.next_element()?.unwrap_or_default();
                Ok(Commented(value, comment))
            }
        }

        deserializer.deserialize_newtype_struct("__yaml_commented", CommentedVisitor(PhantomData))
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Tagged<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        struct TaggedVisitor<T>(PhantomData<T>);

        impl<'de, T: Deserialize<'de>> Visitor<'de> for TaggedVisitor<T> {
            type Value = Tagged<T>;

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

            fn visit_newtype_struct<D>(
                self,
                deserializer: D,
            ) -> std::result::Result<Self::Value, D::Error>
            where
                D: Deserializer<'de>,
            {
                T::deserialize(deserializer).map(|value| Tagged(value, None))
            }

            fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
            where
                A: de::SeqAccess<'de>,
            {
                let value = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let tag: Option<String> = seq.next_element()?;
                Ok(Tagged(value, tag))
            }
        }

        deserializer.deserialize_newtype_struct("__yaml_tagged", TaggedVisitor(PhantomData))
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for SpaceAfter<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        T::deserialize(deserializer).map(SpaceAfter)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for NullableTilde<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        Option::<T>::deserialize(deserializer).map(NullableTilde)
    }
}

#[cfg(all(test, feature = "deserialize"))]
mod tests {
    use serde::Deserialize;

    use crate::{
        Commented, DoubleQuoted, FlowMap, FlowSeq, NullableTilde, SingleQuoted, SpaceAfter, Tagged,
    };

    #[derive(Debug, Deserialize, PartialEq)]
    struct WrappersDoc {
        seq: FlowSeq<Vec<u32>>,
        map: FlowMap<std::collections::BTreeMap<String, u32>>,
        after: SpaceAfter<String>,
        nullable_tilde_none: NullableTilde<String>,
        nullable_tilde_some: NullableTilde<String>,
        commented: Commented<bool>,
        double_quoted: DoubleQuoted<String>,
        single_quoted: SingleQuoted<String>,
    }

    #[test]
    fn wrappers_remain_deserializable_without_serialize() {
        let value: WrappersDoc = crate::from_str(
            "seq: [1, 2]\nmap: {a: 1}\nafter: hello\nnullable_tilde_none: ~\nnullable_tilde_some: value\ncommented: true\ndouble_quoted: value\nsingle_quoted: value\n",
        )
        .unwrap();

        assert_eq!(value.seq, FlowSeq(vec![1, 2]));
        assert_eq!(value.after, SpaceAfter("hello".to_string()));
        assert_eq!(value.nullable_tilde_none, NullableTilde(None));
        assert_eq!(
            value.nullable_tilde_some,
            NullableTilde(Some("value".to_string()))
        );
        assert_eq!(value.commented, Commented(true, String::new()));
        assert_eq!(value.double_quoted, DoubleQuoted("value".to_string()));
        assert_eq!(value.single_quoted, SingleQuoted("value".to_string()));
        assert_eq!(value.map.0.get("a"), Some(&1));
    }

    #[test]
    fn tagged_is_transparent_for_non_yaml_deserializers() {
        let value: Tagged<u32> = serde_json::from_str("5").unwrap();

        assert_eq!(value, Tagged(5, None));
    }
}