Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_format

Crate pw_format

Crate pw_format 

Source
Expand description

The pw_format crate provides format string parsing and formatting utilities to:

  • Parse and syntax-check format strings (printf and core::fmt).
  • Understand format string argument types at compile time in proc macros.
  • Format dynamic values according to format strings at runtime.

pw_format is written against std and is not intended to be used in an embedded on-device context. Some efficiency and memory is traded for a more expressive interface that exposes the format string’s syntax tree to the API client.

§Proc Macros

The macros module provides infrastructure for implementing proc macros that take format strings as arguments.

§Parsing Example

use pw_format::{
    Alignment, Argument, ConversionSpec, Flag, FormatFragment, FormatString,
    Length, MinFieldWidth, Precision, Primitive, Style,
};

let format_string =
  FormatString::parse_printf("long double %+ 4.2Lf is %-03hd%%.").unwrap();

assert_eq!(format_string, FormatString {
  fragments: vec![
      FormatFragment::Literal("long double ".to_string()),
      FormatFragment::Conversion(ConversionSpec {
          argument: Argument::None,
          fill: ' ',
          alignment: Alignment::None,
          flags: [Flag::ForceSign, Flag::SpaceSign].into_iter().collect(),
          min_field_width: MinFieldWidth::Fixed(4),
          precision: Precision::Fixed(2),
          length: Some(Length::LongDouble),
          primitive: Primitive::Float,
          style: Style::None,
      }),
      FormatFragment::Literal(" is ".to_string()),
      FormatFragment::Conversion(ConversionSpec {
          argument: Argument::None,
          fill: ' ',
          alignment: Alignment::Left,
          flags: [Flag::LeftJustify, Flag::LeadingZeros]
              .into_iter()
              .collect(),
          min_field_width: MinFieldWidth::Fixed(3),
          precision: Precision::None,
          length: Some(Length::Short),
          primitive: Primitive::Integer,
          style: Style::None,
      }),
      FormatFragment::Literal("%.".to_string()),
  ]
});

§Runtime Formatting Example

use pw_format::{Arg, FormatString, FormatStyle};

let fmt = FormatString::parse_printf("Hello %s, code: 0x%04x!").unwrap();
let output = fmt.format(
    &[Arg::Str("world".to_string()), Arg::Uint(42)],
    FormatStyle::Printf,
);
assert_eq!(output, "Hello world, code: 0x002a!");

§Error Formatting Example

When formatting strings with missing or mismatched arguments, custom error formatters implementing FormatError can be supplied:

use pw_format::{Arg, ConversionSpec, FormatError, FormatString, FormatStyle};

struct MyErrorFormatter;
impl FormatError for MyErrorFormatter {
    type Error = ();
    fn format_error(&self, spec: &ConversionSpec, _error: &()) -> String {
        format!("<[{} ERROR]>", spec.to_printf())
    }
    fn format_missing(&self, spec: &ConversionSpec) -> String {
        format!("<[{} MISSING]>", spec.to_printf())
    }
    fn format_type_error(&self, spec: &ConversionSpec, _arg: &Arg) -> String {
        format!("<[{} TYPE_ERROR]>", spec.to_printf())
    }
}

let fmt = FormatString::parse_printf("Value: %d").unwrap();
let output = fmt.format_with_errors(&[], FormatStyle::Printf, &MyErrorFormatter);
assert_eq!(output, "Value: <[%d MISSING]>");

Structs§

ConversionSpec
A printf conversion specification aka a % clause.
FormatString
A parsed format string.
Ilp32Platform
Standard ILP32 platform types (32-bit int, long, size_t, ptrdiff_t, and 32-bit pointers; 64-bit long long and intmax_t), matching Pigweed’s 32-bit embedded targets and default detokenizer conventions.
Llp64Platform
Standard LLP64 platform types (32-bit int and long; 64-bit long long, intmax_t, size_t, ptrdiff_t, and 64-bit pointers), matching 64-bit Windows targets.
Lp64Platform
Standard LP64 platform types (32-bit int; 64-bit long, long long, intmax_t, size_t, ptrdiff_t, and 64-bit pointers), matching 64-bit Unix/Linux/macOS targets.
NestedTokenSpec
A nested token specification (e.g. $#%08x, ${domain}#%08x, ${$#%08x}#%08x).

Enums§

Alignment
A core::fmt alignment spec.
Arg
Representation of a decoded argument.
Argument
An argument in a core::fmt style alignment spec.
Flag
A printf flag (the ‘+’ in %+d).
FormatFragment
A fragment of a printf format string.
FormatStyle
The style of formatting to apply (influences defaults).
FormatValueError
Errors that can occur when formatting an Arg for a ConversionSpec.
Length
A printf length (the l in %ld).
MinFieldWidth
A printf minimum field width (the 5 in %5d).
NestedDomain
Domain specification for a nested token.
NestedTokenValue
Token specification for a nested token.
Precision
A printf precision (the .5 in %.5d).
Primitive
Primitive type of a conversion (integer, float, string, etc.)
Style
The abstract formatting style for a conversion.

Traits§

FormatError
A trait for formatting conversion specifiers that failed, were skipped, or were missing.
PlatformTypes
Describes the native C/C++ integer and pointer types of the producing platform for all printf conversion specifiers and length modifiers.
PointerInt
Trait implemented by target platform pointer-sized unsigned integer types (e.g., u32 on ILP32, u64 on LP64/LLP64).
SignedInt
Trait implemented by target platform signed integer types (i8, i16, i32, i64).
UnsignedInt
Trait implemented by target platform unsigned integer types (u8, u16, u32, u64).

Functions§

canonicalize_domain
Canonicalizes a domain string by stripping all whitespace characters.
canonicalize_domain_cow
Canonicalizes a domain string by stripping whitespace, returning a borrowed slice if it contains no whitespace characters.