Skip to main content

Module printf

Module printf 

Source
Expand description

Formatting adapters for C printf semantics that Rust formatting does not express directly.

The adapters cover the integer conversions d, i, o, u, x, and X, including the hh, h, l, and ll length conversions. They also cover the floating conversions f, F, e, E, g, G, a, and A. A lowercase l has the same double semantics as no floating length modifier, while L uses the project’s [f128::f128] mapping for C long double; its output may differ from a host long double with another representation. The s conversion is supported when the bytes selected by its precision and first NUL form valid UTF-8.

Static widths and precisions are supported for all of these conversions. The relevant uses of the -, +, space, #, and 0 flags are supported; the locale-dependent apostrophe (') flag is not. Floating formatting uses the C locale and round-to-nearest, ties-to-even rather than tracking the active process locale or floating-point rounding mode. These adapters do not parse format strings: callers select the wrapper and Rust formatting trait corresponding to the source conversion and pass values after any C length conversion.

Use signed for the d and i conversions and unsigned for the u, o, x, and X conversions. The wrappers preserve the input’s Rust primitive type; the value passed to a wrapper should therefore be the value after the C length conversion. For example, an i8 represents the value formatted by %hhd, while an i32 represents the value formatted by %d.

The wrappers are unnecessary when native Rust formatting already has the same result. They are intended for C integer precision, the space-sign flag, and C alternate octal or hexadecimal form. Using a wrapper in an ordinary case is nevertheless equivalent:

use proctor_libc::printf::{signed, unsigned};

// printf("%d %i", 42, -7);
assert_eq!(format!("{} {}", signed(42_i32), signed(-7_i32)), "42 -7");
// Native `format!("{} {}", 42_i32, -7_i32)` is already exact.

// printf("%u %o %x %X", 42u, 42u, 42u, 42u);
assert_eq!(
    format!(
        "{} {:o} {:x} {:X}",
        unsigned(42_u32),
        unsigned(42_u32),
        unsigned(42_u32),
        unsigned(42_u32),
    ),
    "42 52 2a 2A",
);
// The corresponding native formatting is already exact too.

Rust width, left alignment, sign, and zero padding map to the C printf flags width, -, +, and 0. These cases also work natively when no wrapper-only behavior is combined with them:

use proctor_libc::printf::{signed, unsigned};

// printf("%8d", 42);     printf("%-8d", 42);
assert_eq!(format!("{:8}", signed(42_i32)), "      42");
assert_eq!(format!("{:<8}", signed(42_i32)), "42      ");
// printf("%+d", 42);     printf("%08d", -42);
assert_eq!(format!("{:+}", signed(42_i32)), "+42");
assert_eq!(format!("{:08}", signed(-42_i32)), "-0000042");
// Native i32 formatting produces the same four results.

// printf("%-8u", 42u);   printf("%08X", 42u);
assert_eq!(format!("{:<8}", unsigned(42_u32)), "42      ");
assert_eq!(format!("{:08X}", unsigned(42_u32)), "0000002A");
// Native u32 formatting is sufficient for these cases as well.

// The C `-` flag overrides `0`: printf("%-08d", 42);
assert_eq!(format!("{:<08}", signed(42_i32)), "42      ");

A Rust integer precision on these wrappers has C’s minimum-digit meaning. It also disables 0 padding, and zero formatted with precision zero emits no digits:

use proctor_libc::printf::{signed, unsigned};

// printf("%.5d", 42);    printf("%08.5d", 42);
assert_eq!(format!("{:.5}", signed(42_i32)), "00042");
assert_eq!(format!("{:08.5}", signed(42_i32)), "   00042");
// Both C `-` and precision override `0`: printf("%-08.5u", 42u);
assert_eq!(format!("{:<08.5}", unsigned(42_u32)), "00042   ");
// printf("%.0u", 0u);
assert_eq!(format!("{:.0}", unsigned(0_u32)), "");
// Native Rust integer formatting does not provide C integer precision, so
// the wrappers are required for these cases.

Call Signed::space_sign for C’s space flag. Rust’s + flag takes precedence, as it does for printf:

use proctor_libc::printf::signed;

// printf("% d", 42);     printf("%+ d", 42);
assert_eq!(format!("{}", signed(42_i32).space_sign()), " 42");
assert_eq!(format!("{:+}", signed(42_i32).space_sign()), "+42");
// Native Rust has no space-sign flag, so this wrapper is required.

The # flag uses C’s octal and hexadecimal forms, including their special handling of zero:

use proctor_libc::printf::unsigned;

// printf("%#o %#x %#X", 42u, 42u, 42u);
assert_eq!(
    format!(
        "{:#o} {:#x} {:#X}",
        unsigned(42_u32),
        unsigned(42_u32),
        unsigned(42_u32),
    ),
    "052 0x2a 0X2A",
);
// printf("%#.0o %#x", 0u, 0u);
assert_eq!(
    format!("{:#.0o} {:#x}", unsigned(0_u32), unsigned(0_u32)),
    "0 0",
);
// `0` pads after the prefix, but precision disables `0`:
// printf("%#08x %#08.4x", 42u, 42u);
assert_eq!(
    format!("{:#08x} {:#08.4x}", unsigned(42_u32), unsigned(42_u32)),
    "0x00002a   0x002a",
);
// Rust's native alternate octal prefix and zero-valued hexadecimal form
// differ from C, so the wrapper is required whenever `#` is used.

Use fixed for the f conversion and fixed_upper for the F conversion. A missing Rust precision has C’s default of six digits after the radix point:

use proctor_libc::printf::{fixed, fixed_upper};

// printf("%f %F", 1.25, 1.25);
assert_eq!(
    format!("{} {}", fixed(1.25_f64), fixed_upper(1.25_f64)),
    "1.250000 1.250000",
);
// printf("%lf %lF", 1.25, 1.25);
assert_eq!(
    format!("{} {}", fixed(1.25_f64), fixed_upper(1.25_f64)),
    "1.250000 1.250000",
);

C promotes a float argument to double, so an f32 passed to fixed or fixed_upper has the semantics of %f or %F after that promotion. The f128::f128 implementation is the project’s IEEE binary128 mapping for C long double and the %Lf and %LF spellings:

use proctor_libc::printf::{fixed, fixed_upper};

let float_value = 1.25_f32;
// printf("%f %F", (double)float_value, (double)float_value);
assert_eq!(
    format!("{} {}", fixed(float_value), fixed_upper(float_value)),
    "1.250000 1.250000",
);

let long_double_value = f128::f128::new(1.25_f64);
// Intended equivalents: printf("%Lf %LF", long_double_value, long_double_value);
assert_eq!(
    format!(
        "{} {}",
        fixed(long_double_value),
        fixed_upper(long_double_value),
    ),
    "1.250000 1.250000",
);

Rust precision, width, left alignment, sign, alternate form, and zero padding map to C precision, width, -, +, #, and 0. fixed is needed even in simple cases because native Rust omits C’s default six fractional digits. For an explicit nonzero precision, however, native Rust formatting is already exact for finite f32 and f64 values when no wrapper-only behavior is used:

use proctor_libc::printf::fixed;

// printf("%.2f %.0f", 1.25, 1.5);
assert_eq!(format!("{:.2} {:.0}", fixed(1.25_f64), fixed(1.5_f64)), "1.25 2");
// Native format!("{:.2} {:.0}", 1.25_f64, 1.5_f64) is exact here.

// printf("%8.2f %-8.2f", 1.25, 1.25);
assert_eq!(format!("{:8.2} {:<8.2}", fixed(1.25_f64), fixed(1.25_f64)),
           "    1.25 1.25    ");
// printf("%+08.2f %-08.2f", 1.25, 1.25);
assert_eq!(format!("{:+08.2} {:<08.2}", fixed(1.25_f64), fixed(1.25_f64)),
           "+0001.25 1.25    ");
// These explicit-precision cases also work with native f32/f64 formatting.

Call Fixed::space_sign or FixedUpper::space_sign for C’s space flag. Rust’s + flag takes precedence:

use proctor_libc::printf::fixed;

// printf("% f %+ f", 1.25, 1.25);
assert_eq!(
    format!("{} {:+}", fixed(1.25_f64).space_sign(), fixed(1.25_f64).space_sign()),
    " 1.250000 +1.250000",
);
// Native Rust has no space-sign flag, so the wrapper is required.

C’s # flag retains the radix point at precision zero. This differs from native Rust, and zero padding remains sign-aware:

use proctor_libc::printf::fixed;

// printf("%#.0f %08.2f", 2.0, -1.25);
assert_eq!(format!("{:#.0} {:08.2}", fixed(2.0_f64), fixed(-1.25_f64)),
           "2. -0001.25");
// printf("%#08.0f %-#08.0f", 2.0, 2.0);
assert_eq!(format!("{:#08.0} {:<#08.0}", fixed(2.0_f64), fixed(2.0_f64)),
           "0000002. 2.      ");

fixed_upper is observably different for nonfinite values:

use proctor_libc::printf::{fixed, fixed_upper};

// printf("%f %F", INFINITY, INFINITY);
assert_eq!(format!("{} {}", fixed(f64::INFINITY), fixed_upper(f64::INFINITY)),
           "inf INF");
// Native Rust uses `inf`/`NaN`, which does not cover both C spellings.

Use scientific with Rust’s e or E formatting trait for C’s e or E conversion. The wrapper is always required: Rust’s native exponent formatting does not guarantee C’s + on a nonnegative exponent or its minimum of two exponent digits. A missing precision still means six digits after the radix point:

use proctor_libc::printf::scientific;

// printf("%e %E", 1.25, 1.25);
assert_eq!(
    format!("{:e} {:E}", scientific(1.25_f64), scientific(1.25_f64)),
    "1.250000e+00 1.250000E+00",
);
// printf("%le %lE", 1.25, 1.25);
assert_eq!(
    format!("{:e} {:E}", scientific(1.25_f64), scientific(1.25_f64)),
    "1.250000e+00 1.250000E+00",
);

C promotes float to double. Binary128 supplies the project’s intended %Le and %LE behavior without assuming that the host long double has a compatible ABI:

use proctor_libc::printf::scientific;

let float_value = 1.25_f32;
// printf("%e %E", (double)float_value, (double)float_value);
assert_eq!(
    format!("{:e} {:E}", scientific(float_value), scientific(float_value)),
    "1.250000e+00 1.250000E+00",
);

let long_double_value = f128::f128::new(1.25_f64);
// Intended equivalents: printf("%Le %LE", long_double_value, long_double_value);
assert_eq!(
    format!(
        "{:e} {:E}",
        scientific(long_double_value),
        scientific(long_double_value),
    ),
    "1.250000e+00 1.250000E+00",
);

Precision, width, left alignment, sign, alternate form, and zero padding map to the corresponding C precision, width, -, +, #, and 0:

use proctor_libc::printf::scientific;

// printf("%.2e %.0E %#.0e", 1.25, 1.5, 2.0);
assert_eq!(
    format!(
        "{:.2e} {:.0E} {:#.0e}",
        scientific(1.25_f64),
        scientific(1.5_f64),
        scientific(2.0_f64),
    ),
    "1.25e+00 2E+00 2.e+00",
);
// printf("%12.2e %-12.2e", 1.25, 1.25);
assert_eq!(
    format!("{:12.2e} {:<12.2e}", scientific(1.25_f64), scientific(1.25_f64)),
    "    1.25e+00 1.25e+00    ",
);
// printf("%+012.2e %-012.2e", 1.25, 1.25);
assert_eq!(
    format!("{:+012.2e} {:<012.2e}", scientific(1.25_f64), scientific(1.25_f64)),
    "+0001.25e+00 1.25e+00    ",
);

Call Scientific::space_sign for C’s space flag. Rust’s + flag takes precedence:

use proctor_libc::printf::scientific;

// printf("% e %+ e", 1.25, 1.25);
assert_eq!(
    format!(
        "{:e} {:+e}",
        scientific(1.25_f64).space_sign(),
        scientific(1.25_f64).space_sign(),
    ),
    " 1.250000e+00 +1.250000e+00",
);

Scientific intentionally does not implement std::fmt::Display; the source conversion must select lowercase or uppercase exponent formatting:

ⓘ
use proctor_libc::printf::scientific;

let _ = format!("{}", scientific(1.25_f64));

Use general for the g conversion and general_upper for G. Rust has no corresponding general-format specifier, so the wrapper is always required at the format-specification level. A missing precision means six significant digits, while an explicit precision zero means one:

use proctor_libc::printf::{general, general_upper};

// printf("%g %G", 123.45, 1.0e6);
assert_eq!(
    format!("{} {}", general(123.45_f64), general_upper(1.0e6_f64)),
    "123.45 1E+06",
);
// printf("%lg %lG", 123.45, 1.0e6);
assert_eq!(
    format!("{} {}", general(123.45_f64), general_upper(1.0e6_f64)),
    "123.45 1E+06",
);
// printf("%.0g %.3g", 12.5, 12.5);
assert_eq!(format!("{:.0} {:.3}", general(12.5_f64), general(12.5_f64)),
           "1e+01 12.5");

The conversion first rounds to the requested number of significant digits. It uses scientific notation when the resulting decimal exponent is less than -4 or at least the precision, and fixed notation otherwise:

use proctor_libc::printf::general;

// printf("%.4g %.4g", 0.0001, 0.00001);
assert_eq!(
    format!("{:.4} {:.4}", general(0.0001_f64), general(0.00001_f64)),
    "0.0001 1e-05",
);
// Rounding can change the exponent and therefore the selected style:
// printf("%.4g", 9999.6);
assert_eq!(format!("{:.4}", general(9999.6_f64)), "1e+04");

Trailing fractional zeros and an unnecessary radix point are removed by default. C’s # flag retains them:

use proctor_libc::printf::{general, general_upper};

// printf("%.6g %#.6g", 123.0, 123.0);
assert_eq!(format!("{:.6} {:#.6}", general(123.0_f64), general(123.0_f64)),
           "123 123.000");
// printf("%.6G %#.6G", 1.23e10, 1.23e10);
assert_eq!(
    format!("{:.6} {:#.6}", general_upper(1.23e10_f64), general_upper(1.23e10_f64)),
    "1.23E+10 1.23000E+10",
);

Rust width, left alignment, sign, alternate form, and zero padding map to C width, -, +, #, and 0. Call General::space_sign or GeneralUpper::space_sign for C’s space flag; + takes precedence:

use proctor_libc::printf::general;

// printf("%10.4g %-10.4g", 12.5, 12.5);
assert_eq!(format!("{:10.4} {:<10.4}", general(12.5_f64), general(12.5_f64)),
           "      12.5 12.5      ");
// printf("%+010.4g % 010.4g", 12.5, 12.5);
assert_eq!(
    format!("{:+010.4} {:010.4}", general(12.5_f64), general(12.5_f64).space_sign()),
    "+0000012.5  0000012.5",
);
// `-` overrides `0`: printf("%-010.4g", 12.5);
assert_eq!(format!("{:<010.4}", general(12.5_f64)), "12.5      ");

C promotes float to double. Binary128 supplies the project’s intended %Lg and %LG behavior without assuming that the host long double has a compatible ABI:

use proctor_libc::printf::{general, general_upper};

let float_value = 1.25_f32;
// printf("%g %G", (double)float_value, (double)float_value);
assert_eq!(
    format!("{} {}", general(float_value), general_upper(float_value)),
    "1.25 1.25",
);

let long_double_value = f128::f128::new(1.25_f64);
// Intended equivalents: printf("%Lg %LG", long_double_value, long_double_value);
assert_eq!(
    format!("{} {}", general(long_double_value), general_upper(long_double_value)),
    "1.25 1.25",
);

Use hex_float with Rust’s x or X formatting trait for C’s a or A conversion. Primitive Rust floats do not implement hexadecimal formatting, so the wrapper is always required. A missing precision emits an exact representation and removes trailing zero hexadecimal digits:

use proctor_libc::printf::hex_float;

// printf("%a %A", 1.5, 1.5);
assert_eq!(
    format!("{:x} {:X}", hex_float(1.5_f64), hex_float(1.5_f64)),
    "0x1.8p+0 0X1.8P+0",
);
// `%la` and `%lA` have the same `double` argument and result.
assert_eq!(
    format!("{:x} {:X}", hex_float(1.5_f64), hex_float(1.5_f64)),
    "0x1.8p+0 0X1.8P+0",
);

Precision counts hexadecimal digits after the radix point. Precision zero omits the radix unless # requests it. Width, left alignment, sign, and zero padding map to C’s width, -, +, and 0; zero padding follows the sign and 0x or 0X prefix:

use proctor_libc::printf::hex_float;

// printf("%.3a %.0a %#.0a", 1.5, 1.5, 1.5);
assert_eq!(
    format!("{:.3x} {:.0x} {:#.0x}",
            hex_float(1.5_f64), hex_float(1.5_f64), hex_float(1.5_f64)),
    "0x1.800p+0 0x2p+0 0x2.p+0",
);
// printf("%12.2a %-12.2a %+012.2a", 1.5, 1.5, 1.5);
assert_eq!(
    format!("{:12.2x} {:<12.2x} {:+012.2x}",
            hex_float(1.5_f64), hex_float(1.5_f64), hex_float(1.5_f64)),
    "   0x1.80p+0 0x1.80p+0    +0x001.80p+0",
);

Call HexFloat::space_sign for C’s space flag. Rust’s + flag takes precedence:

use proctor_libc::printf::hex_float;

// printf("% a %+ a", 1.5, 1.5);
assert_eq!(
    format!("{:x} {:+x}",
            hex_float(1.5_f64).space_sign(),
            hex_float(1.5_f64).space_sign()),
    " 0x1.8p+0 +0x1.8p+0",
);

C promotes float to double before %a formatting. Consequently an f32 subnormal is formatted as its exact, usually normal, binary64 value:

use proctor_libc::printf::hex_float;

let float_subnormal = f32::from_bits(1);
// printf("%a", (double)float_subnormal);
assert_eq!(format!("{:x}", hex_float(float_subnormal)), "0x1p-149");

let long_double_value = f128::f128::new(1.5_f64);
// Intended equivalents: printf("%La %LA", long_double_value, long_double_value);
assert_eq!(
    format!("{:x} {:X}", hex_float(long_double_value), hex_float(long_double_value)),
    "0x1.8p+0 0X1.8P+0",
);

Effective binary64 and binary128 subnormals use the deterministic GNU and libquadmath convention: a leading zero and the type’s minimum-normal exponent. Binary128 is the project’s intended %La/%LA mapping and is not passed to a host long double conversion when that ABI differs. Floating formatting uses the C locale and round-to-nearest, ties-to-even; it does not track an active process locale or floating-point rounding mode.

HexFloat intentionally does not implement std::fmt::Display; the source conversion must select lowercase or uppercase hexadecimal formatting:

ⓘ
use proctor_libc::printf::hex_float;

let _ = format!("{}", hex_float(1.5_f64));

Use byte_string for the s conversion when PROCTOR represents the C char * as an i8 slice. It reinterprets each i8 as the corresponding byte, stops at the first NUL, and uses C’s byte-counted width and precision:

use proctor_libc::printf::byte_string;

let text = [b'h' as i8, b'e' as i8, b'l' as i8, b'l' as i8, b'o' as i8, 0];
// printf("%s", text);
assert_eq!(format!("{}", byte_string(&text)), "hello");
// printf("%10s", text);    printf("%-10s", text);
assert_eq!(format!("{:10}", byte_string(&text)), "     hello");
assert_eq!(format!("{:<10}", byte_string(&text)), "hello     ");
// printf("%.3s", text);    printf("%10.3s", text);
assert_eq!(format!("{:.3}", byte_string(&text)), "hel");
assert_eq!(format!("{:10.3}", byte_string(&text)), "       hel");

Precision is a maximum byte count and can make a NUL unnecessary when the slice contains at least that many bytes. Bytes following the first NUL or the precision boundary are not inspected:

use proctor_libc::printf::byte_string;

let terminated = [b'o' as i8, b'k' as i8, 0, b'x' as i8];
// printf("%s", terminated);    printf("%.0s", terminated);
assert_eq!(format!("{}", byte_string(&terminated)), "ok");
assert_eq!(format!("{:.0}", byte_string(&terminated)), "");

let bounded = [b'a' as i8, b'b' as i8, b'c' as i8];
// printf("%.2s", bounded);
assert_eq!(format!("{:.2}", byte_string(&bounded)), "ab");

The selected output bytes must be valid UTF-8. Within that supported PROCTOR domain they are preserved exactly, including multibyte encodings, while width still counts bytes rather than Unicode scalar values:

use proctor_libc::printf::byte_string;

let text = [0xc3_u8 as i8, 0xa9_u8 as i8, b'!' as i8, 0]; // "é!"
// printf("%5s", text);     printf("%.2s", text);
assert_eq!(format!("{:5}", byte_string(&text)).as_bytes(), b"  \xc3\xa9!");
assert_eq!(format!("{:.2}", byte_string(&text)).as_bytes(), b"\xc3\xa9");

A precision can split a UTF-8 encoding; such selected output, like any other non-UTF-8 byte sequence, is outside this wrapper’s supported domain. The implementation remains memory-safe and reports a formatting error. Native &str formatting is sufficient for simple ASCII strings when C’s byte counts and NUL representation are irrelevant. This wrapper is needed for PROCTOR’s &[i8] mapping, first-NUL selection, and byte-counted fields.

Floating formatting uses the C locale’s . radix character and round-to-nearest, ties-to-even. It does not track an active process locale or floating-point rounding mode. Binary128 formatting is tested directly and by invariants, but is not differentially checked against host long-double conversions on systems where C long double has a different representation.

Only f32, f64, and f128::f128 are accepted:

ⓘ
let _ = proctor_libc::printf::fixed(1_i32);

Structs§

ByteString
A borrowed adapter for C printf string formatting in the valid-UTF-8 output domain.
Fixed
A type-preserving adapter for C printf lowercase fixed-point formatting.
FixedUpper
A type-preserving adapter for C printf uppercase fixed-point formatting.
General
A type-preserving adapter for C printf lowercase general formatting.
GeneralUpper
A type-preserving adapter for C printf uppercase general formatting.
HexFloat
A type-preserving adapter for C printf hexadecimal floating formatting.
Scientific
A type-preserving adapter for C printf scientific formatting.
Signed
A type-preserving adapter for C printf signed-integer formatting.
Unsigned
A type-preserving adapter for C printf unsigned-integer formatting.

Traits§

FixedValue
A primitive floating-point value accepted by fixed, fixed_upper, scientific, general, general_upper, and hex_float.
SignedValue
A primitive signed integer accepted by signed.
UnsignedValue
A primitive unsigned integer accepted by unsigned.

Functions§

byte_string
Wraps a PROCTOR char * mapping for C printf-compatible s formatting.
fixed
Wraps a floating-point primitive for C printf-compatible f formatting.
fixed_upper
Wraps a floating-point primitive for C printf-compatible F formatting.
general
Wraps a floating-point primitive for C printf-compatible g formatting.
general_upper
Wraps a floating-point primitive for C printf-compatible G formatting.
hex_float
Wraps a floating-point primitive for C printf-compatible a or A formatting.
scientific
Wraps a floating-point primitive for C printf-compatible e or E formatting.
signed
Wraps a signed primitive for C printf-compatible d or i formatting.
unsigned
Wraps an unsigned primitive for C printf-compatible u, o, x, or X formatting.