mod dtoa;
mod printf;
mod spec;
mod strings;
mod template;
use std::fmt;
use dtoa::{EXACT_DECIMAL_PLACES, FloatStyle, Presentation, format_float};
pub use printf::PrintfFormat;
pub use spec::FormatSpec;
pub use strings::{str_ascii, str_repr};
pub use template::{StrTemplate, TemplateValue};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FormatError {
Value(String),
Type(String),
Key(String),
Index(String),
Unsupported(String),
}
crate::archive_enum!(FormatError {
Value(v0),
Type(v0),
Key(v0),
Index(v0),
Unsupported(v0),
});
impl fmt::Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Value(msg) | Self::Type(msg) | Self::Index(msg) => f.write_str(msg),
Self::Key(name) => write!(f, "unknown format field {name:?}"),
Self::Unsupported(what) => write!(f, "unsupported format feature: {what}"),
}
}
}
impl std::error::Error for FormatError {}
pub const MAX_FIELD_SIZE: usize = 1 << 20;
fn bounded_field(size: Option<usize>, what: &str) -> Result<Option<usize>, FormatError> {
match size {
Some(size) if size > MAX_FIELD_SIZE => Err(FormatError::Unsupported(format!(
"a {what} of {size} (more than {MAX_FIELD_SIZE})"
))),
_ => Ok(size),
}
}
pub fn repr(x: f64) -> String {
format_float(x, FloatStyle::REPR)
}
pub fn integer(x: f64) -> String {
if !x.is_finite() {
return repr(x);
}
let digits = format!("{:.0}", x.trunc().abs());
if x <= -1.0 {
format!("-{digits}")
} else {
digits
}
}
pub fn fixed(x: f64, precision: usize) -> String {
if x.is_finite() && precision <= EXACT_DECIMAL_PLACES {
format!("{x:.precision$}")
} else {
format_float(x, FloatStyle::new(Presentation::Fixed, precision))
}
}
pub fn exponential(x: f64, precision: usize) -> String {
format_float(x, FloatStyle::new(Presentation::Exponent, precision))
}
pub fn general(x: f64, precision: usize) -> String {
format_float(x, FloatStyle::new(Presentation::General, precision))
}
pub fn general_alternate(x: f64, precision: usize) -> String {
format_float(
x,
FloatStyle {
alternate: true,
..FloatStyle::new(Presentation::General, precision)
},
)
}
pub fn auto_format(template: &str, value: f64) -> Result<String, FormatError> {
auto_format_value(template, value, false)
}
pub fn auto_format_value(template: &str, value: f64, integer: bool) -> Result<String, FormatError> {
match PrintfFormat::parse(template).and_then(|format| format.format(value)) {
Err(FormatError::Type(_) | FormatError::Value(_)) if integer => {
let whole = TemplateValue::Int(value as i64);
StrTemplate::parse_positional_int(template)?.render_values(&[whole], |text| text)
}
Err(FormatError::Type(_) | FormatError::Value(_)) => {
StrTemplate::parse_positional(template)?.render(value, None, |text| text)
}
printed => printed,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn auto_format_falls_back_to_str_format() {
assert_eq!(auto_format("%g", 3.0), Ok("3".to_owned()));
assert_eq!(auto_format("{:.0%}", 0.43), Ok("43%".to_owned()));
assert_eq!(auto_format("const", 1.0), Ok("const".to_owned()));
assert_eq!(auto_format("%d", f64::NAN), Ok("%d".to_owned()));
assert!(auto_format("{y}", 1.0).is_err());
}
#[test]
fn convenience_functions() {
assert_eq!(repr(10_000_000.0), "10000000.0");
assert_eq!(integer(-1500.25), "-1500");
assert_eq!(integer(-0.5), "0");
assert_eq!(integer(1e20), "100000000000000000000");
assert_eq!(fixed(-0.0, 1), "-0.0");
assert_eq!(fixed(0.25, 70_000).len(), 70_002);
assert_eq!(exponential(1500.25, 1), "1.5e+03");
assert_eq!(general(1234.5678, 6), "1234.57");
assert_eq!(general_alternate(1.234_567_89, 8), "1.2345679");
assert_eq!(general_alternate(1e-7, 4), "1.000e-07");
}
#[test]
fn fixed_fast_path_matches_the_general_layout() {
let mut rng = crate::rng::SplitMix64::new(7);
let mut values = vec![0.0, -0.0, 0.5, 1.5, 2.5, -2.5, 0.125, -0.001, 1e300, 5e-324];
for _ in 0..5000 {
let magnitude = 10f64.powi((rng.next_u64() % 40) as i32 - 20);
let sign = if rng.next_u64().is_multiple_of(2) {
1.0
} else {
-1.0
};
values.push(sign * rng.next_f64() * magnitude);
}
for value in values {
for precision in 0..=12 {
assert_eq!(
fixed(value, precision),
format_float(value, FloatStyle::new(Presentation::Fixed, precision)),
"{value:e} with {precision} digits"
);
}
}
}
}