proctor_libc/stdio/printf.rs
1//! Formatting adapters for C `printf` semantics that Rust formatting does not
2//! express directly.
3//!
4//! The adapters cover the integer conversions `d`, `i`, `o`, `u`, `x`, and
5//! `X`, including the `hh`, `h`, `l`, and `ll` length conversions. They also
6//! cover the floating conversions `f`, `F`, `e`, `E`, `g`, `G`, `a`, and `A`.
7//! A lowercase `l` has the same `double` semantics as no floating length
8//! modifier, while `L` uses the project's [`f128::f128`] mapping for C `long
9//! double`; its output may differ from a host `long double` with another
10//! representation. The `s` conversion is supported when the bytes selected by
11//! its precision and first NUL form valid UTF-8.
12//!
13//! Static widths and precisions are supported for all of these conversions.
14//! The relevant uses of the `-`, `+`, space, `#`, and `0` flags are supported;
15//! the locale-dependent apostrophe (`'`) flag is not. Floating formatting uses
16//! the C locale and round-to-nearest, ties-to-even rather than tracking the
17//! active process locale or floating-point rounding mode. These adapters do not
18//! parse format strings: callers select the wrapper and Rust formatting trait
19//! corresponding to the source conversion and pass values after any C length
20//! conversion.
21//!
22//! Use [`signed`] for the `d` and `i` conversions and [`unsigned`] for the
23//! `u`, `o`, `x`, and `X` conversions. The wrappers preserve the input's Rust
24//! primitive type; the value passed to a wrapper should therefore be the value
25//! after the C length conversion. For example, an `i8` represents the value
26//! formatted by `%hhd`, while an `i32` represents the value formatted by `%d`.
27//!
28//! The wrappers are unnecessary when native Rust formatting already has the
29//! same result. They are intended for C integer precision, the space-sign flag,
30//! and C alternate octal or hexadecimal form. Using a wrapper in an ordinary
31//! case is nevertheless equivalent:
32//!
33//! ```
34//! use proctor_libc::printf::{signed, unsigned};
35//!
36//! // printf("%d %i", 42, -7);
37//! assert_eq!(format!("{} {}", signed(42_i32), signed(-7_i32)), "42 -7");
38//! // Native `format!("{} {}", 42_i32, -7_i32)` is already exact.
39//!
40//! // printf("%u %o %x %X", 42u, 42u, 42u, 42u);
41//! assert_eq!(
42//! format!(
43//! "{} {:o} {:x} {:X}",
44//! unsigned(42_u32),
45//! unsigned(42_u32),
46//! unsigned(42_u32),
47//! unsigned(42_u32),
48//! ),
49//! "42 52 2a 2A",
50//! );
51//! // The corresponding native formatting is already exact too.
52//! ```
53//!
54//! Rust width, left alignment, sign, and zero padding map to the C `printf`
55//! flags `width`, `-`, `+`, and `0`. These cases also work natively when no
56//! wrapper-only behavior is combined with them:
57//!
58//! ```
59//! use proctor_libc::printf::{signed, unsigned};
60//!
61//! // printf("%8d", 42); printf("%-8d", 42);
62//! assert_eq!(format!("{:8}", signed(42_i32)), " 42");
63//! assert_eq!(format!("{:<8}", signed(42_i32)), "42 ");
64//! // printf("%+d", 42); printf("%08d", -42);
65//! assert_eq!(format!("{:+}", signed(42_i32)), "+42");
66//! assert_eq!(format!("{:08}", signed(-42_i32)), "-0000042");
67//! // Native i32 formatting produces the same four results.
68//!
69//! // printf("%-8u", 42u); printf("%08X", 42u);
70//! assert_eq!(format!("{:<8}", unsigned(42_u32)), "42 ");
71//! assert_eq!(format!("{:08X}", unsigned(42_u32)), "0000002A");
72//! // Native u32 formatting is sufficient for these cases as well.
73//!
74//! // The C `-` flag overrides `0`: printf("%-08d", 42);
75//! assert_eq!(format!("{:<08}", signed(42_i32)), "42 ");
76//! ```
77//!
78//! A Rust integer precision on these wrappers has C's minimum-digit meaning.
79//! It also disables `0` padding, and zero formatted with precision zero emits
80//! no digits:
81//!
82//! ```
83//! use proctor_libc::printf::{signed, unsigned};
84//!
85//! // printf("%.5d", 42); printf("%08.5d", 42);
86//! assert_eq!(format!("{:.5}", signed(42_i32)), "00042");
87//! assert_eq!(format!("{:08.5}", signed(42_i32)), " 00042");
88//! // Both C `-` and precision override `0`: printf("%-08.5u", 42u);
89//! assert_eq!(format!("{:<08.5}", unsigned(42_u32)), "00042 ");
90//! // printf("%.0u", 0u);
91//! assert_eq!(format!("{:.0}", unsigned(0_u32)), "");
92//! // Native Rust integer formatting does not provide C integer precision, so
93//! // the wrappers are required for these cases.
94//! ```
95//!
96//! Call [`Signed::space_sign`] for C's space flag. Rust's `+` flag takes
97//! precedence, as it does for `printf`:
98//!
99//! ```
100//! use proctor_libc::printf::signed;
101//!
102//! // printf("% d", 42); printf("%+ d", 42);
103//! assert_eq!(format!("{}", signed(42_i32).space_sign()), " 42");
104//! assert_eq!(format!("{:+}", signed(42_i32).space_sign()), "+42");
105//! // Native Rust has no space-sign flag, so this wrapper is required.
106//! ```
107//!
108//! The `#` flag uses C's octal and hexadecimal forms, including their special
109//! handling of zero:
110//!
111//! ```
112//! use proctor_libc::printf::unsigned;
113//!
114//! // printf("%#o %#x %#X", 42u, 42u, 42u);
115//! assert_eq!(
116//! format!(
117//! "{:#o} {:#x} {:#X}",
118//! unsigned(42_u32),
119//! unsigned(42_u32),
120//! unsigned(42_u32),
121//! ),
122//! "052 0x2a 0X2A",
123//! );
124//! // printf("%#.0o %#x", 0u, 0u);
125//! assert_eq!(
126//! format!("{:#.0o} {:#x}", unsigned(0_u32), unsigned(0_u32)),
127//! "0 0",
128//! );
129//! // `0` pads after the prefix, but precision disables `0`:
130//! // printf("%#08x %#08.4x", 42u, 42u);
131//! assert_eq!(
132//! format!("{:#08x} {:#08.4x}", unsigned(42_u32), unsigned(42_u32)),
133//! "0x00002a 0x002a",
134//! );
135//! // Rust's native alternate octal prefix and zero-valued hexadecimal form
136//! // differ from C, so the wrapper is required whenever `#` is used.
137//! ```
138//!
139//! Use [`fixed`] for the `f` conversion and [`fixed_upper`] for the `F`
140//! conversion. A missing Rust precision has C's default of six digits after
141//! the radix point:
142//!
143//! ```
144//! use proctor_libc::printf::{fixed, fixed_upper};
145//!
146//! // printf("%f %F", 1.25, 1.25);
147//! assert_eq!(
148//! format!("{} {}", fixed(1.25_f64), fixed_upper(1.25_f64)),
149//! "1.250000 1.250000",
150//! );
151//! // printf("%lf %lF", 1.25, 1.25);
152//! assert_eq!(
153//! format!("{} {}", fixed(1.25_f64), fixed_upper(1.25_f64)),
154//! "1.250000 1.250000",
155//! );
156//! ```
157//!
158//! C promotes a `float` argument to `double`, so an `f32` passed to [`fixed`]
159//! or [`fixed_upper`] has the semantics of `%f` or `%F` after that promotion.
160//! The `f128::f128` implementation is the project's IEEE binary128 mapping for
161//! C `long double` and the `%Lf` and `%LF` spellings:
162//!
163//! ```
164//! use proctor_libc::printf::{fixed, fixed_upper};
165//!
166//! let float_value = 1.25_f32;
167//! // printf("%f %F", (double)float_value, (double)float_value);
168//! assert_eq!(
169//! format!("{} {}", fixed(float_value), fixed_upper(float_value)),
170//! "1.250000 1.250000",
171//! );
172//!
173//! let long_double_value = f128::f128::new(1.25_f64);
174//! // Intended equivalents: printf("%Lf %LF", long_double_value, long_double_value);
175//! assert_eq!(
176//! format!(
177//! "{} {}",
178//! fixed(long_double_value),
179//! fixed_upper(long_double_value),
180//! ),
181//! "1.250000 1.250000",
182//! );
183//! ```
184//!
185//! Rust precision, width, left alignment, sign, alternate form, and zero
186//! padding map to C precision, `width`, `-`, `+`, `#`, and `0`. [`fixed`] is
187//! needed even in simple cases because native Rust omits C's default six
188//! fractional digits. For an explicit nonzero precision, however, native Rust
189//! formatting is already exact for finite `f32` and `f64` values when no
190//! wrapper-only behavior is used:
191//!
192//! ```
193//! use proctor_libc::printf::fixed;
194//!
195//! // printf("%.2f %.0f", 1.25, 1.5);
196//! assert_eq!(format!("{:.2} {:.0}", fixed(1.25_f64), fixed(1.5_f64)), "1.25 2");
197//! // Native format!("{:.2} {:.0}", 1.25_f64, 1.5_f64) is exact here.
198//!
199//! // printf("%8.2f %-8.2f", 1.25, 1.25);
200//! assert_eq!(format!("{:8.2} {:<8.2}", fixed(1.25_f64), fixed(1.25_f64)),
201//! " 1.25 1.25 ");
202//! // printf("%+08.2f %-08.2f", 1.25, 1.25);
203//! assert_eq!(format!("{:+08.2} {:<08.2}", fixed(1.25_f64), fixed(1.25_f64)),
204//! "+0001.25 1.25 ");
205//! // These explicit-precision cases also work with native f32/f64 formatting.
206//! ```
207//!
208//! Call [`Fixed::space_sign`] or [`FixedUpper::space_sign`] for C's space flag.
209//! Rust's `+` flag takes precedence:
210//!
211//! ```
212//! use proctor_libc::printf::fixed;
213//!
214//! // printf("% f %+ f", 1.25, 1.25);
215//! assert_eq!(
216//! format!("{} {:+}", fixed(1.25_f64).space_sign(), fixed(1.25_f64).space_sign()),
217//! " 1.250000 +1.250000",
218//! );
219//! // Native Rust has no space-sign flag, so the wrapper is required.
220//! ```
221//!
222//! C's `#` flag retains the radix point at precision zero. This differs from
223//! native Rust, and zero padding remains sign-aware:
224//!
225//! ```
226//! use proctor_libc::printf::fixed;
227//!
228//! // printf("%#.0f %08.2f", 2.0, -1.25);
229//! assert_eq!(format!("{:#.0} {:08.2}", fixed(2.0_f64), fixed(-1.25_f64)),
230//! "2. -0001.25");
231//! // printf("%#08.0f %-#08.0f", 2.0, 2.0);
232//! assert_eq!(format!("{:#08.0} {:<#08.0}", fixed(2.0_f64), fixed(2.0_f64)),
233//! "0000002. 2. ");
234//! ```
235//!
236//! [`fixed_upper`] is observably different for nonfinite values:
237//!
238//! ```
239//! use proctor_libc::printf::{fixed, fixed_upper};
240//!
241//! // printf("%f %F", INFINITY, INFINITY);
242//! assert_eq!(format!("{} {}", fixed(f64::INFINITY), fixed_upper(f64::INFINITY)),
243//! "inf INF");
244//! // Native Rust uses `inf`/`NaN`, which does not cover both C spellings.
245//! ```
246//!
247//! Use [`scientific`] with Rust's `e` or `E` formatting trait for C's `e` or
248//! `E` conversion. The wrapper is always required: Rust's native exponent
249//! formatting does not guarantee C's `+` on a nonnegative exponent or its
250//! minimum of two exponent digits. A missing precision still means six digits
251//! after the radix point:
252//!
253//! ```
254//! use proctor_libc::printf::scientific;
255//!
256//! // printf("%e %E", 1.25, 1.25);
257//! assert_eq!(
258//! format!("{:e} {:E}", scientific(1.25_f64), scientific(1.25_f64)),
259//! "1.250000e+00 1.250000E+00",
260//! );
261//! // printf("%le %lE", 1.25, 1.25);
262//! assert_eq!(
263//! format!("{:e} {:E}", scientific(1.25_f64), scientific(1.25_f64)),
264//! "1.250000e+00 1.250000E+00",
265//! );
266//! ```
267//!
268//! C promotes `float` to `double`. Binary128 supplies the project's intended
269//! `%Le` and `%LE` behavior without assuming that the host `long double` has a
270//! compatible ABI:
271//!
272//! ```
273//! use proctor_libc::printf::scientific;
274//!
275//! let float_value = 1.25_f32;
276//! // printf("%e %E", (double)float_value, (double)float_value);
277//! assert_eq!(
278//! format!("{:e} {:E}", scientific(float_value), scientific(float_value)),
279//! "1.250000e+00 1.250000E+00",
280//! );
281//!
282//! let long_double_value = f128::f128::new(1.25_f64);
283//! // Intended equivalents: printf("%Le %LE", long_double_value, long_double_value);
284//! assert_eq!(
285//! format!(
286//! "{:e} {:E}",
287//! scientific(long_double_value),
288//! scientific(long_double_value),
289//! ),
290//! "1.250000e+00 1.250000E+00",
291//! );
292//! ```
293//!
294//! Precision, width, left alignment, sign, alternate form, and zero padding
295//! map to the corresponding C precision, `width`, `-`, `+`, `#`, and `0`:
296//!
297//! ```
298//! use proctor_libc::printf::scientific;
299//!
300//! // printf("%.2e %.0E %#.0e", 1.25, 1.5, 2.0);
301//! assert_eq!(
302//! format!(
303//! "{:.2e} {:.0E} {:#.0e}",
304//! scientific(1.25_f64),
305//! scientific(1.5_f64),
306//! scientific(2.0_f64),
307//! ),
308//! "1.25e+00 2E+00 2.e+00",
309//! );
310//! // printf("%12.2e %-12.2e", 1.25, 1.25);
311//! assert_eq!(
312//! format!("{:12.2e} {:<12.2e}", scientific(1.25_f64), scientific(1.25_f64)),
313//! " 1.25e+00 1.25e+00 ",
314//! );
315//! // printf("%+012.2e %-012.2e", 1.25, 1.25);
316//! assert_eq!(
317//! format!("{:+012.2e} {:<012.2e}", scientific(1.25_f64), scientific(1.25_f64)),
318//! "+0001.25e+00 1.25e+00 ",
319//! );
320//! ```
321//!
322//! Call [`Scientific::space_sign`] for C's space flag. Rust's `+` flag takes
323//! precedence:
324//!
325//! ```
326//! use proctor_libc::printf::scientific;
327//!
328//! // printf("% e %+ e", 1.25, 1.25);
329//! assert_eq!(
330//! format!(
331//! "{:e} {:+e}",
332//! scientific(1.25_f64).space_sign(),
333//! scientific(1.25_f64).space_sign(),
334//! ),
335//! " 1.250000e+00 +1.250000e+00",
336//! );
337//! ```
338//!
339//! [`Scientific`] intentionally does not implement [`std::fmt::Display`]; the
340//! source conversion must select lowercase or uppercase exponent formatting:
341//!
342//! ```compile_fail
343//! use proctor_libc::printf::scientific;
344//!
345//! let _ = format!("{}", scientific(1.25_f64));
346//! ```
347//!
348//! Use [`general`] for the `g` conversion and [`general_upper`] for `G`.
349//! Rust has no corresponding general-format specifier, so the wrapper is
350//! always required at the format-specification level. A missing precision
351//! means six significant digits, while an explicit precision zero means one:
352//!
353//! ```
354//! use proctor_libc::printf::{general, general_upper};
355//!
356//! // printf("%g %G", 123.45, 1.0e6);
357//! assert_eq!(
358//! format!("{} {}", general(123.45_f64), general_upper(1.0e6_f64)),
359//! "123.45 1E+06",
360//! );
361//! // printf("%lg %lG", 123.45, 1.0e6);
362//! assert_eq!(
363//! format!("{} {}", general(123.45_f64), general_upper(1.0e6_f64)),
364//! "123.45 1E+06",
365//! );
366//! // printf("%.0g %.3g", 12.5, 12.5);
367//! assert_eq!(format!("{:.0} {:.3}", general(12.5_f64), general(12.5_f64)),
368//! "1e+01 12.5");
369//! ```
370//!
371//! The conversion first rounds to the requested number of significant digits.
372//! It uses scientific notation when the resulting decimal exponent is less
373//! than `-4` or at least the precision, and fixed notation otherwise:
374//!
375//! ```
376//! use proctor_libc::printf::general;
377//!
378//! // printf("%.4g %.4g", 0.0001, 0.00001);
379//! assert_eq!(
380//! format!("{:.4} {:.4}", general(0.0001_f64), general(0.00001_f64)),
381//! "0.0001 1e-05",
382//! );
383//! // Rounding can change the exponent and therefore the selected style:
384//! // printf("%.4g", 9999.6);
385//! assert_eq!(format!("{:.4}", general(9999.6_f64)), "1e+04");
386//! ```
387//!
388//! Trailing fractional zeros and an unnecessary radix point are removed by
389//! default. C's `#` flag retains them:
390//!
391//! ```
392//! use proctor_libc::printf::{general, general_upper};
393//!
394//! // printf("%.6g %#.6g", 123.0, 123.0);
395//! assert_eq!(format!("{:.6} {:#.6}", general(123.0_f64), general(123.0_f64)),
396//! "123 123.000");
397//! // printf("%.6G %#.6G", 1.23e10, 1.23e10);
398//! assert_eq!(
399//! format!("{:.6} {:#.6}", general_upper(1.23e10_f64), general_upper(1.23e10_f64)),
400//! "1.23E+10 1.23000E+10",
401//! );
402//! ```
403//!
404//! Rust width, left alignment, sign, alternate form, and zero padding map to
405//! C `width`, `-`, `+`, `#`, and `0`. Call [`General::space_sign`] or
406//! [`GeneralUpper::space_sign`] for C's space flag; `+` takes precedence:
407//!
408//! ```
409//! use proctor_libc::printf::general;
410//!
411//! // printf("%10.4g %-10.4g", 12.5, 12.5);
412//! assert_eq!(format!("{:10.4} {:<10.4}", general(12.5_f64), general(12.5_f64)),
413//! " 12.5 12.5 ");
414//! // printf("%+010.4g % 010.4g", 12.5, 12.5);
415//! assert_eq!(
416//! format!("{:+010.4} {:010.4}", general(12.5_f64), general(12.5_f64).space_sign()),
417//! "+0000012.5 0000012.5",
418//! );
419//! // `-` overrides `0`: printf("%-010.4g", 12.5);
420//! assert_eq!(format!("{:<010.4}", general(12.5_f64)), "12.5 ");
421//! ```
422//!
423//! C promotes `float` to `double`. Binary128 supplies the project's intended
424//! `%Lg` and `%LG` behavior without assuming that the host `long double` has a
425//! compatible ABI:
426//!
427//! ```
428//! use proctor_libc::printf::{general, general_upper};
429//!
430//! let float_value = 1.25_f32;
431//! // printf("%g %G", (double)float_value, (double)float_value);
432//! assert_eq!(
433//! format!("{} {}", general(float_value), general_upper(float_value)),
434//! "1.25 1.25",
435//! );
436//!
437//! let long_double_value = f128::f128::new(1.25_f64);
438//! // Intended equivalents: printf("%Lg %LG", long_double_value, long_double_value);
439//! assert_eq!(
440//! format!("{} {}", general(long_double_value), general_upper(long_double_value)),
441//! "1.25 1.25",
442//! );
443//! ```
444//!
445//! Use [`hex_float`] with Rust's `x` or `X` formatting trait for C's `a` or
446//! `A` conversion. Primitive Rust floats do not implement hexadecimal
447//! formatting, so the wrapper is always required. A missing precision emits
448//! an exact representation and removes trailing zero hexadecimal digits:
449//!
450//! ```
451//! use proctor_libc::printf::hex_float;
452//!
453//! // printf("%a %A", 1.5, 1.5);
454//! assert_eq!(
455//! format!("{:x} {:X}", hex_float(1.5_f64), hex_float(1.5_f64)),
456//! "0x1.8p+0 0X1.8P+0",
457//! );
458//! // `%la` and `%lA` have the same `double` argument and result.
459//! assert_eq!(
460//! format!("{:x} {:X}", hex_float(1.5_f64), hex_float(1.5_f64)),
461//! "0x1.8p+0 0X1.8P+0",
462//! );
463//! ```
464//!
465//! Precision counts hexadecimal digits after the radix point. Precision zero
466//! omits the radix unless `#` requests it. Width, left alignment, sign, and
467//! zero padding map to C's `width`, `-`, `+`, and `0`; zero padding follows
468//! the sign and `0x` or `0X` prefix:
469//!
470//! ```
471//! use proctor_libc::printf::hex_float;
472//!
473//! // printf("%.3a %.0a %#.0a", 1.5, 1.5, 1.5);
474//! assert_eq!(
475//! format!("{:.3x} {:.0x} {:#.0x}",
476//! hex_float(1.5_f64), hex_float(1.5_f64), hex_float(1.5_f64)),
477//! "0x1.800p+0 0x2p+0 0x2.p+0",
478//! );
479//! // printf("%12.2a %-12.2a %+012.2a", 1.5, 1.5, 1.5);
480//! assert_eq!(
481//! format!("{:12.2x} {:<12.2x} {:+012.2x}",
482//! hex_float(1.5_f64), hex_float(1.5_f64), hex_float(1.5_f64)),
483//! " 0x1.80p+0 0x1.80p+0 +0x001.80p+0",
484//! );
485//! ```
486//!
487//! Call [`HexFloat::space_sign`] for C's space flag. Rust's `+` flag takes
488//! precedence:
489//!
490//! ```
491//! use proctor_libc::printf::hex_float;
492//!
493//! // printf("% a %+ a", 1.5, 1.5);
494//! assert_eq!(
495//! format!("{:x} {:+x}",
496//! hex_float(1.5_f64).space_sign(),
497//! hex_float(1.5_f64).space_sign()),
498//! " 0x1.8p+0 +0x1.8p+0",
499//! );
500//! ```
501//!
502//! C promotes `float` to `double` before `%a` formatting. Consequently an
503//! `f32` subnormal is formatted as its exact, usually normal, binary64 value:
504//!
505//! ```
506//! use proctor_libc::printf::hex_float;
507//!
508//! let float_subnormal = f32::from_bits(1);
509//! // printf("%a", (double)float_subnormal);
510//! assert_eq!(format!("{:x}", hex_float(float_subnormal)), "0x1p-149");
511//!
512//! let long_double_value = f128::f128::new(1.5_f64);
513//! // Intended equivalents: printf("%La %LA", long_double_value, long_double_value);
514//! assert_eq!(
515//! format!("{:x} {:X}", hex_float(long_double_value), hex_float(long_double_value)),
516//! "0x1.8p+0 0X1.8P+0",
517//! );
518//! ```
519//!
520//! Effective binary64 and binary128 subnormals use the deterministic GNU and
521//! libquadmath convention: a leading zero and the type's minimum-normal
522//! exponent. Binary128 is the project's intended `%La`/`%LA` mapping and is
523//! not passed to a host `long double` conversion when that ABI differs.
524//! Floating formatting uses the C locale and round-to-nearest, ties-to-even;
525//! it does not track an active process locale or floating-point rounding mode.
526//!
527//! [`HexFloat`] intentionally does not implement [`std::fmt::Display`]; the
528//! source conversion must select lowercase or uppercase hexadecimal formatting:
529//!
530//! ```compile_fail
531//! use proctor_libc::printf::hex_float;
532//!
533//! let _ = format!("{}", hex_float(1.5_f64));
534//! ```
535//!
536//! Use [`byte_string`] for the `s` conversion when PROCTOR represents the C
537//! `char *` as an `i8` slice. It reinterprets each `i8` as the corresponding
538//! byte, stops at the first NUL, and uses C's byte-counted width and precision:
539//!
540//! ```
541//! use proctor_libc::printf::byte_string;
542//!
543//! let text = [b'h' as i8, b'e' as i8, b'l' as i8, b'l' as i8, b'o' as i8, 0];
544//! // printf("%s", text);
545//! assert_eq!(format!("{}", byte_string(&text)), "hello");
546//! // printf("%10s", text); printf("%-10s", text);
547//! assert_eq!(format!("{:10}", byte_string(&text)), " hello");
548//! assert_eq!(format!("{:<10}", byte_string(&text)), "hello ");
549//! // printf("%.3s", text); printf("%10.3s", text);
550//! assert_eq!(format!("{:.3}", byte_string(&text)), "hel");
551//! assert_eq!(format!("{:10.3}", byte_string(&text)), " hel");
552//! ```
553//!
554//! Precision is a maximum byte count and can make a NUL unnecessary when the
555//! slice contains at least that many bytes. Bytes following the first NUL or
556//! the precision boundary are not inspected:
557//!
558//! ```
559//! use proctor_libc::printf::byte_string;
560//!
561//! let terminated = [b'o' as i8, b'k' as i8, 0, b'x' as i8];
562//! // printf("%s", terminated); printf("%.0s", terminated);
563//! assert_eq!(format!("{}", byte_string(&terminated)), "ok");
564//! assert_eq!(format!("{:.0}", byte_string(&terminated)), "");
565//!
566//! let bounded = [b'a' as i8, b'b' as i8, b'c' as i8];
567//! // printf("%.2s", bounded);
568//! assert_eq!(format!("{:.2}", byte_string(&bounded)), "ab");
569//! ```
570//!
571//! The selected output bytes must be valid UTF-8. Within that supported
572//! PROCTOR domain they are preserved exactly, including multibyte encodings,
573//! while width still counts bytes rather than Unicode scalar values:
574//!
575//! ```
576//! use proctor_libc::printf::byte_string;
577//!
578//! let text = [0xc3_u8 as i8, 0xa9_u8 as i8, b'!' as i8, 0]; // "é!"
579//! // printf("%5s", text); printf("%.2s", text);
580//! assert_eq!(format!("{:5}", byte_string(&text)).as_bytes(), b" \xc3\xa9!");
581//! assert_eq!(format!("{:.2}", byte_string(&text)).as_bytes(), b"\xc3\xa9");
582//! ```
583//!
584//! A precision can split a UTF-8 encoding; such selected output, like any
585//! other non-UTF-8 byte sequence, is outside this wrapper's supported domain.
586//! The implementation remains memory-safe and reports a formatting error.
587//! Native `&str` formatting is sufficient for simple ASCII strings when C's
588//! byte counts and NUL representation are irrelevant. This wrapper is needed
589//! for PROCTOR's `&[i8]` mapping, first-NUL selection, and byte-counted fields.
590//!
591//! Floating formatting uses the C locale's `.` radix character and
592//! round-to-nearest, ties-to-even. It does not track an active process locale
593//! or floating-point rounding mode. Binary128 formatting is tested directly
594//! and by invariants, but is not differentially checked against host
595//! long-double conversions on systems where C `long double` has a different
596//! representation.
597//!
598//! Only `f32`, `f64`, and `f128::f128` are accepted:
599//!
600//! ```compile_fail
601//! let _ = proctor_libc::printf::fixed(1_i32);
602//! ```
603
604use num_bigint::BigUint;
605use std::fmt::{self, Alignment, Formatter};
606
607const SPACE_PADDING: &str = concat!(
608 " ",
609 " ",
610);
611const ZERO_PADDING: &str = concat!(
612 "00000000000000000000000000000000",
613 "00000000000000000000000000000000",
614);
615
616mod private {
617 pub trait SealedSigned: Copy {
618 fn to_i128(self) -> i128;
619 }
620
621 pub trait SealedUnsigned: Copy {
622 fn to_u128(self) -> u128;
623 }
624
625 pub trait SealedFixed: Copy {
626 const FRACTION_BITS: u32;
627 const EXPONENT_BITS: u32;
628 const EXPONENT_BIAS: i32;
629 const HEX_FRACTION_BITS: u32;
630 const HEX_MIN_NORMAL_EXPONENT: i32;
631
632 fn bits(self) -> u128;
633 }
634}
635
636/// A primitive signed integer accepted by [`signed`].
637///
638/// This sealed trait is implemented for `i8`, `i16`, `i32`, `i64`, and
639/// `isize`.
640pub trait SignedValue: private::SealedSigned {}
641
642/// A primitive unsigned integer accepted by [`unsigned`].
643///
644/// This sealed trait is implemented for `u8`, `u16`, `u32`, `u64`, and
645/// `usize`.
646pub trait UnsignedValue: private::SealedUnsigned {}
647
648/// A primitive floating-point value accepted by [`fixed`], [`fixed_upper`],
649/// [`scientific`], [`general`], [`general_upper`], and [`hex_float`].
650///
651/// This sealed trait is implemented for `f32`, `f64`, and
652/// [`struct@f128::f128`].
653pub trait FixedValue: private::SealedFixed {}
654
655macro_rules! impl_signed_value {
656 ($($ty:ty),+ $(,)?) => {
657 $(
658 impl private::SealedSigned for $ty {
659 fn to_i128(self) -> i128 {
660 self as i128
661 }
662 }
663
664 impl SignedValue for $ty {}
665 )+
666 };
667}
668
669macro_rules! impl_unsigned_value {
670 ($($ty:ty),+ $(,)?) => {
671 $(
672 impl private::SealedUnsigned for $ty {
673 fn to_u128(self) -> u128 {
674 self as u128
675 }
676 }
677
678 impl UnsignedValue for $ty {}
679 )+
680 };
681}
682
683impl_signed_value!(i8, i16, i32, i64, isize);
684impl_unsigned_value!(u8, u16, u32, u64, usize);
685
686impl private::SealedFixed for f32 {
687 const FRACTION_BITS: u32 = 23;
688 const EXPONENT_BITS: u32 = 8;
689 const EXPONENT_BIAS: i32 = 127;
690 const HEX_FRACTION_BITS: u32 = 52;
691 const HEX_MIN_NORMAL_EXPONENT: i32 = -1022;
692
693 fn bits(self) -> u128 {
694 self.to_bits() as u128
695 }
696}
697
698impl FixedValue for f32 {}
699
700impl private::SealedFixed for f64 {
701 const FRACTION_BITS: u32 = 52;
702 const EXPONENT_BITS: u32 = 11;
703 const EXPONENT_BIAS: i32 = 1023;
704 const HEX_FRACTION_BITS: u32 = 52;
705 const HEX_MIN_NORMAL_EXPONENT: i32 = -1022;
706
707 fn bits(self) -> u128 {
708 self.to_bits() as u128
709 }
710}
711
712impl FixedValue for f64 {}
713
714impl private::SealedFixed for f128::f128 {
715 const FRACTION_BITS: u32 = 112;
716 const EXPONENT_BITS: u32 = 15;
717 const EXPONENT_BIAS: i32 = 16383;
718 const HEX_FRACTION_BITS: u32 = 112;
719 const HEX_MIN_NORMAL_EXPONENT: i32 = -16382;
720
721 fn bits(self) -> u128 {
722 u128::from_ne_bytes(self.into_inner())
723 }
724}
725
726impl FixedValue for f128::f128 {}
727
728/// Wraps a signed primitive for C `printf`-compatible `d` or `i` formatting.
729///
730/// The wrapper is required for integer precision or [`Signed::space_sign`].
731/// Native Rust formatting is already exact for ordinary `d`/`i`, width, `-`,
732/// `+`, and `0` cases. See the [module documentation](self) for paired Rust and
733/// C examples of every supported conversion and flag.
734pub fn signed<T: SignedValue>(value: T) -> Signed<T> {
735 Signed {
736 value,
737 space_sign: false,
738 }
739}
740
741/// A type-preserving adapter for C `printf` signed-integer formatting.
742#[derive(Clone, Copy)]
743pub struct Signed<T: SignedValue> {
744 value: T,
745 space_sign: bool,
746}
747
748impl<T: SignedValue> Signed<T> {
749 /// Requests C's space-sign flag for a nonnegative value.
750 ///
751 /// A Rust `+` formatting flag overrides the space. For example,
752 /// `format!("{}", signed(7_i8).space_sign())` is equivalent to
753 /// `printf("% hhd", 7)`, while formatting the same wrapper with `{:+}` is
754 /// equivalent to `printf("%+ hhd", 7)`.
755 pub fn space_sign(mut self) -> Self {
756 self.space_sign = true;
757 self
758 }
759}
760
761impl<T: SignedValue> fmt::Display for Signed<T> {
762 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
763 let value = self.value.to_i128();
764 write_integer(
765 f,
766 value.unsigned_abs(),
767 value.is_negative(),
768 self.space_sign,
769 Base::Decimal,
770 )
771 }
772}
773
774/// Wraps an unsigned primitive for C `printf`-compatible `u`, `o`, `x`, or `X`
775/// formatting.
776///
777/// The wrapper is required for integer precision or the `#` flag. Native Rust
778/// formatting is already exact for ordinary conversions, width, `-`, and `0`
779/// cases. See the [module documentation](self) for paired Rust and C examples
780/// of every supported conversion and flag.
781pub fn unsigned<T: UnsignedValue>(value: T) -> Unsigned<T> {
782 Unsigned { value }
783}
784
785/// A type-preserving adapter for C `printf` unsigned-integer formatting.
786#[derive(Clone, Copy)]
787pub struct Unsigned<T: UnsignedValue> {
788 value: T,
789}
790
791impl<T: UnsignedValue> fmt::Display for Unsigned<T> {
792 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
793 write_integer(f, self.value.to_u128(), false, false, Base::Decimal)
794 }
795}
796
797impl<T: UnsignedValue> fmt::Octal for Unsigned<T> {
798 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
799 write_integer(f, self.value.to_u128(), false, false, Base::Octal)
800 }
801}
802
803impl<T: UnsignedValue> fmt::LowerHex for Unsigned<T> {
804 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
805 write_integer(f, self.value.to_u128(), false, false, Base::LowerHex)
806 }
807}
808
809impl<T: UnsignedValue> fmt::UpperHex for Unsigned<T> {
810 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
811 write_integer(f, self.value.to_u128(), false, false, Base::UpperHex)
812 }
813}
814
815/// Wraps a floating-point primitive for C `printf`-compatible `f` formatting.
816///
817/// The wrapper supplies C's default precision of six, exact binary128
818/// formatting, lowercase nonfinite spelling, alternate form at precision zero,
819/// and [`Fixed::space_sign`]. Native Rust formatting is already exact for
820/// finite `f32` and `f64` values when an explicit nonzero precision is present
821/// and none of those wrapper-only behaviors is needed. See the [module
822/// documentation](self) for paired Rust and C examples of every supported type,
823/// spelling, and flag.
824pub fn fixed<T: FixedValue>(value: T) -> Fixed<T> {
825 Fixed {
826 value,
827 space_sign: false,
828 }
829}
830
831/// A type-preserving adapter for C `printf` lowercase fixed-point formatting.
832#[derive(Clone, Copy)]
833pub struct Fixed<T: FixedValue> {
834 value: T,
835 space_sign: bool,
836}
837
838impl<T: FixedValue> Fixed<T> {
839 /// Requests C's space-sign flag for a nonnegative value.
840 ///
841 /// A Rust `+` formatting flag overrides the space. For example,
842 /// `format!("{}", fixed(1.25_f32).space_sign())` is equivalent to
843 /// `printf("% f", (double)1.25f)`, while formatting the same wrapper with
844 /// `{:+}` is equivalent to `printf("%+ f", (double)1.25f)`.
845 pub fn space_sign(mut self) -> Self {
846 self.space_sign = true;
847 self
848 }
849}
850
851impl<T: FixedValue> fmt::Display for Fixed<T> {
852 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
853 write_fixed(
854 f,
855 FloatParts::from_value(self.value),
856 self.space_sign,
857 false,
858 )
859 }
860}
861
862/// Wraps a floating-point primitive for C `printf`-compatible `F` formatting.
863///
864/// This has the same fixed-point semantics as [`fixed`] and uses uppercase
865/// `INF` and `NAN`. See the [module documentation](self) for paired Rust and C
866/// examples of `%F`, `%lF`, `%LF`, and every supported flag.
867pub fn fixed_upper<T: FixedValue>(value: T) -> FixedUpper<T> {
868 FixedUpper {
869 value,
870 space_sign: false,
871 }
872}
873
874/// A type-preserving adapter for C `printf` uppercase fixed-point formatting.
875#[derive(Clone, Copy)]
876pub struct FixedUpper<T: FixedValue> {
877 value: T,
878 space_sign: bool,
879}
880
881impl<T: FixedValue> FixedUpper<T> {
882 /// Requests C's space-sign flag for a nonnegative value.
883 ///
884 /// A Rust `+` formatting flag overrides the space. For example,
885 /// `format!("{}", fixed_upper(1.25_f64).space_sign())` is equivalent to
886 /// `printf("% F", 1.25)`, while formatting the same wrapper with `{:+}` is
887 /// equivalent to `printf("%+ F", 1.25)`.
888 pub fn space_sign(mut self) -> Self {
889 self.space_sign = true;
890 self
891 }
892}
893
894impl<T: FixedValue> fmt::Display for FixedUpper<T> {
895 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
896 write_fixed(f, FloatParts::from_value(self.value), self.space_sign, true)
897 }
898}
899
900/// Wraps a floating-point primitive for C `printf`-compatible `e` or `E`
901/// formatting.
902///
903/// Format the returned wrapper with Rust's `e` or `E` trait to select the
904/// conversion case. It intentionally does not implement [`fmt::Display`]. See
905/// the [module documentation](self) for paired Rust and C examples of every
906/// supported type, spelling, and flag.
907pub fn scientific<T: FixedValue>(value: T) -> Scientific<T> {
908 Scientific {
909 value,
910 space_sign: false,
911 }
912}
913
914/// A type-preserving adapter for C `printf` scientific formatting.
915#[derive(Clone, Copy)]
916pub struct Scientific<T: FixedValue> {
917 value: T,
918 space_sign: bool,
919}
920
921impl<T: FixedValue> Scientific<T> {
922 /// Requests C's space-sign flag for a nonnegative value.
923 ///
924 /// A Rust `+` formatting flag overrides the space. For example,
925 /// `format!("{:e}", scientific(1.25_f32).space_sign())` is equivalent to
926 /// `printf("% e", (double)1.25f)`, while formatting the same wrapper with
927 /// `{:+e}` is equivalent to `printf("%+ e", (double)1.25f)`.
928 pub fn space_sign(mut self) -> Self {
929 self.space_sign = true;
930 self
931 }
932}
933
934impl<T: FixedValue> fmt::LowerExp for Scientific<T> {
935 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
936 write_scientific(
937 f,
938 FloatParts::from_value(self.value),
939 self.space_sign,
940 false,
941 )
942 }
943}
944
945impl<T: FixedValue> fmt::UpperExp for Scientific<T> {
946 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
947 write_scientific(f, FloatParts::from_value(self.value), self.space_sign, true)
948 }
949}
950
951/// Wraps a floating-point primitive for C `printf`-compatible `g` formatting.
952///
953/// Rust has no native general floating-point conversion, so this wrapper is
954/// required for every `%g`, `%lg`, or intended binary128 `%Lg` conversion. See
955/// the [module documentation](self) for paired Rust and C examples of every
956/// supported type, precision, and flag.
957pub fn general<T: FixedValue>(value: T) -> General<T> {
958 General {
959 value,
960 space_sign: false,
961 }
962}
963
964/// A type-preserving adapter for C `printf` lowercase general formatting.
965#[derive(Clone, Copy)]
966pub struct General<T: FixedValue> {
967 value: T,
968 space_sign: bool,
969}
970
971impl<T: FixedValue> General<T> {
972 /// Requests C's space-sign flag for a nonnegative value.
973 ///
974 /// A Rust `+` formatting flag overrides the space. For example,
975 /// `format!("{}", general(1.25_f32).space_sign())` is equivalent to
976 /// `printf("% g", (double)1.25f)`, while formatting the same wrapper with
977 /// `{:+}` is equivalent to `printf("%+ g", (double)1.25f)`.
978 pub fn space_sign(mut self) -> Self {
979 self.space_sign = true;
980 self
981 }
982}
983
984impl<T: FixedValue> fmt::Display for General<T> {
985 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
986 write_general(
987 f,
988 FloatParts::from_value(self.value),
989 self.space_sign,
990 false,
991 )
992 }
993}
994
995/// Wraps a floating-point primitive for C `printf`-compatible `G` formatting.
996///
997/// This has the same general-format semantics as [`general`] and uses `E`,
998/// `INF`, and `NAN`. See the [module documentation](self) for paired Rust and C
999/// examples of `%G`, `%lG`, `%LG`, and every supported flag.
1000pub fn general_upper<T: FixedValue>(value: T) -> GeneralUpper<T> {
1001 GeneralUpper {
1002 value,
1003 space_sign: false,
1004 }
1005}
1006
1007/// A type-preserving adapter for C `printf` uppercase general formatting.
1008#[derive(Clone, Copy)]
1009pub struct GeneralUpper<T: FixedValue> {
1010 value: T,
1011 space_sign: bool,
1012}
1013
1014impl<T: FixedValue> GeneralUpper<T> {
1015 /// Requests C's space-sign flag for a nonnegative value.
1016 ///
1017 /// A Rust `+` formatting flag overrides the space. For example,
1018 /// `format!("{}", general_upper(1.25_f64).space_sign())` is equivalent to
1019 /// `printf("% G", 1.25)`, while formatting the same wrapper with `{:+}` is
1020 /// equivalent to `printf("%+ G", 1.25)`.
1021 pub fn space_sign(mut self) -> Self {
1022 self.space_sign = true;
1023 self
1024 }
1025}
1026
1027impl<T: FixedValue> fmt::Display for GeneralUpper<T> {
1028 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1029 write_general(f, FloatParts::from_value(self.value), self.space_sign, true)
1030 }
1031}
1032
1033/// Wraps a floating-point primitive for C `printf`-compatible `a` or `A`
1034/// formatting.
1035///
1036/// Format the returned wrapper with Rust's `x` or `X` trait to select the
1037/// conversion case. Primitive Rust floats have no native hexadecimal
1038/// formatter, and this adapter intentionally does not implement
1039/// [`fmt::Display`]. See the [module documentation](self) for paired Rust and C
1040/// examples of every supported type, precision, and flag.
1041pub fn hex_float<T: FixedValue>(value: T) -> HexFloat<T> {
1042 HexFloat {
1043 value,
1044 space_sign: false,
1045 }
1046}
1047
1048/// A type-preserving adapter for C `printf` hexadecimal floating formatting.
1049#[derive(Clone, Copy)]
1050pub struct HexFloat<T: FixedValue> {
1051 value: T,
1052 space_sign: bool,
1053}
1054
1055impl<T: FixedValue> HexFloat<T> {
1056 /// Requests C's space-sign flag for a nonnegative value.
1057 ///
1058 /// A Rust `+` formatting flag overrides the space. For example,
1059 /// `format!("{:x}", hex_float(1.5_f32).space_sign())` is equivalent to
1060 /// `printf("% a", (double)1.5f)`, while formatting the same wrapper with
1061 /// `{:+x}` is equivalent to `printf("%+ a", (double)1.5f)`.
1062 pub fn space_sign(mut self) -> Self {
1063 self.space_sign = true;
1064 self
1065 }
1066}
1067
1068impl<T: FixedValue> fmt::LowerHex for HexFloat<T> {
1069 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1070 write_hex_float::<T>(
1071 f,
1072 FloatParts::from_value(self.value),
1073 self.space_sign,
1074 false,
1075 )
1076 }
1077}
1078
1079impl<T: FixedValue> fmt::UpperHex for HexFloat<T> {
1080 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1081 write_hex_float::<T>(f, FloatParts::from_value(self.value), self.space_sign, true)
1082 }
1083}
1084
1085/// Wraps a PROCTOR `char *` mapping for C `printf`-compatible `s` formatting.
1086///
1087/// The selected bytes must be valid UTF-8. Precision and width count bytes,
1088/// and missing precision selects bytes preceding the first NUL. See the
1089/// [module documentation](self) for paired Rust and C examples of `%s`, width,
1090/// left alignment, precision, NUL termination, and multibyte UTF-8.
1091pub fn byte_string(value: &[i8]) -> ByteString<'_> {
1092 ByteString { value }
1093}
1094
1095/// A borrowed adapter for C `printf` string formatting in the valid-UTF-8
1096/// output domain.
1097#[derive(Clone, Copy)]
1098pub struct ByteString<'a> {
1099 value: &'a [i8],
1100}
1101
1102impl fmt::Display for ByteString<'_> {
1103 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1104 let bytes: &[u8] = bytemuck::cast_slice(self.value);
1105 let selected = match f.precision() {
1106 Some(0) => &bytes[..0],
1107 Some(precision) => {
1108 let within_precision = &bytes[..bytes.len().min(precision)];
1109 if let Some(nul) = within_precision.iter().position(|&byte| byte == 0) {
1110 &within_precision[..nul]
1111 } else if bytes.len() >= precision {
1112 &bytes[..precision]
1113 } else {
1114 return Err(fmt::Error);
1115 }
1116 }
1117 None => {
1118 let nul = bytes.iter().position(|&byte| byte == 0).ok_or(fmt::Error)?;
1119 &bytes[..nul]
1120 }
1121 };
1122 let text = std::str::from_utf8(selected).map_err(|_| fmt::Error)?;
1123
1124 let padding = f.width().unwrap_or_default().saturating_sub(selected.len());
1125 let (left_spaces, right_spaces) = match f.align().unwrap_or(Alignment::Right) {
1126 Alignment::Left => (0, padding),
1127 Alignment::Right => (padding, 0),
1128 Alignment::Center => (padding / 2, padding - padding / 2),
1129 };
1130 write_repeated(f, SPACE_PADDING, left_spaces)?;
1131 f.write_str(text)?;
1132 write_repeated(f, SPACE_PADDING, right_spaces)
1133 }
1134}
1135
1136#[derive(Clone, Copy)]
1137enum FloatParts {
1138 Finite {
1139 negative: bool,
1140 significand: u128,
1141 binary_exponent: i32,
1142 },
1143 Infinite {
1144 negative: bool,
1145 },
1146 Nan {
1147 negative: bool,
1148 },
1149}
1150
1151impl FloatParts {
1152 fn from_value<T: FixedValue>(value: T) -> Self {
1153 Self::from_ieee_bits(
1154 value.bits(),
1155 T::FRACTION_BITS,
1156 T::EXPONENT_BITS,
1157 T::EXPONENT_BIAS,
1158 )
1159 }
1160
1161 fn from_ieee_bits(
1162 bits: u128,
1163 fraction_bits: u32,
1164 exponent_bits: u32,
1165 exponent_bias: i32,
1166 ) -> Self {
1167 let negative = bits >> (fraction_bits + exponent_bits) != 0;
1168 let exponent_mask = (1_u128 << exponent_bits) - 1;
1169 let exponent_field = (bits >> fraction_bits) & exponent_mask;
1170 let fraction_mask = (1_u128 << fraction_bits) - 1;
1171 let fraction = bits & fraction_mask;
1172
1173 if exponent_field == exponent_mask {
1174 return if fraction == 0 {
1175 Self::Infinite { negative }
1176 } else {
1177 Self::Nan { negative }
1178 };
1179 }
1180
1181 let (significand, unbiased_exponent) = if exponent_field == 0 {
1182 (fraction, 1 - exponent_bias)
1183 } else {
1184 (
1185 (1_u128 << fraction_bits) | fraction,
1186 exponent_field as i32 - exponent_bias,
1187 )
1188 };
1189 Self::Finite {
1190 negative,
1191 significand,
1192 binary_exponent: unbiased_exponent - fraction_bits as i32,
1193 }
1194 }
1195}
1196
1197fn write_fixed(
1198 f: &mut Formatter<'_>,
1199 parts: FloatParts,
1200 space_sign: bool,
1201 uppercase: bool,
1202) -> fmt::Result {
1203 let (negative, body, finite) = match parts {
1204 FloatParts::Finite {
1205 negative,
1206 significand,
1207 binary_exponent,
1208 } => (
1209 negative,
1210 fixed_body(
1211 significand,
1212 binary_exponent,
1213 f.precision().unwrap_or(6),
1214 f.alternate(),
1215 ),
1216 true,
1217 ),
1218 FloatParts::Infinite { negative } => (
1219 negative,
1220 if uppercase { "INF" } else { "inf" }.to_owned(),
1221 false,
1222 ),
1223 FloatParts::Nan { negative } => (
1224 negative,
1225 if uppercase { "NAN" } else { "nan" }.to_owned(),
1226 false,
1227 ),
1228 };
1229
1230 write_float_field(f, negative, &body, finite, space_sign)
1231}
1232
1233fn write_scientific(
1234 f: &mut Formatter<'_>,
1235 parts: FloatParts,
1236 space_sign: bool,
1237 uppercase: bool,
1238) -> fmt::Result {
1239 let (negative, body, finite) = match parts {
1240 FloatParts::Finite {
1241 negative,
1242 significand,
1243 binary_exponent,
1244 } => (
1245 negative,
1246 scientific_body(
1247 significand,
1248 binary_exponent,
1249 f.precision().unwrap_or(6),
1250 f.alternate(),
1251 uppercase,
1252 ),
1253 true,
1254 ),
1255 FloatParts::Infinite { negative } => (
1256 negative,
1257 if uppercase { "INF" } else { "inf" }.to_owned(),
1258 false,
1259 ),
1260 FloatParts::Nan { negative } => (
1261 negative,
1262 if uppercase { "NAN" } else { "nan" }.to_owned(),
1263 false,
1264 ),
1265 };
1266
1267 write_float_field(f, negative, &body, finite, space_sign)
1268}
1269
1270fn write_general(
1271 f: &mut Formatter<'_>,
1272 parts: FloatParts,
1273 space_sign: bool,
1274 uppercase: bool,
1275) -> fmt::Result {
1276 let (negative, body, finite) = match parts {
1277 FloatParts::Finite {
1278 negative,
1279 significand,
1280 binary_exponent,
1281 } => (
1282 negative,
1283 general_body(
1284 significand,
1285 binary_exponent,
1286 f.precision().unwrap_or(6).max(1),
1287 f.alternate(),
1288 uppercase,
1289 ),
1290 true,
1291 ),
1292 FloatParts::Infinite { negative } => (
1293 negative,
1294 if uppercase { "INF" } else { "inf" }.to_owned(),
1295 false,
1296 ),
1297 FloatParts::Nan { negative } => (
1298 negative,
1299 if uppercase { "NAN" } else { "nan" }.to_owned(),
1300 false,
1301 ),
1302 };
1303
1304 write_float_field(f, negative, &body, finite, space_sign)
1305}
1306
1307fn write_hex_float<T: FixedValue>(
1308 f: &mut Formatter<'_>,
1309 parts: FloatParts,
1310 space_sign: bool,
1311 uppercase: bool,
1312) -> fmt::Result {
1313 match parts {
1314 FloatParts::Finite {
1315 negative,
1316 significand,
1317 binary_exponent,
1318 } => {
1319 let body = hex_float_body(
1320 significand,
1321 binary_exponent,
1322 T::HEX_FRACTION_BITS,
1323 T::HEX_MIN_NORMAL_EXPONENT,
1324 f.precision(),
1325 f.alternate(),
1326 uppercase,
1327 );
1328 write_hex_float_field(f, negative, &body, space_sign, uppercase)
1329 }
1330 FloatParts::Infinite { negative } => write_float_field(
1331 f,
1332 negative,
1333 if uppercase { "INF" } else { "inf" },
1334 false,
1335 space_sign,
1336 ),
1337 FloatParts::Nan { negative } => write_float_field(
1338 f,
1339 negative,
1340 if uppercase { "NAN" } else { "nan" },
1341 false,
1342 space_sign,
1343 ),
1344 }
1345}
1346
1347fn hex_float_body(
1348 significand: u128,
1349 binary_exponent: i32,
1350 fraction_bits: u32,
1351 minimum_normal_exponent: i32,
1352 precision: Option<usize>,
1353 alternate: bool,
1354 uppercase: bool,
1355) -> String {
1356 debug_assert_eq!(fraction_bits % 4, 0);
1357
1358 let (mantissa, displayed_exponent) = if significand == 0 {
1359 (0, 0)
1360 } else {
1361 let highest_bit = (u128::BITS - 1 - significand.leading_zeros()) as i32;
1362 let highest_exponent = highest_bit + binary_exponent;
1363 if highest_exponent >= minimum_normal_exponent {
1364 let shift = fraction_bits as i32 - highest_bit;
1365 debug_assert!(shift >= 0);
1366 (significand << shift as usize, highest_exponent)
1367 } else {
1368 let shift = binary_exponent + fraction_bits as i32 - minimum_normal_exponent;
1369 debug_assert!(shift >= 0);
1370 (significand << shift as usize, minimum_normal_exponent)
1371 }
1372 };
1373
1374 let exact_fraction_digits = fraction_bits as usize / 4;
1375 let (digits, fractional_digits) = match precision {
1376 Some(requested) if requested < exact_fraction_digits => {
1377 let discarded_bits = (exact_fraction_digits - requested) * 4;
1378 let mut rounded = mantissa >> discarded_bits;
1379 let discarded_mask = (1_u128 << discarded_bits) - 1;
1380 let discarded = mantissa & discarded_mask;
1381 let halfway = 1_u128 << (discarded_bits - 1);
1382 if discarded > halfway || (discarded == halfway && rounded & 1 != 0) {
1383 rounded += 1;
1384 }
1385 (
1386 padded_hex_digits(rounded, requested + 1, uppercase),
1387 requested,
1388 )
1389 }
1390 Some(requested) => {
1391 let mut digits = padded_hex_digits(mantissa, exact_fraction_digits + 1, uppercase);
1392 digits.extend(std::iter::repeat_n('0', requested - exact_fraction_digits));
1393 (digits, requested)
1394 }
1395 None => {
1396 let mut digits = padded_hex_digits(mantissa, exact_fraction_digits + 1, uppercase);
1397 while digits.len() > 1 && digits.ends_with('0') {
1398 digits.pop();
1399 }
1400 let fractional_digits = digits.len() - 1;
1401 (digits, fractional_digits)
1402 }
1403 };
1404
1405 let mut body = String::with_capacity(digits.len() + 10);
1406 body.push_str(&digits[..1]);
1407 if fractional_digits != 0 || alternate {
1408 body.push('.');
1409 }
1410 body.push_str(&digits[1..]);
1411 body.push(if uppercase { 'P' } else { 'p' });
1412 if displayed_exponent < 0 {
1413 body.push('-');
1414 } else {
1415 body.push('+');
1416 }
1417 body.push_str(&displayed_exponent.unsigned_abs().to_string());
1418 body
1419}
1420
1421fn padded_hex_digits(value: u128, width: usize, uppercase: bool) -> String {
1422 let digits = if uppercase {
1423 format!("{value:X}")
1424 } else {
1425 format!("{value:x}")
1426 };
1427 if digits.len() >= width {
1428 return digits;
1429 }
1430
1431 let mut padded = String::with_capacity(width);
1432 padded.extend(std::iter::repeat_n('0', width - digits.len()));
1433 padded.push_str(&digits);
1434 padded
1435}
1436
1437fn write_hex_float_field(
1438 f: &mut Formatter<'_>,
1439 negative: bool,
1440 body: &str,
1441 space_sign: bool,
1442 uppercase: bool,
1443) -> fmt::Result {
1444 let sign = if negative {
1445 "-"
1446 } else if f.sign_plus() {
1447 "+"
1448 } else if space_sign {
1449 " "
1450 } else {
1451 ""
1452 };
1453 let prefix = if uppercase { "0X" } else { "0x" };
1454 let content_width = sign.len() + prefix.len() + body.len();
1455 let padding = f.width().unwrap_or_default().saturating_sub(content_width);
1456 let alignment = f.align().unwrap_or(Alignment::Right);
1457 let zero_padding = f.sign_aware_zero_pad() && alignment == Alignment::Right;
1458 let (left_spaces, right_spaces) = if zero_padding {
1459 (0, 0)
1460 } else {
1461 match alignment {
1462 Alignment::Left => (0, padding),
1463 Alignment::Right => (padding, 0),
1464 Alignment::Center => (padding / 2, padding - padding / 2),
1465 }
1466 };
1467
1468 write_repeated(f, SPACE_PADDING, left_spaces)?;
1469 f.write_str(sign)?;
1470 f.write_str(prefix)?;
1471 if zero_padding {
1472 write_repeated(f, ZERO_PADDING, padding)?;
1473 }
1474 f.write_str(body)?;
1475 write_repeated(f, SPACE_PADDING, right_spaces)
1476}
1477
1478fn write_float_field(
1479 f: &mut Formatter<'_>,
1480 negative: bool,
1481 body: &str,
1482 finite: bool,
1483 space_sign: bool,
1484) -> fmt::Result {
1485 let sign = if negative {
1486 "-"
1487 } else if f.sign_plus() {
1488 "+"
1489 } else if space_sign {
1490 " "
1491 } else {
1492 ""
1493 };
1494 let content_width = sign.len() + body.len();
1495 let padding = f.width().unwrap_or_default().saturating_sub(content_width);
1496 let alignment = f.align().unwrap_or(Alignment::Right);
1497 let zero_padding = finite && f.sign_aware_zero_pad() && alignment == Alignment::Right;
1498 let (left_spaces, right_spaces) = if zero_padding {
1499 (0, 0)
1500 } else {
1501 match alignment {
1502 Alignment::Left => (0, padding),
1503 Alignment::Right => (padding, 0),
1504 Alignment::Center => (padding / 2, padding - padding / 2),
1505 }
1506 };
1507
1508 write_repeated(f, SPACE_PADDING, left_spaces)?;
1509 f.write_str(sign)?;
1510 if zero_padding {
1511 write_repeated(f, ZERO_PADDING, padding)?;
1512 }
1513 f.write_str(body)?;
1514 write_repeated(f, SPACE_PADDING, right_spaces)
1515}
1516
1517fn scientific_body(
1518 significand: u128,
1519 binary_exponent: i32,
1520 precision: usize,
1521 alternate: bool,
1522 uppercase: bool,
1523) -> String {
1524 let (digits, decimal_exponent) =
1525 rounded_significant_digits(significand, binary_exponent, precision + 1);
1526 scientific_body_from_digits(&digits, decimal_exponent, alternate, uppercase)
1527}
1528
1529fn rounded_significant_digits(
1530 significand: u128,
1531 binary_exponent: i32,
1532 significant_digits: usize,
1533) -> (String, i32) {
1534 debug_assert_ne!(significant_digits, 0);
1535 let mut decimal_exponent = if significand == 0 {
1536 0
1537 } else {
1538 decimal_exponent(significand, binary_exponent)
1539 };
1540
1541 let rounded = if decimal_exponent <= 0 {
1542 let decimal_shift = significant_digits - 1 + (-decimal_exponent) as usize;
1543 scale_and_round(significand, binary_exponent, decimal_shift)
1544 } else if significant_digits > decimal_exponent as usize {
1545 scale_and_round(
1546 significand,
1547 binary_exponent,
1548 significant_digits - 1 - decimal_exponent as usize,
1549 )
1550 } else {
1551 scale_down_and_round(
1552 significand,
1553 binary_exponent,
1554 decimal_exponent as usize + 1 - significant_digits,
1555 )
1556 };
1557
1558 let expected_digits = significant_digits;
1559 let mut digits = rounded.to_str_radix(10);
1560 match digits.len().cmp(&expected_digits) {
1561 std::cmp::Ordering::Greater => {
1562 decimal_exponent += 1;
1563 digits.pop();
1564 }
1565 std::cmp::Ordering::Less => {
1566 digits.insert_str(0, &"0".repeat(expected_digits - digits.len()));
1567 }
1568 std::cmp::Ordering::Equal => {}
1569 }
1570
1571 (digits, decimal_exponent)
1572}
1573
1574fn scientific_body_from_digits(
1575 digits: &str,
1576 decimal_exponent: i32,
1577 alternate: bool,
1578 uppercase: bool,
1579) -> String {
1580 let precision = digits.len() - 1;
1581 let mut body = String::with_capacity(digits.len() + 8);
1582 body.push_str(&digits[..1]);
1583 if precision != 0 || alternate {
1584 body.push('.');
1585 }
1586 body.push_str(&digits[1..]);
1587 body.push(if uppercase { 'E' } else { 'e' });
1588 if decimal_exponent < 0 {
1589 body.push('-');
1590 } else {
1591 body.push('+');
1592 }
1593 let exponent_digits = decimal_exponent.unsigned_abs().to_string();
1594 if exponent_digits.len() < 2 {
1595 body.push('0');
1596 }
1597 body.push_str(&exponent_digits);
1598 body
1599}
1600
1601fn general_body(
1602 significand: u128,
1603 binary_exponent: i32,
1604 precision: usize,
1605 alternate: bool,
1606 uppercase: bool,
1607) -> String {
1608 let (digits, decimal_exponent) =
1609 rounded_significant_digits(significand, binary_exponent, precision);
1610 let use_scientific =
1611 decimal_exponent < -4 || (decimal_exponent >= 0 && decimal_exponent as usize >= precision);
1612
1613 if use_scientific {
1614 let mut body = scientific_body_from_digits(&digits, decimal_exponent, alternate, uppercase);
1615 if !alternate {
1616 trim_scientific_fraction(&mut body);
1617 }
1618 body
1619 } else {
1620 let fractional_digits = (precision as i32 - (decimal_exponent + 1)) as usize;
1621 let mut body = fixed_body(significand, binary_exponent, fractional_digits, alternate);
1622 if !alternate {
1623 trim_fixed_fraction(&mut body);
1624 }
1625 body
1626 }
1627}
1628
1629fn trim_fixed_fraction(body: &mut String) {
1630 if let Some(point) = body.find('.') {
1631 while body.as_bytes().last() == Some(&b'0') {
1632 body.pop();
1633 }
1634 if body.len() == point + 1 {
1635 body.pop();
1636 }
1637 }
1638}
1639
1640fn trim_scientific_fraction(body: &mut String) {
1641 let exponent = body
1642 .find(['e', 'E'])
1643 .expect("scientific body always has an exponent marker");
1644 let suffix = body.split_off(exponent);
1645 trim_fixed_fraction(body);
1646 body.push_str(&suffix);
1647}
1648
1649fn decimal_exponent(significand: u128, binary_exponent: i32) -> i32 {
1650 debug_assert_ne!(significand, 0);
1651 let highest_binary_exponent =
1652 (u128::BITS - 1 - significand.leading_zeros()) as i32 + binary_exponent;
1653 let mut exponent =
1654 (f64::from(highest_binary_exponent) * std::f64::consts::LOG10_2).floor() as i32;
1655
1656 while compare_with_power_of_ten(significand, binary_exponent, exponent).is_lt() {
1657 exponent -= 1;
1658 }
1659 while !compare_with_power_of_ten(significand, binary_exponent, exponent + 1).is_lt() {
1660 exponent += 1;
1661 }
1662 exponent
1663}
1664
1665fn compare_with_power_of_ten(
1666 significand: u128,
1667 binary_exponent: i32,
1668 decimal_exponent: i32,
1669) -> std::cmp::Ordering {
1670 let mut left = BigUint::from(significand);
1671 let mut right = BigUint::from(1_u8);
1672
1673 if binary_exponent >= 0 {
1674 left <<= binary_exponent as usize;
1675 } else {
1676 right <<= (-binary_exponent) as usize;
1677 }
1678
1679 if decimal_exponent >= 0 {
1680 right *= pow_ten(decimal_exponent as usize);
1681 } else {
1682 left *= pow_ten((-decimal_exponent) as usize);
1683 }
1684 left.cmp(&right)
1685}
1686
1687fn scale_down_and_round(significand: u128, binary_exponent: i32, decimal_places: usize) -> BigUint {
1688 if significand == 0 {
1689 return BigUint::from(0_u8);
1690 }
1691
1692 let mut numerator = BigUint::from(significand);
1693 let mut denominator = pow_five(decimal_places);
1694 let binary_shift = i64::from(binary_exponent) - decimal_places as i64;
1695 if binary_shift >= 0 {
1696 numerator <<= binary_shift as usize;
1697 } else {
1698 denominator <<= (-binary_shift) as usize;
1699 }
1700
1701 let quotient = &numerator / &denominator;
1702 let remainder = numerator - "ient * &denominator;
1703 let twice_remainder = remainder << 1;
1704 if twice_remainder > denominator || (twice_remainder == denominator && quotient.bit(0)) {
1705 quotient + 1_u8
1706 } else {
1707 quotient
1708 }
1709}
1710
1711fn fixed_body(
1712 significand: u128,
1713 binary_exponent: i32,
1714 precision: usize,
1715 alternate: bool,
1716) -> String {
1717 let scaled = scale_and_round(significand, binary_exponent, precision);
1718 let digits = scaled.to_str_radix(10);
1719
1720 if precision == 0 {
1721 if alternate {
1722 return digits + ".";
1723 }
1724 return digits;
1725 }
1726
1727 if digits.len() > precision {
1728 let point = digits.len() - precision;
1729 let mut result = String::with_capacity(digits.len() + 1);
1730 result.push_str(&digits[..point]);
1731 result.push('.');
1732 result.push_str(&digits[point..]);
1733 result
1734 } else {
1735 let leading_zeros = precision - digits.len();
1736 let mut result = String::with_capacity(precision + 2);
1737 result.push_str("0.");
1738 result.extend(std::iter::repeat_n('0', leading_zeros));
1739 result.push_str(&digits);
1740 result
1741 }
1742}
1743
1744fn scale_and_round(significand: u128, binary_exponent: i32, precision: usize) -> BigUint {
1745 if significand == 0 {
1746 return BigUint::from(0_u8);
1747 }
1748
1749 let mut numerator = BigUint::from(significand) * pow_five(precision);
1750 if binary_exponent >= 0 {
1751 return numerator << (precision + binary_exponent as usize);
1752 }
1753
1754 let denominator_shift = (-binary_exponent) as usize;
1755 if precision >= denominator_shift {
1756 return numerator << (precision - denominator_shift);
1757 }
1758
1759 let shift = denominator_shift - precision;
1760 let quotient = &numerator >> shift;
1761 numerator -= "ient << shift;
1762 let halfway = BigUint::from(1_u8) << (shift - 1);
1763 if numerator > halfway || (numerator == halfway && quotient.bit(0)) {
1764 quotient + 1_u8
1765 } else {
1766 quotient
1767 }
1768}
1769
1770fn pow_five(mut exponent: usize) -> BigUint {
1771 let mut result = BigUint::from(1_u8);
1772 let mut base = BigUint::from(5_u8);
1773 while exponent != 0 {
1774 if exponent & 1 != 0 {
1775 result *= &base;
1776 }
1777 exponent >>= 1;
1778 if exponent != 0 {
1779 base = &base * &base;
1780 }
1781 }
1782 result
1783}
1784
1785fn pow_ten(exponent: usize) -> BigUint {
1786 pow_five(exponent) << exponent
1787}
1788
1789#[derive(Clone, Copy, Eq, PartialEq)]
1790enum Base {
1791 Decimal,
1792 Octal,
1793 LowerHex,
1794 UpperHex,
1795}
1796
1797impl Base {
1798 fn radix(self) -> u128 {
1799 match self {
1800 Self::Decimal => 10,
1801 Self::Octal => 8,
1802 Self::LowerHex | Self::UpperHex => 16,
1803 }
1804 }
1805
1806 fn digit(self, value: u128) -> u8 {
1807 match value {
1808 0..=9 => b'0' + value as u8,
1809 10..=15 if self == Self::UpperHex => b'A' + (value - 10) as u8,
1810 10..=15 => b'a' + (value - 10) as u8,
1811 _ => unreachable!(),
1812 }
1813 }
1814}
1815
1816fn write_integer(
1817 f: &mut Formatter<'_>,
1818 magnitude: u128,
1819 negative: bool,
1820 space_sign: bool,
1821 base: Base,
1822) -> fmt::Result {
1823 let mut digit_buffer = [0_u8; 128];
1824 let mut digit_start = digit_buffer.len();
1825 let precision = f.precision();
1826
1827 if magnitude != 0 || precision != Some(0) {
1828 let radix = base.radix();
1829 let mut remaining = magnitude;
1830 loop {
1831 digit_start -= 1;
1832 digit_buffer[digit_start] = base.digit(remaining % radix);
1833 remaining /= radix;
1834 if remaining == 0 {
1835 break;
1836 }
1837 }
1838 }
1839
1840 let digits = &digit_buffer[digit_start..];
1841 let mut precision_zeros = precision.unwrap_or_default().saturating_sub(digits.len());
1842 let alternate = f.alternate();
1843
1844 if alternate && base == Base::Octal && precision_zeros == 0 && digits.first() != Some(&b'0') {
1845 precision_zeros = 1;
1846 }
1847
1848 let prefix = if alternate && magnitude != 0 {
1849 match base {
1850 Base::LowerHex => "0x",
1851 Base::UpperHex => "0X",
1852 Base::Decimal | Base::Octal => "",
1853 }
1854 } else {
1855 ""
1856 };
1857 let sign = if negative {
1858 "-"
1859 } else if f.sign_plus() {
1860 "+"
1861 } else if space_sign {
1862 " "
1863 } else {
1864 ""
1865 };
1866
1867 let content_width = sign.len() + prefix.len() + precision_zeros + digits.len();
1868 let padding = f.width().unwrap_or_default().saturating_sub(content_width);
1869 let alignment = f.align().unwrap_or(Alignment::Right);
1870 let zero_padding =
1871 f.sign_aware_zero_pad() && precision.is_none() && alignment == Alignment::Right;
1872
1873 let (left_spaces, right_spaces) = if zero_padding {
1874 (0, 0)
1875 } else {
1876 match alignment {
1877 Alignment::Left => (0, padding),
1878 Alignment::Right => (padding, 0),
1879 Alignment::Center => (padding / 2, padding - padding / 2),
1880 }
1881 };
1882
1883 write_repeated(f, SPACE_PADDING, left_spaces)?;
1884 f.write_str(sign)?;
1885 f.write_str(prefix)?;
1886 if zero_padding {
1887 write_repeated(f, ZERO_PADDING, padding)?;
1888 }
1889 write_repeated(f, ZERO_PADDING, precision_zeros)?;
1890 // SAFETY: `digits` contains only ASCII bytes produced by `Base::digit`.
1891 f.write_str(unsafe { std::str::from_utf8_unchecked(digits) })?;
1892 write_repeated(f, SPACE_PADDING, right_spaces)
1893}
1894
1895fn write_repeated(f: &mut Formatter<'_>, chunk: &str, mut count: usize) -> fmt::Result {
1896 while count >= chunk.len() {
1897 f.write_str(chunk)?;
1898 count -= chunk.len();
1899 }
1900 if count != 0 {
1901 f.write_str(&chunk[..count])?;
1902 }
1903 Ok(())
1904}