1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
//! # Integer formatting.
//!
//! Both [UBig] and [IBig] support rust formatter traits ([Display], [LowerHex], etc.). The sign,
//! width, filling and padding options of the formatter are supported for all formatter traits except
//! [Debug]. Different from other formatters, [Debug] will display the least and the most significant
//! digits of the integer, but omitting the middle digits when it's too large. This helps to improve the
//! readability of debug info, and the printing speed. The digit length and bit length will also be displayed
//! when the alternate flag of the formatter is set. (pretty printing)
//!
//! The struct [InRadix] can be used to print the integer in a given radix, which also supporting
//! the common formatter options. But the [Debug] trait is not implemented for [InRadix] yet.
//!
use crate::{
error::panic_invalid_radix,
ibig::IBig,
radix::{self, Digit, DigitCase},
repr::TypedReprRef,
ubig::UBig,
Sign::{self, *},
};
use core::fmt::{
self, Alignment, Binary, Debug, Display, Formatter, LowerHex, Octal, UpperHex, Write,
};
use digit_writer::DigitWriter;
mod digit_writer;
mod non_power_two;
mod power_two;
pub use radix::{MAX_RADIX, MIN_RADIX};
impl Display for UBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
InRadixWriter {
sign: Positive,
magnitude: self.repr(),
radix: 10,
prefix: "",
digit_case: DigitCase::NoLetters,
}
.fmt(f)
}
}
impl Debug for UBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
DoubleEnd {
sign: Positive,
magnitude: self.repr(),
verbose: f.alternate(),
}
.fmt(f)
}
}
impl Binary for UBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
InRadixWriter {
sign: Positive,
magnitude: self.repr(),
radix: 2,
prefix: if f.alternate() { "0b" } else { "" },
digit_case: DigitCase::NoLetters,
}
.fmt(f)
}
}
impl Octal for UBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
InRadixWriter {
sign: Positive,
magnitude: self.repr(),
radix: 8,
prefix: if f.alternate() { "0o" } else { "" },
digit_case: DigitCase::NoLetters,
}
.fmt(f)
}
}
impl LowerHex for UBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
InRadixWriter {
sign: Positive,
magnitude: self.repr(),
radix: 16,
prefix: if f.alternate() { "0x" } else { "" },
digit_case: DigitCase::Lower,
}
.fmt(f)
}
}
impl UpperHex for UBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
InRadixWriter {
sign: Positive,
magnitude: self.repr(),
radix: 16,
prefix: if f.alternate() { "0x" } else { "" },
digit_case: DigitCase::Upper,
}
.fmt(f)
}
}
impl Display for IBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let (sign, magnitude) = self.as_sign_repr();
InRadixWriter {
sign,
magnitude,
radix: 10,
prefix: "",
digit_case: DigitCase::NoLetters,
}
.fmt(f)
}
}
impl Debug for IBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let (sign, magnitude) = self.as_sign_repr();
DoubleEnd {
sign,
magnitude,
verbose: f.alternate(),
}
.fmt(f)
}
}
impl Binary for IBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let (sign, magnitude) = self.as_sign_repr();
InRadixWriter {
sign,
magnitude,
radix: 2,
prefix: if f.alternate() { "0b" } else { "" },
digit_case: DigitCase::NoLetters,
}
.fmt(f)
}
}
impl Octal for IBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let (sign, magnitude) = self.as_sign_repr();
InRadixWriter {
sign,
magnitude,
radix: 8,
prefix: if f.alternate() { "0o" } else { "" },
digit_case: DigitCase::NoLetters,
}
.fmt(f)
}
}
impl LowerHex for IBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let (sign, magnitude) = self.as_sign_repr();
InRadixWriter {
sign,
magnitude,
radix: 16,
prefix: if f.alternate() { "0x" } else { "" },
digit_case: DigitCase::Lower,
}
.fmt(f)
}
}
impl UpperHex for IBig {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let (sign, magnitude) = self.as_sign_repr();
InRadixWriter {
sign,
magnitude,
radix: 16,
prefix: if f.alternate() { "0x" } else { "" },
digit_case: DigitCase::Upper,
}
.fmt(f)
}
}
impl UBig {
/// Representation in a given radix.
///
/// # Panics
///
/// Panics if `radix` is not between 2 and 36 inclusive.
///
/// # Examples
///
/// ```
/// # use dashu_int::UBig;
/// assert_eq!(format!("{}", UBig::from(83u8).in_radix(3)), "10002");
/// assert_eq!(format!("{:+010}", UBig::from(35u8).in_radix(36)), "+00000000z");
/// ```
#[inline]
pub fn in_radix(&self, radix: u32) -> InRadix {
if !radix::is_radix_valid(radix) {
panic_invalid_radix(radix);
}
InRadix {
sign: Positive,
magnitude: self.repr(),
radix,
}
}
}
impl IBig {
/// Representation in a given radix.
///
/// # Panics
///
/// Panics if `radix` is not between 2 and 36 inclusive.
///
/// # Examples
///
/// ```
/// # use dashu_int::IBig;
/// assert_eq!(format!("{}", IBig::from(-83).in_radix(3)), "-10002");
/// assert_eq!(format!("{:010}", IBig::from(-35).in_radix(36)), "-00000000z");
/// ```
#[inline]
pub fn in_radix(&self, radix: u32) -> InRadix {
if !radix::is_radix_valid(radix) {
panic_invalid_radix(radix);
}
let (sign, magnitude) = self.as_sign_repr();
InRadix {
sign,
magnitude,
radix,
}
}
}
/// Representation of a [UBig] or [IBig] in any radix between [MIN_RADIX] and [MAX_RADIX] inclusive.
///
/// This can be used to format a number in a non-standard radix, by calling [UBig::in_radix] or [IBig::in_radix].
///
/// The default format uses lower-case letters a-z for digits 10-35.
/// The "alternative" format (`{:#}`) uses upper-case letters.
///
/// # Examples
///
/// ```
/// # use dashu_int::{IBig, UBig};
/// assert_eq!(format!("{}", UBig::from(83u8).in_radix(3)), "10002");
/// assert_eq!(format!("{:+010}", UBig::from(35u8).in_radix(36)), "+00000000z");
/// // For bases 2, 8, 10, 16 we don't have to use `InRadix`:
/// assert_eq!(format!("{:x}", UBig::from(3000u32)), "bb8");
/// assert_eq!(format!("{:#X}", IBig::from(-3000)), "-0xBB8");
/// ```
pub struct InRadix<'a> {
sign: Sign,
magnitude: TypedReprRef<'a>,
radix: Digit,
}
impl Display for InRadix<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let digit_case = if self.radix <= 10 {
DigitCase::NoLetters
} else if f.alternate() {
DigitCase::Upper
} else {
DigitCase::Lower
};
InRadixWriter {
sign: self.sign,
magnitude: self.magnitude,
radix: self.radix,
prefix: "",
digit_case,
}
.fmt(f)
}
}
/// Representation in a given radix with a prefix and digit case.
struct InRadixWriter<'a> {
sign: Sign,
magnitude: TypedReprRef<'a>,
radix: Digit,
prefix: &'static str,
digit_case: DigitCase,
}
/// Representation for printing only head and tail of the number, only decimal is supported
struct DoubleEnd<'a> {
sign: Sign,
magnitude: TypedReprRef<'a>,
verbose: bool,
}
impl InRadixWriter<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.radix.is_power_of_two() {
self.fmt_power_two(f)
} else {
self.fmt_non_power_two(f)
}
}
/// Format using a `PreparedForFormatting`.
fn format_prepared(
&self,
f: &mut Formatter,
prepared: &mut dyn PreparedForFormatting,
) -> fmt::Result {
let mut width = prepared.width();
// Adding sign and prefix to width will not overflow, because Buffer::MAX_CAPACITY leaves
// (WORD_BITS - 1) spare bits before we would hit overflow.
let sign = if self.sign == Negative {
"-"
} else if f.sign_plus() {
"+"
} else {
""
};
// In bytes, but it's OK because everything is ASCII.
width += sign.len() + self.prefix.len();
let mut write_digits = |f| {
let mut digit_writer = DigitWriter::new(f, self.digit_case);
prepared.write(&mut digit_writer)?;
digit_writer.flush()
};
match f.width() {
None => {
f.write_str(sign)?;
f.write_str(self.prefix)?;
write_digits(f)?
}
Some(min_width) => {
if width >= min_width {
f.write_str(sign)?;
f.write_str(self.prefix)?;
write_digits(f)?;
} else if f.sign_aware_zero_pad() {
f.write_str(sign)?;
f.write_str(self.prefix)?;
for _ in 0..min_width - width {
f.write_char('0')?;
}
write_digits(f)?;
} else {
let left_pad = match f.align() {
Some(Alignment::Left) => 0,
Some(Alignment::Right) | None => min_width - width,
Some(Alignment::Center) => (min_width - width) / 2,
};
let fill = f.fill();
for _ in 0..left_pad {
f.write_char(fill)?;
}
f.write_str(sign)?;
f.write_str(self.prefix)?;
write_digits(f)?;
for _ in left_pad..min_width - width {
f.write_char(fill)?;
}
}
}
}
Ok(())
}
}
impl DoubleEnd<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
self.fmt_non_power_two(f)
}
/// Format using a `PreparedForFormatting`.
fn format_prepared(
&self,
f: &mut Formatter,
digits: usize,
prepared_high: &mut dyn PreparedForFormatting,
prepared_low: Option<&mut dyn PreparedForFormatting>,
) -> fmt::Result {
let sign = if self.sign == Negative {
"-"
} else if f.sign_plus() {
"+"
} else {
""
};
f.write_str(sign)?;
let mut digit_writer = DigitWriter::new(f, DigitCase::NoLetters);
prepared_high.write(&mut digit_writer)?;
digit_writer.flush()?;
if let Some(low) = prepared_low {
f.write_str("..")?;
let mut digit_writer = DigitWriter::new(f, DigitCase::NoLetters);
low.write(&mut digit_writer)?;
digit_writer.flush()?;
}
if self.verbose {
f.write_str(" (")?;
non_power_two::write_usize_decimals(f, digits)?;
f.write_str(" digits, ")?;
non_power_two::write_usize_decimals(f, self.magnitude.bit_len())?;
f.write_str(" bits)")?;
}
Ok(())
}
}
/// Trait for state of a partially-formatted [UBig].
///
/// The state must be such the width (number of digits) is already known.
trait PreparedForFormatting {
/// Returns the number of characters that will be written.
fn width(&self) -> usize;
/// Write to a stream.
fn write(&mut self, digit_writer: &mut DigitWriter) -> fmt::Result;
}