babbel_yaml 0.1.0

Fast, modular YAML 1.2 parser and emitter with anchors, aliases, and tags
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
//! YAML Formatting Options & Control
//!
//! Provides fine-grained control over YAML output formatting, including indentation,
//! line width, quote styles, and collection formatting for serialization.
//!
//! Copyright (c) 2026 YAML Library Developers

use alloc::string::String;

use crate::io::destinations::buffer::Buffer as BufferDestination;
use crate::nodes::node::{Node, Numeric};
use crate::stringify::default::stringify as yaml_stringify;

/// YAML output formatting options
#[derive(Debug, Clone)]
pub struct FormatOptions {
    /// Number of spaces per indentation level (default: 2)
    pub indent: usize,
    /// Maximum line width before wrapping (default: 80, 0 = no limit)
    pub line_width: usize,
    /// Preferred quote style for strings
    pub quote_style: QuoteStyle,
    /// How to format collections
    pub collection_style: CollectionStyle,
    /// Whether to emit document start marker (---)
    pub explicit_start: bool,
    /// Whether to emit document end marker (...)
    pub explicit_end: bool,
    /// Number of newlines between documents (default: 1)
    pub document_separator_lines: usize,
    /// Whether to preserve original formatting hints
    pub preserve_formatting: bool,
    /// Whether to sort mapping keys
    pub sort_keys: bool,
    /// Whether to emit null values
    pub emit_null: bool,
    /// Whether to use flow style for empty collections
    pub flow_empty_collections: bool,
    /// Minimum collection size to use block style (default: 3)
    pub block_threshold: usize,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            indent: 2,
            line_width: 80,
            quote_style: QuoteStyle::Auto,
            collection_style: CollectionStyle::Auto,
            explicit_start: false,
            explicit_end: false,
            document_separator_lines: 1,
            preserve_formatting: true,
            sort_keys: false,
            emit_null: true,
            flow_empty_collections: true,
            block_threshold: 3,
        }
    }
}

impl FormatOptions {
    /// Create new default format options
    pub fn new() -> Self {
        Self::default()
    }

    /// Compact formatting (minimal whitespace)
    pub fn compact() -> Self {
        Self {
            indent: 2,
            line_width: 0,
            quote_style: QuoteStyle::Auto,
            collection_style: CollectionStyle::Flow,
            explicit_start: false,
            explicit_end: false,
            document_separator_lines: 0,
            preserve_formatting: false,
            sort_keys: false,
            emit_null: false,
            flow_empty_collections: true,
            block_threshold: 100,
        }
    }

    /// Pretty formatting (readable, well-spaced)
    pub fn pretty() -> Self {
        Self {
            indent: 2,
            line_width: 80,
            quote_style: QuoteStyle::Auto,
            collection_style: CollectionStyle::Block,
            explicit_start: true,
            explicit_end: false,
            document_separator_lines: 1,
            preserve_formatting: false,
            sort_keys: true,
            emit_null: true,
            flow_empty_collections: true,
            block_threshold: 3,
        }
    }

    /// Minimal formatting (bare minimum valid YAML)
    pub fn minimal() -> Self {
        Self {
            indent: 2,
            line_width: 0,
            quote_style: QuoteStyle::None,
            collection_style: CollectionStyle::Flow,
            explicit_start: false,
            explicit_end: false,
            document_separator_lines: 0,
            preserve_formatting: false,
            sort_keys: false,
            emit_null: false,
            flow_empty_collections: true,
            block_threshold: 100,
        }
    }

    /// Builder method: set indentation
    pub fn with_indent(mut self, indent: usize) -> Self {
        self.indent = indent;
        self
    }

    /// Builder method: set line width
    pub fn with_line_width(mut self, width: usize) -> Self {
        self.line_width = width;
        self
    }

    /// Builder method: set quote style
    pub fn with_quote_style(mut self, style: QuoteStyle) -> Self {
        self.quote_style = style;
        self
    }

    /// Builder method: set collection style
    pub fn with_collection_style(mut self, style: CollectionStyle) -> Self {
        self.collection_style = style;
        self
    }

    /// Builder method: enable explicit document markers
    pub fn with_explicit_markers(mut self, start: bool, end: bool) -> Self {
        self.explicit_start = start;
        self.explicit_end = end;
        self
    }

    /// Builder method: enable key sorting
    pub fn with_sorted_keys(mut self, sort: bool) -> Self {
        self.sort_keys = sort;
        self
    }

    /// Builder method: set block threshold
    pub fn with_block_threshold(mut self, threshold: usize) -> Self {
        self.block_threshold = threshold;
        self
    }
}

/// Quote style for string values
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuoteStyle {
    /// Choose automatically based on content
    Auto,
    /// Prefer no quotes when possible
    None,
    /// Prefer single quotes
    Single,
    /// Prefer double quotes
    Double,
    /// Always use single quotes
    AlwaysSingle,
    /// Always use double quotes
    AlwaysDouble,
}

/// Collection formatting style
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CollectionStyle {
    /// Choose automatically based on size and content
    Auto,
    /// Prefer block style (multi-line)
    Block,
    /// Prefer flow style (inline)
    Flow,
    /// Force block style
    AlwaysBlock,
    /// Force flow style
    AlwaysFlow,
}

/// Formatting context for recursive serialization
#[derive(Debug, Clone)]
pub struct FormatContext {
    /// Current indentation level
    pub level: usize,
    /// Current column position
    pub column: usize,
    /// Parent collection style
    pub parent_style: CollectionStyle,
    /// Whether we're at the start of a line
    pub at_line_start: bool,
}

impl FormatContext {
    /// Create new format context
    pub fn new() -> Self {
        Self {
            level: 0,
            column: 0,
            parent_style: CollectionStyle::Block,
            at_line_start: true,
        }
    }

    /// Increase indentation level
    pub fn indent(&mut self) {
        self.level += 1;
    }

    /// Decrease indentation level
    pub fn dedent(&mut self) {
        if self.level > 0 {
            self.level -= 1;
        }
    }

    /// Get indentation string
    pub fn indent_str(&self, options: &FormatOptions) -> String {
        " ".repeat(self.level * options.indent)
    }

    /// Update column position
    pub fn advance(&mut self, count: usize) {
        self.column += count;
        self.at_line_start = false;
    }

    /// Reset to new line
    pub fn newline(&mut self) {
        self.column = 0;
        self.at_line_start = true;
    }
}

impl Default for FormatContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert a `Numeric` value to a human-readable string.
///
/// This is a thin wrapper around `Numeric::to_string_lossy` so that
/// callers outside of `nodes` can depend on a stable helper in the
/// stringify layer.
pub fn numeric_to_string_lossy(num: &Numeric) -> String {
    num.to_string_lossy()
}

/// Convert a `Node` into a general-purpose string representation.
///
/// This is intended for diagnostics, devtools, and non-critical
/// formatting paths. Complex structures fall back to YAML stringify;
/// if that fails, a `Debug` representation is used as a last resort.
pub fn node_to_string_lossy(node: &Node) -> String {
    match node {
        Node::Str(s, _, _) => s.clone(),
        Node::Number(num) => numeric_to_string_lossy(num),
        Node::Boolean(b) => {
            if *b {
                "true".to_string()
            } else {
                "false".to_string()
            }
        }
        Node::None => "null".to_string(),
        Node::Comment(c) => c.clone(),
        Node::Alias(name) => name.clone(),
        // For all structural/container forms, fall back to YAML
        // stringify to get a stable textual view.
        _ => {
            let mut buf = BufferDestination::new();
            if yaml_stringify(node, &mut buf).is_ok() {
                buf.to_string()
            } else {
                format!("{:?}", node)
            }
        }
    }
}

/// Convert a `Node` into a string suitable for use as a mapping key.
///
/// Key-specific tweaks over `node_to_string_lossy`:
/// - `None` is rendered as an empty string.
/// - Other types reuse the lossy representation.
pub fn node_to_key_like_string(node: &Node) -> String {
    match node {
        Node::None => String::new(),
        _ => node_to_string_lossy(node),
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_format_options_defaults() {
        let opts = FormatOptions::default();
        assert_eq!(opts.indent, 2);
        assert_eq!(opts.line_width, 80);
        assert_eq!(opts.quote_style, QuoteStyle::Auto);
        assert_eq!(opts.collection_style, CollectionStyle::Auto);
        assert!(!opts.explicit_start);
        assert!(!opts.explicit_end);
        assert_eq!(opts.document_separator_lines, 1);
        assert!(opts.preserve_formatting);
        assert!(!opts.sort_keys);
        assert!(opts.emit_null);
        assert!(opts.flow_empty_collections);
        assert_eq!(opts.block_threshold, 3);
    }

    #[test]
    fn test_format_options_builder() {
        let opts = FormatOptions::new()
            .with_indent(3)
            .with_line_width(100)
            .with_sorted_keys(true)
            .with_explicit_markers(true, false)
            .with_block_threshold(5);
        assert_eq!(opts.indent, 3);
        assert_eq!(opts.line_width, 100);
        assert!(opts.sort_keys);
        assert!(opts.explicit_start);
        assert!(!opts.explicit_end);
        assert_eq!(opts.block_threshold, 5);
    }

    #[test]
    fn test_format_context_newline_and_column() {
        let mut ctx = FormatContext::new();
        ctx.advance(2);
        assert_eq!(ctx.column, 2);
        ctx.newline();
        assert_eq!(ctx.column, 0);
        assert!(ctx.at_line_start);
    }

    #[test]
    fn test_format_context_indent_and_dedent() {
        let mut ctx = FormatContext::new();
        ctx.indent();
        ctx.indent();
        assert_eq!(ctx.level, 2);
        ctx.dedent();
        assert_eq!(ctx.level, 1);
        ctx.dedent();
        assert_eq!(ctx.level, 0);
    }

    #[test]
    fn test_format_options_explicit_markers() {
        let opts = FormatOptions::new().with_explicit_markers(true, true);
        assert!(opts.explicit_start);
        assert!(opts.explicit_end);
    }
    use super::*;

    #[test]
    fn test_default_options() {
        let opts = FormatOptions::default();
        assert_eq!(opts.indent, 2);
        assert_eq!(opts.line_width, 80);
        assert!(!opts.explicit_start);
        assert!(opts.preserve_formatting);
    }

    #[test]
    fn test_compact_options() {
        let opts = FormatOptions::compact();
        assert_eq!(opts.line_width, 0);
        assert_eq!(opts.collection_style, CollectionStyle::Flow);
        assert!(!opts.emit_null);
        assert!(!opts.preserve_formatting);
    }

    #[test]
    fn test_pretty_options() {
        let opts = FormatOptions::pretty();
        assert!(opts.explicit_start);
        assert!(opts.sort_keys);
        assert_eq!(opts.collection_style, CollectionStyle::Block);
    }

    #[test]
    fn test_builder_pattern() {
        let opts = FormatOptions::new()
            .with_indent(4)
            .with_line_width(120)
            .with_sorted_keys(true)
            .with_explicit_markers(true, true);

        assert_eq!(opts.indent, 4);
        assert_eq!(opts.line_width, 120);
        assert!(opts.sort_keys);
        assert!(opts.explicit_start);
        assert!(opts.explicit_end);
    }

    #[test]
    fn test_format_context() {
        let mut ctx = FormatContext::new();
        assert_eq!(ctx.level, 0);
        assert!(ctx.at_line_start);

        ctx.indent();
        assert_eq!(ctx.level, 1);

        ctx.advance(5);
        assert_eq!(ctx.column, 5);
        assert!(!ctx.at_line_start);

        ctx.newline();
        assert_eq!(ctx.column, 0);
        assert!(ctx.at_line_start);

        ctx.dedent();
        assert_eq!(ctx.level, 0);
    }

    #[test]
    fn test_indent_str() {
        let opts = FormatOptions::new();
        let mut ctx = FormatContext::new();

        assert_eq!(ctx.indent_str(&opts), "");

        ctx.indent();
        assert_eq!(ctx.indent_str(&opts), "  ");

        ctx.indent();
        assert_eq!(ctx.indent_str(&opts), "    ");
    }

    #[test]
    fn test_indent_str_custom() {
        let opts = FormatOptions::new().with_indent(4);
        let mut ctx = FormatContext::new();

        ctx.indent();
        assert_eq!(ctx.indent_str(&opts), "    ");

        ctx.indent();
        assert_eq!(ctx.indent_str(&opts), "        ");
    }
}