|
| 1 | +//! Python format mini-language (`__format__`) support. |
| 2 | +//! |
| 3 | +//! Integers (`UBig`/`IBig`) delegate to Python's own `int.__format__` (Python ints are |
| 4 | +//! arbitrary precision, so there is no loss). Floats (`FBig`/`DBig`) are rendered in decimal |
| 5 | +//! (an `FBig` is first converted to base 10) using dashu's precision-aware formatting, then |
| 6 | +//! the Python spec's layout (sign / width / align / fill / zero-pad / grouping) and the |
| 7 | +//! scientific exponent are normalized to CPython conventions. |
| 8 | +
|
| 9 | +use dashu_float::DBig; |
| 10 | +use pyo3::PyResult; |
| 11 | +use pyo3::exceptions::PyValueError; |
| 12 | + |
| 13 | +/// A parsed Python format spec: `[[fill]align][sign][#][0][width][grouping][.precision][type]`. |
| 14 | +#[allow(dead_code)] |
| 15 | +pub struct Spec { |
| 16 | + pub fill: char, |
| 17 | + pub align: Option<char>, // '<' '>' '=' '^' |
| 18 | + pub sign: char, // '+' '-' ' ' |
| 19 | + pub alt: bool, // '#' |
| 20 | + pub zero: bool, // '0' (zero-pad) |
| 21 | + pub width: Option<usize>, |
| 22 | + pub group: Option<char>, // ',' or '_' |
| 23 | + pub prec: Option<usize>, |
| 24 | + pub ty: char, // '\0' = none |
| 25 | +} |
| 26 | + |
| 27 | +const FLOAT_TYPES: &str = "eEfFgGn%"; |
| 28 | + |
| 29 | +pub fn parse(spec: &str) -> PyResult<Spec> { |
| 30 | + let chars: Vec<char> = spec.chars().collect(); |
| 31 | + let mut i = 0; |
| 32 | + let n = chars.len(); |
| 33 | + |
| 34 | + // [[fill]align] |
| 35 | + let mut fill = ' '; |
| 36 | + let mut align = None; |
| 37 | + if n >= 2 && "<>=^".contains(chars[1]) { |
| 38 | + fill = chars[0]; |
| 39 | + align = Some(chars[1]); |
| 40 | + i = 2; |
| 41 | + } else if n >= 1 && "<>=^".contains(chars[0]) { |
| 42 | + align = Some(chars[0]); |
| 43 | + i = 1; |
| 44 | + } |
| 45 | + |
| 46 | + // [sign] |
| 47 | + let mut sign = '-'; |
| 48 | + if i < n && "+- ".contains(chars[i]) { |
| 49 | + sign = chars[i]; |
| 50 | + i += 1; |
| 51 | + } |
| 52 | + |
| 53 | + // [#] |
| 54 | + let mut alt = false; |
| 55 | + if i < n && chars[i] == '#' { |
| 56 | + alt = true; |
| 57 | + i += 1; |
| 58 | + } |
| 59 | + |
| 60 | + // [0] |
| 61 | + let mut zero = false; |
| 62 | + if i < n && chars[i] == '0' { |
| 63 | + zero = true; |
| 64 | + i += 1; |
| 65 | + } |
| 66 | + |
| 67 | + // [width] |
| 68 | + let mut width = None; |
| 69 | + let start = i; |
| 70 | + while i < n && chars[i].is_ascii_digit() { |
| 71 | + i += 1; |
| 72 | + } |
| 73 | + if i > start { |
| 74 | + width = Some(chars[start..i].iter().collect::<String>().parse().unwrap()); |
| 75 | + } |
| 76 | + |
| 77 | + // [grouping] |
| 78 | + let mut group = None; |
| 79 | + if i < n && (chars[i] == ',' || chars[i] == '_') { |
| 80 | + group = Some(chars[i]); |
| 81 | + i += 1; |
| 82 | + } |
| 83 | + |
| 84 | + // [.precision] |
| 85 | + let mut prec = None; |
| 86 | + if i < n && chars[i] == '.' { |
| 87 | + i += 1; |
| 88 | + let start = i; |
| 89 | + while i < n && chars[i].is_ascii_digit() { |
| 90 | + i += 1; |
| 91 | + } |
| 92 | + if i == start { |
| 93 | + return Err(PyValueError::new_err("missing precision in format spec")); |
| 94 | + } |
| 95 | + prec = Some(chars[start..i].iter().collect::<String>().parse().unwrap()); |
| 96 | + } |
| 97 | + |
| 98 | + // [type] |
| 99 | + let ty = if i < n { |
| 100 | + let t = chars[i]; |
| 101 | + if i + 1 != n { |
| 102 | + return Err(PyValueError::new_err(format!("invalid format specifier '{spec}'"))); |
| 103 | + } |
| 104 | + t |
| 105 | + } else { |
| 106 | + '\0' |
| 107 | + }; |
| 108 | + |
| 109 | + Ok(Spec { |
| 110 | + fill, |
| 111 | + align, |
| 112 | + sign, |
| 113 | + alt, |
| 114 | + zero, |
| 115 | + width, |
| 116 | + group, |
| 117 | + prec, |
| 118 | + ty, |
| 119 | + }) |
| 120 | +} |
| 121 | + |
| 122 | +impl Spec { |
| 123 | + fn is_float_type(&self) -> bool { |
| 124 | + self.ty == '\0' || FLOAT_TYPES.contains(self.ty) |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +/// Render a `DBig` (base-10 float) according to a parsed Python spec, including layout. |
| 129 | +pub fn format_dbig(d: &DBig, spec_str: &str) -> PyResult<String> { |
| 130 | + let s = parse(spec_str)?; |
| 131 | + if !s.is_float_type() { |
| 132 | + let ty_str = if s.ty == '\0' { |
| 133 | + String::new() |
| 134 | + } else { |
| 135 | + s.ty.to_string() |
| 136 | + }; |
| 137 | + return Err(PyValueError::new_err(format!( |
| 138 | + "unknown format code '{ty_str}' for object of type 'float'" |
| 139 | + ))); |
| 140 | + } |
| 141 | + |
| 142 | + // Produce the unsigned (no sign policy) numeric body in decimal. |
| 143 | + let (negative, body) = render_body(d, &s)?; |
| 144 | + let signed = apply_sign(body, negative, s.sign); |
| 145 | + let grouped = apply_grouping(signed, s.group); |
| 146 | + Ok(apply_layout(grouped, &s)) |
| 147 | +} |
| 148 | + |
| 149 | +/// Render the magnitude as a decimal string (without sign), per the spec's type. |
| 150 | +fn render_body(d: &DBig, s: &Spec) -> PyResult<(bool, String)> { |
| 151 | + // infinite values: let dashu render, then strip the sign |
| 152 | + let (neg, raw) = match s.ty { |
| 153 | + 'e' | 'E' => { |
| 154 | + let p = s.prec.unwrap_or(6); |
| 155 | + let mut raw = format!("{:.*e}", p, d); |
| 156 | + raw = normalize_sci(raw, s.ty == 'E'); |
| 157 | + strip_sign(&raw) |
| 158 | + } |
| 159 | + 'f' | 'F' => { |
| 160 | + let p = s.prec.unwrap_or(6); |
| 161 | + strip_sign(&format!("{:.*}", p, d)) |
| 162 | + } |
| 163 | + '%' => { |
| 164 | + let p = s.prec.unwrap_or(6); |
| 165 | + // ×100, fixed, then a trailing '%' |
| 166 | + let scaled = d.clone() * DBig::from(100u8); |
| 167 | + let (neg, mut body) = strip_sign(&format!("{:.*}", p, &scaled)); |
| 168 | + body.push('%'); |
| 169 | + (neg, body) |
| 170 | + } |
| 171 | + 'g' | 'G' | 'n' | '\0' => { |
| 172 | + // general / default: full plain decimal (dashu Display), with optional precision |
| 173 | + // limiting significant digits via a re-round. |
| 174 | + if let Some(p) = s.prec { |
| 175 | + let rounded = d.clone().with_precision(p.max(1)).value(); |
| 176 | + strip_sign(&format!("{}", rounded)) |
| 177 | + } else { |
| 178 | + strip_sign(&format!("{}", d)) |
| 179 | + } |
| 180 | + } |
| 181 | + _ => unreachable!(), |
| 182 | + }; |
| 183 | + Ok((neg, raw)) |
| 184 | +} |
| 185 | + |
| 186 | +/// Split a leading '-' from a dashu-rendered string; return (is_negative, magnitude_str). |
| 187 | +fn strip_sign(s: &str) -> (bool, String) { |
| 188 | + if let Some(rest) = s.strip_prefix('-') { |
| 189 | + (true, rest.to_string()) |
| 190 | + } else if let Some(rest) = s.strip_prefix('+') { |
| 191 | + (false, rest.to_string()) |
| 192 | + } else { |
| 193 | + (false, s.to_string()) |
| 194 | + } |
| 195 | +} |
| 196 | + |
| 197 | +/// Reattach the sign according to the Python sign option ('+', '-', ' '). |
| 198 | +fn apply_sign(body: String, negative: bool, sign: char) -> String { |
| 199 | + if negative { |
| 200 | + format!("-{body}") |
| 201 | + } else { |
| 202 | + match sign { |
| 203 | + '+' => format!("+{body}"), |
| 204 | + ' ' => format!(" {body}"), |
| 205 | + _ => body, |
| 206 | + } |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +/// Insert a grouping separator every 3 digits in the integer part. |
| 211 | +fn apply_grouping(mut body: String, group: Option<char>) -> String { |
| 212 | + let sep = match group { |
| 213 | + Some(c) => c, |
| 214 | + None => return body, |
| 215 | + }; |
| 216 | + // locate the integer-part digits: from start (or after a leading sign) up to '.'/'e'/'E'/'%' |
| 217 | + let bytes: Vec<char> = body.chars().collect(); |
| 218 | + let start = if bytes |
| 219 | + .first() |
| 220 | + .map(|c| *c == '-' || *c == '+') |
| 221 | + .unwrap_or(false) |
| 222 | + { |
| 223 | + 1 |
| 224 | + } else { |
| 225 | + 0 |
| 226 | + }; |
| 227 | + let end = bytes |
| 228 | + .iter() |
| 229 | + .enumerate() |
| 230 | + .skip(start) |
| 231 | + .find(|(_, c)| **c == '.' || **c == 'e' || **c == 'E' || **c == '%') |
| 232 | + .map(|(i, _)| i) |
| 233 | + .unwrap_or(bytes.len()); |
| 234 | + if end <= start { |
| 235 | + return body; |
| 236 | + } |
| 237 | + let int_digits: Vec<char> = bytes[start..end].to_vec(); |
| 238 | + let m = int_digits.len(); |
| 239 | + let mut grouped = String::new(); |
| 240 | + for (k, c) in int_digits.iter().enumerate() { |
| 241 | + if k > 0 && (m - k) % 3 == 0 { |
| 242 | + grouped.push(sep); |
| 243 | + } |
| 244 | + grouped.push(*c); |
| 245 | + } |
| 246 | + // reassemble |
| 247 | + let prefix: String = bytes[..start].iter().collect(); |
| 248 | + let suffix: String = bytes[end..].iter().collect(); |
| 249 | + body = format!("{prefix}{grouped}{suffix}"); |
| 250 | + body |
| 251 | +} |
| 252 | + |
| 253 | +/// Apply width / align / fill / zero-pad. |
| 254 | +fn apply_layout(mut body: String, s: &Spec) -> String { |
| 255 | + let width = match s.width { |
| 256 | + Some(w) => w, |
| 257 | + None => return body, |
| 258 | + }; |
| 259 | + let pad = width.saturating_sub(body.chars().count()); |
| 260 | + if pad == 0 { |
| 261 | + return body; |
| 262 | + } |
| 263 | + let (fill, align) = if s.zero { |
| 264 | + ('0', s.align.unwrap_or('=')) |
| 265 | + } else { |
| 266 | + (s.fill, s.align.unwrap_or('>')) |
| 267 | + }; |
| 268 | + let pad_str: String = std::iter::repeat_n(fill, pad).collect(); |
| 269 | + match align { |
| 270 | + '<' => body.push_str(&pad_str), |
| 271 | + '>' => body = format!("{pad_str}{body}"), |
| 272 | + '^' => { |
| 273 | + let half = pad / 2; |
| 274 | + body = format!( |
| 275 | + "{}{}{}", |
| 276 | + std::iter::repeat_n(fill, half).collect::<String>(), |
| 277 | + body, |
| 278 | + std::iter::repeat_n(fill, pad - half).collect::<String>() |
| 279 | + ); |
| 280 | + } |
| 281 | + '=' => { |
| 282 | + // padding after the sign |
| 283 | + let (sign, rest) = if body.starts_with('-') || body.starts_with('+') { |
| 284 | + body.split_at(1) |
| 285 | + } else { |
| 286 | + ("", body.as_str()) |
| 287 | + }; |
| 288 | + body = format!("{sign}{pad_str}{rest}"); |
| 289 | + } |
| 290 | + _ => {} |
| 291 | + } |
| 292 | + body |
| 293 | +} |
| 294 | + |
| 295 | +/// Normalize dashu's bare scientific exponent (`1.5e0`) to CPython's form (`1.5e+00`). |
| 296 | +fn normalize_sci(s: String, upper: bool) -> String { |
| 297 | + let idx = s.find(['e', 'E']); |
| 298 | + match idx { |
| 299 | + Some(i) => { |
| 300 | + let (head, tail) = s.split_at(i); |
| 301 | + let exp_part = &tail[1..]; |
| 302 | + let exp: isize = exp_part.parse().unwrap_or(0); |
| 303 | + let marker = if upper { 'E' } else { 'e' }; |
| 304 | + format!("{head}{marker}{exp:+03}") |
| 305 | + } |
| 306 | + None => s, |
| 307 | + } |
| 308 | +} |
0 commit comments