Skip to main content

serde_saphyr/ser/
options.rs

1//! Serializer options for YAML emission.
2//!
3//! Controls indentation and optional anchor name generation for the serializer.
4//!
5//! Example: use 4-space indentation and a custom anchor naming scheme.
6//!
7//! ```rust
8//! use serde::Serialize;
9//!
10//! #[derive(Serialize)]
11//! struct Item { a: i32, b: bool }
12//!
13//! let mut buf = String::new();
14//! let opts = serde_saphyr::ser_options! {
15//!     indent_step: 4,
16//!     anchor_generator: Some(|id| format!("id{}/", id)),
17//! };
18//! serde_saphyr::to_fmt_writer_with_options(&mut buf, &Item { a: 1, b: true }, opts).unwrap();
19//! assert!(buf.contains("a: 1"));
20//! ```
21
22use crate::ser_error::Error;
23
24/// Placement style for comments emitted by [`crate::Commented`].
25///
26/// Requires the `comments` feature, which is enabled by default.
27#[non_exhaustive]
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29#[cfg(feature = "comments")]
30pub enum CommentPosition {
31    /// Emit the comment inline on the right side from the item it describes (default)
32    Inline,
33    /// Emit the comment above the item it describes
34    Above,
35}
36
37/// Serializer options for YAML emission.
38///
39/// This struct controls various aspects of YAML serialization, such as indentation,
40/// anchor generation, and scalar styles.
41///
42/// Construct `SerializerOptions` using the [`ser_options!`](crate::ser_options!)
43/// macro to ensure compatibility with future updates.
44///
45/// ```rust
46/// use serde::Serialize;
47/// use serde_saphyr::{ser_options, to_string_with_options};
48///
49/// #[derive(Serialize)]
50/// struct Config {
51///     name: String,
52///     values: Vec<i32>,
53/// }
54///
55/// let config = Config {
56///     name: "test".to_string(),
57///     values: vec![1, 2, 3],
58/// };
59///
60/// // Use 4-space indentation and quote all strings
61/// let options = ser_options! {
62///     indent_step: 4,
63///     quote_all: true,
64/// };
65///
66/// let yaml = to_string_with_options(&config, options).unwrap();
67/// ```
68#[non_exhaustive]
69#[derive(Clone, Debug)]
70pub struct SerializerOptions {
71    /// If true, empty maps are emitted as braces {} and empty lists as [] (this is the default).
72    /// This form is valid YAML, distinguishes empty collections from null, and may be easier
73    /// for a human to read.
74    pub empty_as_braces: bool,
75    /// Number of spaces to indent per nesting level when emitting block-style collections (2 by default).
76    /// Values must be in `1..=64`.
77    pub indent_step: usize,
78    /// When enabled, emit list items with a more compact indentation style. On by default.
79    /// ```yaml
80    ///       containers:
81    ///       - env:
82    ///         - name: METHOD
83    ///           value: WATCH
84    /// ```
85    ///
86    /// Compared to a more expanded indentation style:
87    ///
88    /// ```yaml
89    ///       containers:
90    ///         - env:
91    ///             - name: METHOD
92    ///               value: WATCH
93    /// ```
94    pub compact_list_indent: bool,
95    /// Optional custom anchor-name generator.
96    ///
97    /// Receives a monotonically increasing `usize` id (starting at 1) and returns the
98    /// anchor name to emit. If `None`, the built-in generator yields names like `a1`, `a2`, ...
99    /// Generated names must be 1 to 256 bytes and cannot contain whitespace, control characters,
100    /// or the flow punctuation `[`, `]`, `{`, `}`, or `,`; unsupported names produce a
101    /// serialization error. The generator remains responsible for returning unique names.
102    pub anchor_generator: Option<fn(usize) -> String>,
103    /// Threshold for block-string wrappers ([`crate::LitStr`]/[`crate::FoldStr`] and owned variants
104    /// [`crate::LitString`]/[`crate::FoldString`]).
105    ///
106    /// If the string contains a newline, block style is always used. Otherwise, when the
107    /// string is single-line and its length is strictly less than this threshold, the
108    /// serializer emits a normal YAML scalar (no block style). Longer strings use block
109    /// styles `|` or `>` depending on the wrapper. See the type docs for
110    /// [`crate::LitStr`], [`crate::FoldStr`], [`crate::LitString`] and [`crate::FoldString`] for
111    /// examples.
112    pub min_fold_chars: usize,
113    /// Maximum width (in characters) for lines in folded block scalars (`>`).
114    ///
115    /// Lines are wrapped **only** at whitespace so that each emitted line is at most
116    /// this many characters long (excluding indentation). If no whitespace is present
117    /// within the limit (e.g., a single long token), the line is emitted unwrapped
118    /// to preserve round-trip correctness: YAML folded scalars typically fold inserted
119    /// newlines back as spaces when parsing. Default: 80.
120    pub folded_wrap_chars: usize,
121    /// When enabled, serialize simple enums that become a single scalar (unit variants)
122    /// using YAML tags, e.g. `!!Enum Variant` instead of a plain scalar `Variant`.
123    /// Deserializer does not need this setting as both cases will be understood. Off by default.
124    pub tagged_enums: bool,
125
126    /// When enabled, strings containing more than `folded_wrap_chars` (80 by default) are written
127    /// in folded block scalar style (`>`), and strings containing newlines are written in
128    /// literal block scalar style (`|`), selecting chomping based on the number of trailing empty lines.
129    /// On by default.
130    pub prefer_block_scalars: bool,
131
132    /// When enabled, quote all string scalars. Uses single quotes by default,
133    /// but switches to double quotes when the string contains escape sequences
134    /// (control characters like `\n`, `\t`, `\r`, backslash) or single quotes.
135    /// Disables block scalar styles (`|` and `>`) for quoted strings when active.
136    /// Off by default.
137    pub quote_all: bool,
138
139    /// Controls where [`crate::Commented`] comments are emitted in block style.
140    ///
141    /// [`CommentPosition::Inline`] preserves the existing `value # comment` behavior for
142    /// scalars and aliases. [`CommentPosition::Above`] emits the comment on its own line
143    /// immediately before the wrapped value. Comments remain suppressed in flow-style
144    /// collections in both modes.
145    /// Available with the `comments` feature, which is enabled by default.
146    #[cfg(feature = "comments")]
147    pub comment_position: CommentPosition,
148
149    /// When enabled, emit `%YAML 1.2` and the required document start marker
150    /// at the beginning of the document, and use YAML 1.2 rules for certain
151    /// compatibility heuristics. Set [`no_lang_directive`](Self::no_lang_directive)
152    /// to suppress the directive and its document start marker while keeping
153    /// these heuristics.
154    ///
155    /// With the default `false`, strings matching YAML 1.1 numeric, boolean,
156    /// null, timestamp, and reserved-token spellings are quoted to preserve their
157    /// type across readers. With `true`, YAML 1.1-specific quoting checks are
158    /// disabled, including boolean spellings like `yes`/`no`/`on`/`off`/`y`/`n`,
159    /// sexagesimal numbers, and timestamps. YAML syntax safety checks still apply.
160    /// Default: false.
161    pub yaml_12: bool,
162
163    /// Suppress the `%YAML 1.2` directive and its leading `---` document start
164    /// marker when [`yaml_12`](Self::yaml_12) is enabled, without changing string
165    /// quoting heuristics. Document separators between multiple documents are
166    /// still emitted. Has no effect when `yaml_12` is false. Default: false.
167    pub no_lang_directive: bool,
168}
169
170// Below this length, block-string wrappers serialize as regular scalars
171// instead of YAML block styles. This keeps short values compact.
172pub(crate) const MIN_FOLD_CHARS: usize = 32;
173/// Maximum width (in characters) for lines inside folded block scalars.
174/// Lines will be wrapped at whitespace so that each emitted line is at most
175/// this many characters long (excluding indentation). If no whitespace is
176/// available within the limit, the line is not wrapped.
177pub(crate) const FOLDED_WRAP_CHARS: usize = 80;
178
179impl SerializerOptions {
180    // Keep this value in sync with the literal compile-time check in `ser_options!`.
181    pub(crate) const MAX_INDENT_STEP: usize = 64;
182
183    pub(crate) fn consistent(&self) -> Result<(), Error> {
184        if self.indent_step == 0 || self.indent_step > Self::MAX_INDENT_STEP {
185            return Err(Error::InvalidOptions(format!(
186                "indent_step must be in 1..={}",
187                Self::MAX_INDENT_STEP
188            )));
189        }
190        Ok(())
191    }
192}
193
194impl Default for SerializerOptions {
195    fn default() -> Self {
196        // Defaults mirror internal constants used by the serializer.
197        Self {
198            indent_step: 2,
199            compact_list_indent: true,
200            anchor_generator: None,
201            min_fold_chars: MIN_FOLD_CHARS,
202            folded_wrap_chars: FOLDED_WRAP_CHARS,
203            tagged_enums: false,
204            empty_as_braces: true,
205            prefer_block_scalars: true,
206            quote_all: false,
207            #[cfg(feature = "comments")]
208            comment_position: CommentPosition::Inline,
209            yaml_12: false,
210            no_lang_directive: false,
211        }
212    }
213}