Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. src
  5. pw_format/format_string.rs

pw_format/
format_string.rs

1// Copyright 2023 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use core::convert::Infallible;
16use core::iter::Peekable;
17use core::marker::PhantomData;
18use std::borrow::Cow;
19use std::collections::HashSet;
20
21#[cfg(feature = "proc_macro")]
22use quote::{quote, ToTokens};
23
24mod float;
25mod integer;
26mod padding;
27mod platform;
28mod text;
29
30use self::float::format_float;
31use self::integer::{format_int, format_ptr, format_uint};
32pub use self::platform::{
33    Ilp32Platform, Llp64Platform, Lp64Platform, PlatformTypes, PointerInt, SignedInt, UnsignedInt,
34};
35use self::text::{format_char, format_str};
36use crate::{core_fmt, printf};
37
38/// Maximum allowed minimum field width or precision (`65,536`) when
39/// formatting values at runtime.
40///
41/// Bounding width and precision specifier counts prevents corrupted or
42/// untrusted arguments (such as wire varints in `pw_tokenizer`) or malformed
43/// format strings from triggering multi-GiB heap allocations.
44pub const MAX_FIELD_LEN: u32 = 0x0001_0000;
45
46/// Primitive type of a conversion (integer, float, string, etc.)
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum Primitive {
49    /// Signed integer primitive.
50    Integer,
51
52    /// Unsigned integer primitive.
53    Unsigned,
54
55    /// Floating point primitive.
56    Float,
57
58    /// String primitive.
59    String,
60
61    /// Character primitive.
62    Character,
63
64    /// Pointer primitive.
65    Pointer,
66
67    /// Dynamically typed.
68    Dynamic,
69}
70
71/// The abstract formatting style for a conversion.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73pub enum Style {
74    /// No style specified, use defaults.
75    None,
76
77    /// Octal rendering (i.e. "%o" or "{:o}").
78    Octal,
79
80    /// Hexadecimal rendering (i.e. "%x" or "{:x}").
81    Hex,
82
83    /// Upper case hexadecimal rendering (i.e. "%X" or "{:X}").
84    UpperHex,
85
86    /// Exponential rendering (i.e. "%e" or "{:e}").
87    Exponential,
88
89    /// Upper case exponential rendering (i.e. "%E" or "{:E}".
90    UpperExponential,
91
92    /// Compact shortest floating point representation (i.e. "%g" or "{:g}").
93    General,
94
95    /// Upper case compact shortest floating point representation (i.e. "%G" or "{:G}").
96    UpperGeneral,
97
98    /// Hexadecimal floating point representation (i.e. "%a" or "{:a}").
99    HexFloat,
100
101    /// Upper case hexadecimal floating point representation (i.e. "%A" or "{:A}").
102    UpperHexFloat,
103
104    /// Upper case floating point representation (i.e. "%F" or "{:F}").
105    Upper,
106
107    /// Pointer type rendering (i.e. "%p" or "{:p}").
108    Pointer,
109
110    /// `core::fmt`'s `{:?}`
111    Debug,
112
113    /// `core::fmt`'s `{:x?}`
114    HexDebug,
115
116    /// `core::fmt`'s `{:X?}`
117    UpperHexDebug,
118
119    /// Unsupported binary rendering
120    ///
121    /// This variant exists so that the proc macros can give useful error
122    /// messages.
123    Binary,
124}
125
126/// Implemented for testing through the pw_format_test_macros crate.
127#[cfg(feature = "proc_macro")]
128impl ToTokens for Style {
129    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
130        let new_tokens = match self {
131            Style::None => quote!(pw_format::Style::None),
132            Style::Octal => quote!(pw_format::Style::Octal),
133            Style::Hex => quote!(pw_format::Style::Hex),
134            Style::UpperHex => quote!(pw_format::Style::UpperHex),
135            Style::Exponential => quote!(pw_format::Style::Exponential),
136            Style::UpperExponential => quote!(pw_format::Style::UpperExponential),
137            Style::General => quote!(pw_format::Style::General),
138            Style::UpperGeneral => quote!(pw_format::Style::UpperGeneral),
139            Style::HexFloat => quote!(pw_format::Style::HexFloat),
140            Style::UpperHexFloat => quote!(pw_format::Style::UpperHexFloat),
141            Style::Upper => quote!(pw_format::Style::Upper),
142            Style::Debug => quote!(pw_format::Style::Debug),
143            Style::HexDebug => quote!(pw_format::Style::HexDebug),
144            Style::UpperHexDebug => quote!(pw_format::Style::UpperHexDebug),
145            Style::Pointer => quote!(pw_format::Style::Pointer),
146            Style::Binary => quote!(pw_format::Style::Binary),
147        };
148        new_tokens.to_tokens(tokens);
149    }
150}
151
152/// A printf flag (the '+' in %+d).
153#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
154pub enum Flag {
155    /// `-`
156    LeftJustify,
157
158    /// `+`
159    ForceSign,
160
161    /// ` `
162    SpaceSign,
163
164    /// `#`
165    AlternateSyntax,
166
167    /// `0`
168    LeadingZeros,
169}
170
171/// A printf minimum field width (the 5 in %5d).
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum MinFieldWidth {
174    /// No field width specified.
175    None,
176
177    /// Fixed field width.
178    Fixed(u32),
179
180    /// Variable field width passed as an argument (i.e. %*d).
181    Variable,
182}
183
184/// A printf precision (the .5 in %.5d).
185///
186/// For string conversions (%s) this is treated as the maximum number of
187/// bytes of the string to output.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub enum Precision {
190    /// No precision specified.
191    None,
192
193    /// Fixed precision.
194    Fixed(u32),
195
196    /// Variable precision passed as an argument (i.e. %.*f).
197    Variable,
198}
199
200impl Precision {
201    /// Returns the fixed precision value if present, or None otherwise.
202    #[must_use]
203    pub const fn to_fixed(self) -> Option<u32> {
204        match self {
205            Self::Fixed(p) => Some(p),
206            _ => None,
207        }
208    }
209}
210
211/// A printf length (the l in %ld).
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub enum Length {
214    /// `hh`
215    Char,
216
217    /// `h`
218    Short,
219
220    /// `l`
221    Long,
222
223    /// `ll`
224    LongLong,
225
226    /// `L`
227    LongDouble,
228
229    /// `j`
230    IntMax,
231
232    /// `z`
233    Size,
234
235    /// `t`
236    PointerDiff,
237}
238
239impl Length {
240    /// Returns the length modifier string (e.g., `"hh"`, `"l"`).
241    #[must_use]
242    pub const fn as_str(&self) -> &'static str {
243        match self {
244            Self::Char => "hh",
245            Self::Short => "h",
246            Self::Long => "l",
247            Self::LongLong => "ll",
248            Self::LongDouble => "L",
249            Self::IntMax => "j",
250            Self::Size => "z",
251            Self::PointerDiff => "t",
252        }
253    }
254}
255
256/// A core::fmt alignment spec.
257#[derive(Clone, Copy, Debug, PartialEq, Eq)]
258pub enum Alignment {
259    /// No alignment
260    None,
261
262    /// Left alignment (`<`)
263    Left,
264
265    /// Center alignment (`^`)
266    Center,
267
268    /// Right alignment (`>`)
269    Right,
270}
271
272/// An argument in a core::fmt style alignment spec.
273///
274/// i.e. the var_name in `{var_name:#0x}`
275#[derive(Clone, Debug, PartialEq, Eq)]
276pub enum Argument {
277    /// No argument
278    None,
279
280    /// A positional argument (i.e. `{0}`).
281    Positional(usize),
282
283    /// A named argument (i.e. `{var_name}`).
284    Named(String),
285}
286
287/// A printf conversion specification aka a % clause.
288#[derive(Clone, Debug, PartialEq, Eq)]
289pub struct ConversionSpec {
290    /// ConversionSpec's argument.
291    pub argument: Argument,
292    /// ConversionSpec's fill character.
293    pub fill: char,
294    /// ConversionSpec's field alignment.
295    pub alignment: Alignment,
296    /// ConversionSpec's set of [Flag]s.
297    pub flags: HashSet<Flag>,
298    /// ConversionSpec's minimum field width argument.
299    pub min_field_width: MinFieldWidth,
300    /// ConversionSpec's [Precision] argument.
301    pub precision: Precision,
302    /// ConversionSpec's [Length] argument.
303    pub length: Option<Length>,
304    /// ConversionSpec's [Primitive].
305    pub primitive: Primitive,
306    /// ConversionSpec's [Style].
307    pub style: Style,
308}
309
310impl Default for ConversionSpec {
311    fn default() -> Self {
312        Self {
313            argument: Argument::None,
314            fill: ' ',
315            alignment: Alignment::None,
316            flags: HashSet::new(),
317            min_field_width: MinFieldWidth::None,
318            precision: Precision::None,
319            length: None,
320            primitive: Primitive::Dynamic,
321            style: Style::None,
322        }
323    }
324}
325
326impl ConversionSpec {
327    /// Returns `true` if fixed width and precision do not exceed
328    /// [`MAX_FIELD_LEN`].
329    #[must_use]
330    pub const fn has_valid_field_lengths(&self) -> bool {
331        !matches!(self.min_field_width, MinFieldWidth::Fixed(w) if w > MAX_FIELD_LEN)
332            && !matches!(self.precision, Precision::Fixed(p) if p > MAX_FIELD_LEN)
333    }
334
335    /// Reconstructs the conversion specifier back to its printf format string representation (e.g., `%+05.2ld`).
336    #[must_use]
337    pub fn to_printf(&self) -> String {
338        let mut s = String::from("%");
339        if self.flags.contains(&Flag::LeftJustify) {
340            s.push('-');
341        }
342        if self.flags.contains(&Flag::ForceSign) {
343            s.push('+');
344        }
345        if self.flags.contains(&Flag::SpaceSign) {
346            s.push(' ');
347        }
348        if self.flags.contains(&Flag::AlternateSyntax) {
349            s.push('#');
350        }
351        if self.flags.contains(&Flag::LeadingZeros) {
352            s.push('0');
353        }
354
355        match self.min_field_width {
356            MinFieldWidth::None => {}
357            MinFieldWidth::Fixed(w) => s.push_str(&w.to_string()),
358            MinFieldWidth::Variable => s.push('*'),
359        }
360
361        match self.precision {
362            Precision::None => {}
363            Precision::Fixed(p) => s.push_str(&format!(".{p}")),
364            Precision::Variable => s.push_str(".*"),
365        }
366
367        if let Some(length) = self.length {
368            s.push_str(length.as_str());
369        }
370
371        let type_char = match (self.primitive, self.style) {
372            (Primitive::Integer, _) => 'd',
373            (Primitive::Unsigned, Style::Octal) => 'o',
374            (Primitive::Unsigned, Style::Hex) => 'x',
375            (Primitive::Unsigned, Style::UpperHex) => 'X',
376            (Primitive::Unsigned, _) => 'u',
377            (Primitive::Float, Style::Exponential) => 'e',
378            (Primitive::Float, Style::UpperExponential) => 'E',
379            (Primitive::Float, Style::General) => 'g',
380            (Primitive::Float, Style::UpperGeneral) => 'G',
381            (Primitive::Float, Style::HexFloat) => 'a',
382            (Primitive::Float, Style::UpperHexFloat) => 'A',
383            (Primitive::Float, Style::Upper) => 'F',
384            (Primitive::Float, _) => 'f',
385            (Primitive::Character, _) => 'c',
386            (Primitive::String, _) => 's',
387            (Primitive::Pointer, _) => 'p',
388            (Primitive::Dynamic, _) => 'v',
389        };
390        s.push(type_char);
391        s
392    }
393}
394
395/// A single (non-bit-field) domain specification for a nested token.
396#[derive(Clone, Debug, Default, PartialEq, Eq)]
397pub enum SimpleNestedDomain {
398    /// Default / not-specified domain (e.g. `$#%08x` or `${}#%08x`).
399    #[default]
400    Default,
401
402    /// A literal domain string (e.g. `${domain}#%08x`).
403    Literal(String),
404
405    /// A literal token that gives the domain string (e.g. `${$#01234567}#%08x` or `${${domain}#01234567}#%08x`).
406    LiteralToken {
407        /// Optional domain for looking up the token (empty for default domain).
408        domain: String,
409        /// The literal token value.
410        token: u32,
411    },
412
413    /// A variable domain token requiring a read from the argument data (e.g. `${$#%08x}#%08x` or `${${domain}#%08x}#%08x`).
414    VariableToken {
415        /// Optional domain for looking up the variable token (empty for default domain).
416        domain: String,
417    },
418}
419
420/// Domain specification for a nested token.
421#[derive(Clone, Debug, Default, PartialEq, Eq)]
422pub enum NestedDomain {
423    /// Default / not-specified domain (e.g. `$#%08x` or `${}#%08x`).
424    #[default]
425    Default,
426
427    /// A literal domain string (e.g. `${domain}#%08x`).
428    Literal(String),
429
430    /// A literal token that gives the domain string (e.g. `${$#01234567}#%08x` or `${${domain}#01234567}#%08x`).
431    LiteralToken {
432        /// Optional domain for looking up the token (empty for default domain).
433        domain: String,
434        /// The literal token value.
435        token: u32,
436    },
437
438    /// A variable domain token requiring a read from the argument data (e.g. `${$#%08x}#%08x` or `${${domain}#%08x}#%08x`).
439    VariableToken {
440        /// Optional domain for looking up the variable token (empty for default domain).
441        domain: String,
442    },
443
444    /// A bit-field domain splitting the 32-bit token between low and high fields
445    /// (e.g. `${low/5,high}#%08x`).
446    BitField {
447        /// Domain for the low `low_bits` bits of the token.
448        low: SimpleNestedDomain,
449        /// Number of bits in the low field (`0..=32`).
450        low_bits: u8,
451        /// Domain for the remaining high `32 - low_bits` bits of the token.
452        high: SimpleNestedDomain,
453    },
454}
455
456impl NestedDomain {
457    /// Returns `true` if resolving this domain consumes a runtime token argument.
458    #[must_use]
459    pub const fn has_variable_token(&self) -> bool {
460        match self {
461            Self::VariableToken { .. } => true,
462            Self::BitField { low, high, .. } => {
463                matches!(low, SimpleNestedDomain::VariableToken { .. })
464                    || matches!(high, SimpleNestedDomain::VariableToken { .. })
465            }
466            Self::Default | Self::Literal(_) | Self::LiteralToken { .. } => false,
467        }
468    }
469
470    /// Returns `true` if this domain contains a literal nested token (`LiteralToken`).
471    #[must_use]
472    pub const fn has_literal_token(&self) -> bool {
473        match self {
474            Self::LiteralToken { .. } => true,
475            Self::BitField { low, high, .. } => {
476                matches!(low, SimpleNestedDomain::LiteralToken { .. })
477                    || matches!(high, SimpleNestedDomain::LiteralToken { .. })
478            }
479            Self::Default | Self::Literal(_) | Self::VariableToken { .. } => false,
480        }
481    }
482}
483
484impl From<SimpleNestedDomain> for NestedDomain {
485    fn from(domain: SimpleNestedDomain) -> Self {
486        match domain {
487            SimpleNestedDomain::Default => Self::Default,
488            SimpleNestedDomain::Literal(name) => Self::Literal(name),
489            SimpleNestedDomain::LiteralToken { domain, token } => {
490                Self::LiteralToken { domain, token }
491            }
492            SimpleNestedDomain::VariableToken { domain } => Self::VariableToken { domain },
493        }
494    }
495}
496
497/// Token specification for a nested token.
498#[derive(Clone, Copy, Debug, PartialEq, Eq)]
499pub enum NestedTokenValue {
500    /// A literal token value (e.g. `$#01234567` or `$10#0000000010`).
501    Literal(u32),
502
503    /// A variable token requiring a read from the argument data (`%08x`, `%010d`, or `%010u`).
504    Variable,
505}
506
507/// A nested token specification (e.g. `$#%08x`, `${domain}#%08x`, `${$#%08x}#%08x`).
508#[derive(Clone, Debug, PartialEq, Eq)]
509pub struct NestedTokenSpec {
510    /// Prefix character, typically `'$'`.
511    pub prefix: char,
512
513    /// Domain specification.
514    pub domain: NestedDomain,
515
516    /// The token value specification.
517    pub token: NestedTokenValue,
518
519    /// Additional token argument data decoded from base64 (`None` if not base64).
520    pub token_data: Option<Vec<u8>>,
521
522    /// The raw format string slice representing this nested token.
523    ///
524    /// Preserved verbatim because parsing SEED-0105 nested tokens into
525    /// `(prefix, domain, token)` is intentionally lossy across:
526    /// - stripped whitespace inside `{ ... }` domain braces (e.g. `${ my domain }#...`
527    ///   and `${}#%08x` vs `$#%08x`),
528    /// - explicit radix specifiers (`$10#...`, `$16#...`, `$64#...`),
529    /// - hex letter casing (`$#DEADBEEF` vs `$#deadbeef`), and
530    /// - Base64 nested tokens with embedded binary argument payloads (`$AQIDBA==`).
531    ///
532    /// Retaining the verbatim source slice ensures fallback formatting when a
533    /// nested token cannot be decoded reproduces the exact original text.
534    pub raw: String,
535}
536
537impl Default for NestedTokenSpec {
538    fn default() -> Self {
539        Self {
540            prefix: FormatString::DEFAULT_NESTED_PREFIX,
541            domain: NestedDomain::Default,
542            token: NestedTokenValue::Variable,
543            token_data: None,
544            raw: String::new(),
545        }
546    }
547}
548
549impl NestedTokenSpec {
550    /// Returns the additional token argument data as an optional byte slice.
551    #[must_use]
552    pub fn token_data(&self) -> Option<&[u8]> {
553        self.token_data.as_deref()
554    }
555
556    /// Returns the raw format string slice for this nested token.
557    #[must_use]
558    pub fn raw(&self) -> &str {
559        &self.raw
560    }
561
562    /// Reconstructs the nested token specification back to its printf format string representation.
563    #[must_use]
564    pub fn to_printf(&self) -> String {
565        self.raw.clone()
566    }
567}
568
569/// A fragment of a printf format string.
570#[derive(Clone, Debug, PartialEq, Eq)]
571pub enum FormatFragment {
572    /// A literal string value.
573    Literal(String),
574
575    /// A conversion specification (i.e. %d).
576    Conversion(ConversionSpec),
577
578    /// A nested token specification (i.e. $#%08x or ${domain}#%08x).
579    NestedToken(NestedTokenSpec),
580}
581
582impl FormatFragment {
583    /// Try to append `fragment` to `self`.
584    ///
585    /// Returns `None` if the appending succeeds and `Some<fragment>` if it fails.
586    fn try_append<'a>(&mut self, fragment: &'a FormatFragment) -> Option<&'a FormatFragment> {
587        let Self::Literal(literal_fragment) = &fragment else {
588            return Some(fragment);
589        };
590
591        let Self::Literal(literal_self) = self else {
592            return Some(fragment);
593        };
594
595        literal_self.push_str(literal_fragment);
596
597        None
598    }
599}
600
601/// Representation of a decoded argument.
602#[derive(Debug, Clone, PartialEq)]
603pub enum Arg {
604    /// Signed integer.
605    Int(i64),
606    /// Unsigned integer.
607    Uint(u64),
608    /// Floating point number.
609    Float(f64),
610    /// String.
611    Str(String),
612    /// Character.
613    Char(char),
614    /// Pointer.
615    Ptr(usize),
616}
617
618/// The style of formatting to apply (influences defaults).
619#[derive(Debug, Clone, Copy, PartialEq, Eq)]
620pub enum FormatStyle {
621    /// Printf style defaults (e.g. %f defaults to precision 6).
622    Printf,
623    /// Core::fmt style defaults.
624    CoreFmt,
625}
626
627/// A trait for formatting conversion specifiers that failed, were skipped, or were missing.
628pub trait FormatError {
629    /// The domain-specific error type.
630    type Error;
631
632    /// Renders a conversion specifier that failed with a domain-specific error.
633    fn format_error(&self, spec: &ConversionSpec, error: &Self::Error) -> String;
634
635    /// Renders a conversion specifier that was missing from the supplied arguments.
636    fn format_missing(&self, spec: &ConversionSpec) -> String;
637
638    /// Renders a conversion specifier that decoded successfully but failed to format (type mismatch).
639    fn format_type_error(&self, spec: &ConversionSpec, arg: &Arg) -> String;
640
641    /// Renders a nested token specification that failed with a domain-specific error.
642    fn format_nested_token_error(&self, spec: &NestedTokenSpec, _error: &Self::Error) -> String {
643        spec.to_printf()
644    }
645
646    /// Renders a nested token specification that was missing from the supplied arguments.
647    fn format_nested_token_missing(&self, spec: &NestedTokenSpec) -> String {
648        spec.to_printf()
649    }
650
651    /// Renders a nested token specification that decoded successfully but failed to format (type mismatch).
652    fn format_nested_token_type_error(&self, spec: &NestedTokenSpec, _arg: &Arg) -> String {
653        spec.to_printf()
654    }
655}
656
657/// Formatter that retains the original conversion specifier when formatting fails,
658/// parameterizing over `std::convert::Infallible` (which has no error state).
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660struct DefaultFormatter;
661
662impl FormatError for DefaultFormatter {
663    type Error = core::convert::Infallible;
664
665    fn format_error(&self, spec: &ConversionSpec, _error: &core::convert::Infallible) -> String {
666        spec.to_printf()
667    }
668    fn format_missing(&self, spec: &ConversionSpec) -> String {
669        spec.to_printf()
670    }
671    fn format_type_error(&self, spec: &ConversionSpec, _arg: &Arg) -> String {
672        spec.to_printf()
673    }
674}
675
676/// A parsed format string.
677#[derive(Clone, Debug, PartialEq, Eq)]
678pub struct FormatString {
679    /// The [FormatFragment]s that comprise the [FormatString].
680    pub fragments: Vec<FormatFragment>,
681}
682
683impl FormatString {
684    /// Formats a parsed format string with provided arguments using the specified
685    /// producing platform's integer and pointer widths (`P: PlatformTypes`).
686    #[must_use]
687    pub fn format_for_platform<P: PlatformTypes>(
688        &self,
689        args: &[Arg],
690        style: FormatStyle,
691    ) -> String {
692        let result_args: Vec<Result<Arg, Infallible>> =
693            args.iter().map(|arg| Ok(arg.clone())).collect();
694        self.format_with_errors_for_platform::<P, _>(&result_args, style, &DefaultFormatter)
695    }
696
697    /// Formats a parsed format string with provided arguments.
698    #[must_use]
699    pub fn format(&self, args: &[Arg], style: FormatStyle) -> String {
700        self.format_for_platform::<Ilp32Platform>(args, style)
701    }
702
703    /// Formats a parsed format string with the provided argument states (`Result<Arg, FE::Error>`),
704    /// delegating formatting of any failures, missing arguments, or type mismatches
705    /// to the provided `FormatError` implementation.
706    pub fn format_with_errors<FE: FormatError>(
707        &self,
708        args: &[Result<Arg, FE::Error>],
709        style: FormatStyle,
710        error_formatter: &FE,
711    ) -> String {
712        self.format_with_errors_for_platform::<Ilp32Platform, FE>(args, style, error_formatter)
713    }
714
715    /// Formats a parsed format string with the provided argument states (`Result<Arg, FE::Error>`)
716    /// using the specified producing platform's integer and pointer widths (`P: PlatformTypes`).
717    pub fn format_with_errors_for_platform<P: PlatformTypes, FE: FormatError>(
718        &self,
719        args: &[Result<Arg, FE::Error>],
720        style: FormatStyle,
721        error_formatter: &FE,
722    ) -> String {
723        let mut output = String::new();
724        let mut session =
725            FormatSession::<_, _, P>::new(args.iter(), style, error_formatter, &mut output);
726
727        for fragment in &self.fragments {
728            session.format_fragment(fragment);
729        }
730
731        output
732    }
733
734    /// Default prefix character for nested token specifiers.
735    pub const DEFAULT_NESTED_PREFIX: char = '$';
736
737    /// Parses a printf style format string using the default nested token prefix ('$').
738    pub fn parse_printf(s: &str) -> Result<Self, String> {
739        Self::parse_printf_with_prefix(s, Self::DEFAULT_NESTED_PREFIX)
740    }
741
742    /// Parses a printf style format string using a specified nested token prefix.
743    pub fn parse_printf_with_prefix(s: &str, prefix: char) -> Result<Self, String> {
744        Self::parse_printf_opt_prefix(s, Some(prefix))
745    }
746
747    /// Parses a pure printf style format string without nested token parsing.
748    pub fn parse_pure_printf(s: &str) -> Result<Self, String> {
749        Self::parse_printf_opt_prefix(s, None)
750    }
751
752    fn parse_printf_opt_prefix(s: &str, prefix: Option<char>) -> Result<Self, String> {
753        // TODO: b/281858500 - Add better errors to failed parses.
754        let (rest, result) = printf::format_string(s, prefix)
755            .map_err(|e| format!("Failed to parse format string \"{s}\": {e}"))?;
756
757        // If the parser did not consume all the input, return an error.
758        if !rest.is_empty() {
759            return Err(format!(
760                "Failed to parse format string fragment \"{rest}\" in \"{s}\""
761            ));
762        }
763
764        Ok(result)
765    }
766
767    /// Parses a printf style format string infallibly using the default nested
768    /// token prefix (`'$'`), treating any invalid or incomplete `%` sequence as
769    /// a literal `'%'` and continuing to parse subsequent conversion specifiers
770    /// and nested tokens.
771    #[must_use]
772    pub fn parse_printf_lossy(s: &str) -> Self {
773        Self::parse_printf_lossy_with_prefix(s, Self::DEFAULT_NESTED_PREFIX)
774    }
775
776    /// Parses a printf style format string infallibly using a specified nested
777    /// token prefix, treating any invalid or incomplete `%` sequence as a
778    /// literal `'%'` and continuing to parse subsequent conversion specifiers
779    /// and nested tokens.
780    #[must_use]
781    pub fn parse_printf_lossy_with_prefix(s: &str, prefix: char) -> Self {
782        printf::format_string_lossy(s, Some(prefix))
783    }
784
785    /// Parses plain text containing nested token specifiers using the default prefix (`'$'`),
786    /// treating `%` characters as literal text rather than conversion specifiers.
787    #[must_use]
788    pub fn parse_nested_tokens(s: &str) -> Self {
789        Self::parse_nested_tokens_with_prefix(s, Self::DEFAULT_NESTED_PREFIX)
790    }
791
792    /// Parses plain text containing nested token specifiers using a specified prefix,
793    /// treating `%` characters as literal text rather than conversion specifiers.
794    #[must_use]
795    pub fn parse_nested_tokens_with_prefix(s: &str, prefix: char) -> Self {
796        let (_, result) = printf::nested_tokens_string(s, prefix)
797            .expect("nested_tokens_string is infallible on all UTF-8 inputs");
798        result
799    }
800
801    /// Parses a core::fmt style format string.
802    pub fn parse_core_fmt(s: &str) -> Result<Self, String> {
803        // TODO: b/281858500 - Add better errors to failed parses.
804        let (rest, result) = core_fmt::format_string(s)
805            .map_err(|e| format!("Failed to parse format string \"{s}\": {e}"))?;
806
807        // If the parser did not consume all the input, return an error.
808        if !rest.is_empty() {
809            return Err(format!(
810                "Failed to parse format string fragment \"{rest}\" in \"{s}\""
811            ));
812        }
813
814        Ok(result)
815    }
816
817    /// Creates a `FormatString` from a slice of fragments.
818    ///
819    /// The primary responsibility of this function is to merge literal
820    /// fragments.  Adjacent literal fragments occur when a parser parses
821    /// escape sequences.  Merging them here allows a
822    /// [`macros::FormatMacroGenerator`] to not worry about the escape codes.
823    pub(crate) fn from_fragments(fragments: &[FormatFragment]) -> Self {
824        Self {
825            fragments: fragments
826                .iter()
827                .fold(Vec::<_>::new(), |mut fragments, fragment| {
828                    // Collapse adjacent literal fragments.
829                    let Some(last) = fragments.last_mut() else {
830                        // If there are no accumulated fragments, add this one and return.
831                        fragments.push((*fragment).clone());
832                        return fragments;
833                    };
834                    if let Some(fragment) = last.try_append(fragment) {
835                        // If the fragments were able to append, no more work to do
836                        fragments.push((*fragment).clone());
837                    };
838                    fragments
839                }),
840        }
841    }
842}
843
844/// State for formatting a single [`FormatString`] with a sequence of arguments.
845///
846/// # Lifetimes
847///
848/// * `'a`: The lifetime of the decoded [`Arg`] items (and any decoding errors)
849///   yielded by the `args` iterator `I`.
850/// * `'b`: The lifetime of the borrowed error formatter (`error_formatter`) and
851///   the output string buffer (`output`) for the duration of the formatting
852///   session.
853struct FormatSession<'a, 'b, I, FE, P: PlatformTypes>
854where
855    I: Iterator<Item = &'a Result<Arg, FE::Error>>,
856    FE: FormatError,
857    FE::Error: 'a,
858{
859    /// Peekable iterator yielding references to decoded [`Arg`] results for each conversion.
860    args: Peekable<I>,
861    /// The formatting style ([`FormatStyle::Printf`] or [`FormatStyle::CoreFmt`]).
862    style: FormatStyle,
863    /// Formatter invoked to produce fallback text when an argument is missing,
864    /// fails to decode, or has a mismatched type.
865    error_formatter: &'b FE,
866    /// Destination string buffer where formatted fragments are appended.
867    output: &'b mut String,
868    /// Marker for the producing platform's native integer/pointer types.
869    _platform: PhantomData<P>,
870}
871
872impl<'a, 'b, I, FE, P: PlatformTypes> FormatSession<'a, 'b, I, FE, P>
873where
874    I: Iterator<Item = &'a Result<Arg, FE::Error>>,
875    FE: FormatError,
876    FE::Error: 'a,
877{
878    fn new(args: I, style: FormatStyle, error_formatter: &'b FE, output: &'b mut String) -> Self {
879        Self {
880            args: args.peekable(),
881            style,
882            error_formatter,
883            output,
884            _platform: PhantomData,
885        }
886    }
887
888    fn push_missing(&mut self, spec: &ConversionSpec) {
889        self.output
890            .push_str(&self.error_formatter.format_missing(spec));
891    }
892
893    fn push_error(&mut self, spec: &ConversionSpec, err: &FE::Error) {
894        self.output
895            .push_str(&self.error_formatter.format_error(spec, err));
896    }
897
898    fn push_type_error(&mut self, spec: &ConversionSpec, arg: &Arg) {
899        self.output
900            .push_str(&self.error_formatter.format_type_error(spec, arg));
901    }
902
903    // Only consume `Ok` slots so downstream `Err` markers (such as
904    // `TokenizerError::Skipped` after an aborted decode) stay intact.
905    fn drain_remaining_ok_args(&mut self, count: usize) {
906        for _ in 0..count {
907            if matches!(self.args.peek(), Some(Ok(_))) {
908                self.args.next();
909            } else {
910                break;
911            }
912        }
913    }
914
915    fn fail_dynamic_arg(&mut self, spec: &ConversionSpec, arg: &Arg, remaining_ok_slots: usize) {
916        self.push_type_error(spec, arg);
917        self.drain_remaining_ok_args(remaining_ok_slots);
918    }
919
920    fn next_arg(&mut self, spec: &ConversionSpec, remaining_ok_slots: usize) -> Option<&'a Arg> {
921        let Some(decoded) = self.args.next() else {
922            self.push_missing(spec);
923            return None;
924        };
925        match decoded {
926            Ok(arg) => Some(arg),
927            Err(err) => {
928                self.push_error(spec, err);
929                self.drain_remaining_ok_args(remaining_ok_slots);
930                None
931            }
932        }
933    }
934
935    fn format_fragment(&mut self, fragment: &FormatFragment) {
936        match fragment {
937            FormatFragment::Literal(s) => self.output.push_str(s),
938            FormatFragment::NestedToken(token_spec) => self.format_nested_token(token_spec),
939            FormatFragment::Conversion(spec) => self.format_conversion(spec),
940        }
941    }
942
943    fn format_nested_token(&mut self, token_spec: &NestedTokenSpec) {
944        let Some(decoded) = self.args.next() else {
945            self.output
946                .push_str(&self.error_formatter.format_nested_token_missing(token_spec));
947            return;
948        };
949
950        let arg = match decoded {
951            Ok(arg) => arg,
952            Err(err) => {
953                self.output.push_str(
954                    &self
955                        .error_formatter
956                        .format_nested_token_error(token_spec, err),
957                );
958                return;
959            }
960        };
961
962        if let Arg::Str(s) = arg {
963            self.output.push_str(s);
964        } else {
965            self.output.push_str(
966                &self
967                    .error_formatter
968                    .format_nested_token_type_error(token_spec, arg),
969            );
970        }
971    }
972
973    fn format_conversion(&mut self, spec: &ConversionSpec) {
974        let Some(effective_spec) = self.resolve_dynamic_spec(spec) else {
975            return;
976        };
977
978        let Some(arg) = self.next_arg(spec, 0) else {
979            return;
980        };
981
982        let initial_len = self.output.len();
983        if format_value::<P>(&effective_spec, arg, self.style, self.output).is_err() {
984            self.output.truncate(initial_len);
985            self.push_type_error(spec, arg);
986        }
987    }
988
989    fn resolve_dynamic_spec<'s>(
990        &mut self,
991        spec: &'s ConversionSpec,
992    ) -> Option<Cow<'s, ConversionSpec>> {
993        if spec.min_field_width != MinFieldWidth::Variable && spec.precision != Precision::Variable
994        {
995            return Some(Cow::Borrowed(spec));
996        }
997
998        let mut resolved = spec.clone();
999        resolved.min_field_width = self.resolve_dynamic_width(spec, &mut resolved.flags)?;
1000        if resolved.flags.contains(&Flag::LeftJustify) {
1001            resolved.alignment = Alignment::Left;
1002        }
1003        resolved.precision = self.resolve_dynamic_precision(spec)?;
1004        Some(Cow::Owned(resolved))
1005    }
1006
1007    fn resolve_dynamic_width(
1008        &mut self,
1009        spec: &ConversionSpec,
1010        flags: &mut HashSet<Flag>,
1011    ) -> Option<MinFieldWidth> {
1012        let MinFieldWidth::Variable = spec.min_field_width else {
1013            return Some(spec.min_field_width);
1014        };
1015        let remaining_slots = usize::from(spec.precision == Precision::Variable) + 1;
1016        let arg = self.next_arg(spec, remaining_slots)?;
1017        let (width, is_negative) = match arg {
1018            Arg::Int(val) => (validate_field_len(val.unsigned_abs()), *val < 0),
1019            Arg::Uint(val) => (validate_field_len(*val), false),
1020            _ => (None, false),
1021        };
1022        let Some(w) = width else {
1023            self.fail_dynamic_arg(spec, arg, remaining_slots);
1024            return None;
1025        };
1026        if is_negative {
1027            flags.insert(Flag::LeftJustify);
1028        }
1029        Some(MinFieldWidth::Fixed(w))
1030    }
1031
1032    fn resolve_dynamic_precision(&mut self, spec: &ConversionSpec) -> Option<Precision> {
1033        let Precision::Variable = spec.precision else {
1034            return Some(spec.precision);
1035        };
1036        let arg = self.next_arg(spec, 1)?;
1037        let resolved = match arg {
1038            // Per C99 §7.19.6.1p5, a negative 32-bit C `int` precision is treated
1039            // as omitted; values below `i32::MIN` are rejected as out of range.
1040            Arg::Int(val) if *val < 0 => i32::try_from(*val).ok().map(|_| Precision::None),
1041            Arg::Int(val) => validate_field_len(val.cast_unsigned()).map(Precision::Fixed),
1042            Arg::Uint(val) => validate_field_len(*val).map(Precision::Fixed),
1043            _ => None,
1044        };
1045        let Some(precision) = resolved else {
1046            self.fail_dynamic_arg(spec, arg, 1);
1047            return None;
1048        };
1049        Some(precision)
1050    }
1051}
1052
1053fn validate_field_len(val: u64) -> Option<u32> {
1054    u32::try_from(val).ok().filter(|&v| v <= MAX_FIELD_LEN)
1055}
1056
1057/// Errors that can occur when formatting an [`Arg`] for a [`ConversionSpec`].
1058#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1059pub enum FormatValueError {
1060    /// The conversion specifier and argument types are incompatible.
1061    MismatchedType,
1062
1063    /// The argument value exceeds the valid range for the conversion specifier
1064    /// or target platform type.
1065    ValueOutOfRange,
1066}
1067
1068fn format_value<P: PlatformTypes>(
1069    spec: &ConversionSpec,
1070    arg: &Arg,
1071    style: FormatStyle,
1072    output: &mut String,
1073) -> Result<(), FormatValueError> {
1074    if !spec.has_valid_field_lengths() {
1075        return Err(FormatValueError::ValueOutOfRange);
1076    }
1077
1078    match (spec.primitive, arg) {
1079        (Primitive::Integer, Arg::Int(v)) => format_int::<P>(*v, spec, style, output),
1080        (Primitive::Integer, Arg::Uint(v)) => format_int::<P>(v.cast_signed(), spec, style, output),
1081        (Primitive::Unsigned, Arg::Uint(v)) => format_uint::<P>(*v, spec, style, output),
1082        (Primitive::Unsigned, Arg::Int(v)) => {
1083            format_uint::<P>(v.cast_unsigned(), spec, style, output)
1084        }
1085        (Primitive::Float, Arg::Float(v)) => format_float(*v, spec, style, output),
1086        (Primitive::String, Arg::Str(v)) => format_str(v, spec, output),
1087        (Primitive::Character, Arg::Char(v)) => format_char(*v, spec, output),
1088
1089        // Note: For integer arguments (`Arg::Int` / `Arg::Uint`) in `128..=255`,
1090        // `u8... as char` maps to Latin-1 Unicode code points (`U+0080..=U+00FF`),
1091        // which encode as two-byte UTF-8 sequences in a Rust string.
1092        (Primitive::Character, Arg::Int(v)) => {
1093            let c = u8::try_from(*v).map_err(|_| FormatValueError::ValueOutOfRange)? as char;
1094            format_char(c, spec, output);
1095        }
1096        (Primitive::Character, Arg::Uint(v)) => {
1097            let c = u8::try_from(*v).map_err(|_| FormatValueError::ValueOutOfRange)? as char;
1098            format_char(c, spec, output);
1099        }
1100        (Primitive::Pointer, Arg::Ptr(v)) => {
1101            format_ptr(P::Pointer::ptr_from_usize(*v)?, spec, output)
1102        }
1103        (Primitive::Pointer, Arg::Uint(v)) => {
1104            format_ptr(P::Pointer::ptr_from_u64(*v), spec, output)
1105        }
1106        (Primitive::Pointer, Arg::Int(v)) => {
1107            format_ptr(P::Pointer::ptr_from_u64(v.cast_unsigned()), spec, output)
1108        }
1109        (Primitive::Dynamic, _) => format_dynamic::<P>(spec, arg, style, output)?,
1110        _ => return Err(FormatValueError::MismatchedType),
1111    }
1112    Ok(())
1113}
1114
1115fn format_dynamic<P: PlatformTypes>(
1116    spec: &ConversionSpec,
1117    arg: &Arg,
1118    style: FormatStyle,
1119    output: &mut String,
1120) -> Result<(), FormatValueError> {
1121    match arg {
1122        Arg::Int(v) => format_int::<P>(*v, spec, style, output),
1123        Arg::Uint(v) => format_uint::<P>(*v, spec, style, output),
1124        Arg::Float(v) => format_float(*v, spec, style, output),
1125        Arg::Str(v) => format_str(v, spec, output),
1126        Arg::Char(v) => format_char(*v, spec, output),
1127        Arg::Ptr(v) => format_ptr(P::Pointer::ptr_from_usize(*v)?, spec, output),
1128    }
1129    Ok(())
1130}