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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Formatting implementation.
#![allow(clippy::cast_precision_loss)]
mod preset;
#[cfg(feature = "alloc")]
use alloc::format;
#[cfg(feature = "alloc")]
use alloc::string::String;
use core::fmt;
use unroll_lite::unroll;
use crate::unit::RangedUnit;
#[derive(Debug, Clone, Copy)]
/// Formatter of numbers for human-readable output.
pub struct Formatter<const N: usize = 0> {
/// Separator between numbers and units.
///
/// Defaults to be " " (space)
separator: &'static str,
/// The abbreviated number's units.
///
/// If the number is too large and no corresponding unit is found, the
/// scientific notation like `3.0e99` will be used.
ranged_units: &'static [RangedUnit; N],
/// The custom unit attached after the abbreviated number's unit.
custom_unit: Option<&'static str>,
}
impl Formatter {
/// Binary units (`Ki`, `Mi`, `Gi`, `Ti`, `Pi`, `Ei`, `Zi`, `Yi`)
pub const BINARY: Formatter<9> = Formatter {
ranged_units: &preset::BINARY_UNITS,
separator: " ",
custom_unit: None,
};
/// Chinese units (`万`, `亿`, `兆`, `京`, `垓`, `秭`, `穰`, `沟`)
pub const CHINESE: Formatter<9> = Formatter {
ranged_units: &preset::CHINESE_UNITS,
separator: " ",
custom_unit: None,
};
/// Decimal units (`K`, `M`, `G`, `T`, `P`, `E`, `Z`, `Y`)
pub const SI: Formatter<9> = Formatter {
ranged_units: &preset::SI_UNITS,
separator: " ",
custom_unit: None,
};
}
impl<const N: usize> Formatter<N> {
#[inline]
#[must_use]
/// Creates a custom formatter with the given ranged units.
///
/// ## Invariants
///
/// - The first `ranged_unit.range_max` is the base, the `n`th
/// `ranged_unit.range_max` is the `n`th power of the first
/// `ranged_unit.range_max`.
/// - `ranged_units` SHOULD NOT be empty.
pub const fn custom(ranged_units: &'static [RangedUnit; N]) -> Option<Self> {
if ranged_units.is_empty() {
return None;
}
let base = ranged_units[0].range_max.get();
unroll!(i in 1..N => {
#[allow(clippy::cast_possible_truncation)]
if ranged_units[i].range_max.get() != base.pow((i + 1) as u32) {
return None;
}
});
#[allow(unsafe_code, reason = "Has checked")]
Some(unsafe { Self::custom_unchecked(ranged_units) })
}
#[allow(
unsafe_code,
reason = "The caller's responsibility to ensure the `ranged_units` is valid."
)]
#[inline]
#[must_use]
/// See [`Formatter::custom`].
///
/// ## Safety
///
/// See [`Formatter::custom`].
pub const unsafe fn custom_unchecked(ranged_units: &'static [RangedUnit; N]) -> Self {
Self {
separator: " ",
ranged_units,
custom_unit: None,
}
}
#[inline]
#[must_use]
/// Sets the separator between numbers and units.
pub const fn with_separator(self, separator: &'static str) -> Self {
Self { separator, ..self }
}
#[inline]
#[must_use]
/// Set custom unit attached after the abbreviated number's unit.
pub const fn with_custom_unit(self, custom_unit: &'static str) -> Self {
Self {
custom_unit: Some(custom_unit),
..self
}
}
#[inline]
#[must_use]
/// Formats a number, with default 2 decimal places.
///
/// Any number type that implements the [`Humat`] trait is supported.
pub fn format(&self, target: impl Humat) -> Formatted {
target.humat(self)
}
#[inline]
#[must_use]
/// Formats a number, with fixed `DECIMAL_PLACES`.
///
/// Any number type that implements the [`Humat`] trait is supported.
pub fn format_fixed_dp<const DECIMAL_PLACES: usize>(
&self,
target: impl Humat,
) -> Formatted<DECIMAL_PLACES> {
target.humat_fixed_dp(self)
}
}
impl<const N: usize> Formatter<N> {
#[inline]
#[must_use]
/// Formats an unsigned integer, with default 2 decimal places.
pub const fn format_uint(&self, target: u128) -> Formatted {
self.format_uint_fixed_dp(target)
}
#[inline]
#[must_use]
/// Formats an unsigned integer, with fixed `DECIMAL_PLACES`.
pub const fn format_uint_fixed_dp<const DECIMAL_PLACES: usize>(
&self,
target: u128,
) -> Formatted<DECIMAL_PLACES> {
if target < self.ranged_units[0].range_max.get() {
return Formatted {
number: FormattedImpl::Int {
positive: true,
integer: target,
unit: self.ranged_units[0].unit,
},
separator: self.separator,
custom_unit: self.custom_unit,
};
}
let mut idx = 1;
// Precision loss for very large numbers
let number_precision_max = self.ranged_units[0].range_max.get() as f64
- self.ranged_units[0].range_max.get() as f64 * 0.000_000_000_000_01;
while idx < N {
if target < self.ranged_units[idx].range_max.get() {
let base = self.ranged_units[idx - 1].range_max.get();
let integer_part = target / base;
let leftover = target % base;
let fractional_part = leftover as f64 / base as f64;
let number = integer_part as f64 + fractional_part;
let number = if number >= number_precision_max {
number_precision_max
} else {
number
};
return Formatted {
number: FormattedImpl::F64 {
number,
unit: self.ranged_units[idx].unit,
},
separator: self.separator,
custom_unit: self.custom_unit,
};
}
idx += 1;
}
Formatted {
number: FormattedImpl::F64 {
number: target as f64,
unit: None,
},
separator: self.separator,
custom_unit: self.custom_unit,
}
}
#[inline]
#[must_use]
/// Formats a signed integer, with default 2 decimal places.
pub const fn format_int(&self, target: i128) -> Formatted {
self.format_uint_fixed_dp(target.unsigned_abs())
.with_sign(target >= 0)
}
#[inline]
#[must_use]
/// Formats a signed integer, with fixed `DECIMAL_PLACES`.
pub const fn format_int_fixed_dp<const DECIMAL_PLACES: usize>(
&self,
target: i128,
) -> Formatted<DECIMAL_PLACES> {
self.format_uint_fixed_dp(target.unsigned_abs())
.with_sign(target >= 0)
}
#[inline]
#[must_use]
/// Formats an `f64`, with default 2 decimal places.
pub const fn format_double(&self, target: f64) -> Formatted {
self.format_double_fixed_dp(target)
}
#[inline]
#[must_use]
/// Formats an `f64`, with fixed `DECIMAL_PLACES`.
pub const fn format_double_fixed_dp<const DECIMAL_PLACES: usize>(
&self,
target: f64,
) -> Formatted<DECIMAL_PLACES> {
if !target.is_finite() {
return Formatted {
number: FormattedImpl::F64 {
number: target,
unit: None,
},
separator: self.separator,
custom_unit: self.custom_unit,
};
}
if target < self.ranged_units[0].range_max.get() as f64 {
return Formatted {
number: FormattedImpl::F64 {
number: target,
unit: self.ranged_units[0].unit,
},
separator: self.separator,
custom_unit: self.custom_unit,
};
}
let mut idx = 1;
while idx < N {
if target < self.ranged_units[idx].range_max.get() as f64 {
return Formatted {
number: FormattedImpl::F64 {
number: target / self.ranged_units[idx - 1].range_max.get() as f64,
unit: self.ranged_units[idx].unit,
},
separator: self.separator,
custom_unit: self.custom_unit,
};
}
idx += 1;
}
Formatted {
number: FormattedImpl::F64 {
number: target,
unit: None,
},
separator: self.separator,
custom_unit: self.custom_unit,
}
}
}
// === Humat ===
/// Helper trait for formatting numbers in a human-readable way.
pub trait Humat {
#[must_use]
/// Formats the number, with default 2 decimal places.
fn humat<const N: usize>(self, formatter: &Formatter<N>) -> Formatted;
#[must_use]
/// Formats the number, with fixed `DECIMAL_PLACES`.
fn humat_fixed_dp<const DECIMAL_PLACES: usize, const N: usize>(
self,
formatter: &Formatter<N>,
) -> Formatted<DECIMAL_PLACES>;
}
macro_rules! impl_number {
($fty:ident $cty:ident => $($ty:ident)*) => {
impl<const N: usize> Formatter<N> {
$(
pastey::paste! {
#[inline]
#[must_use]
#[doc = concat!("Formats ", stringify!($ty), ", with default 2 decimal places.")]
pub const fn [<format_ $ty>](&self, target: $ty) -> Formatted {
self.[<format_ $fty _fixed_dp>](target as $cty)
}
#[inline]
#[must_use]
#[doc = concat!("Formats ", stringify!($ty), ", with fixed `DECIMAL_PLACES`.")]
pub const fn [<format_ $ty _fixed_dp>]<const DECIMAL_PLACES: usize>(&self, target: $ty) -> Formatted<DECIMAL_PLACES> {
self.[<format_ $fty _fixed_dp>](target as $cty)
}
}
)*
}
$(
impl Humat for $ty {
pastey::paste! {
#[inline]
fn humat<const N: usize>(self, formatter: &Formatter<N>) -> Formatted {
formatter.[<format_ $ty>](self)
}
#[inline]
fn humat_fixed_dp<const DECIMAL_PLACES: usize, const N: usize>(
self,
formatter: &Formatter<N>,
) -> Formatted<DECIMAL_PLACES> {
formatter.[<format_ $ty _fixed_dp>](self)
}
}
}
)*
};
}
impl_number!(uint u128 => usize u128 u64 u32 u16 u8);
impl_number!(int i128 => isize i128 i64 i32 i16 i8);
impl_number!(double f64 => f64 f32);
// === Formatted ===
#[derive(Debug)]
/// The number to be formatted.
enum FormattedImpl {
/// An integer with an optional fractional part.
Int {
/// Whether the number is positive.
positive: bool,
/// The integer part.
integer: u128,
/// The abbreviated number's unit.
unit: Option<&'static str>,
},
/// An `f64`
F64 {
/// The integer part.
number: f64,
/// The abbreviated number's unit.
unit: Option<&'static str>,
},
}
#[derive(Debug)]
/// The formatted number, with default 2 decimal places.
pub struct Formatted<const DECIMAL_PLACES: usize = 2> {
/// The formatted number.
number: FormattedImpl,
/// Separator between numbers and units.
///
/// Defaults to be " " (space)
separator: &'static str,
/// The custom unit attached after the abbreviated number's unit.
custom_unit: Option<&'static str>,
}
impl<const DECIMAL_PLACES: usize> Formatted<DECIMAL_PLACES> {
#[inline]
const fn with_sign(mut self, positive: bool) -> Self {
match &mut self.number {
FormattedImpl::Int { positive: p, .. } => *p = positive,
FormattedImpl::F64 { number, .. } => {
if !positive {
*number = -(*number);
}
}
}
self
}
#[inline]
#[must_use]
/// Set the decimal places for the formatted number.
///
/// ## Examples
///
/// ```rust
/// use humat::Formatter;
///
/// let formatter = Formatter::SI;
/// let formatted = formatter.format(1_000);
/// assert_eq!(formatted.to_string(), "1.00 K"); // default 2 decimal places
/// assert_eq!(formatted.with_decimal_places::<4>().to_string(), "1.0000 K"); // with 4 decimal places
/// ```
pub fn with_decimal_places<const NEW_DECIMAL_PLACES: usize>(
self,
) -> Formatted<NEW_DECIMAL_PLACES> {
#[allow(unsafe_code, reason = "compile time const value")]
unsafe {
core::mem::transmute(self)
}
}
#[inline]
#[must_use]
/// Returns the raw number as a `f64`.
pub const fn number(&self) -> f64 {
match self.number {
FormattedImpl::Int {
positive, integer, ..
} => integer as f64 * if positive { 1.0 } else { -1.0 },
FormattedImpl::F64 { number, .. } => number,
}
}
#[inline]
#[must_use]
/// Returns the separator between numbers and units.
pub const fn separator(&self) -> &'static str {
self.separator
}
#[inline]
#[must_use]
/// Returns the custom unit attached after the abbreviated number's unit.
pub const fn custom_unit(&self) -> Option<&'static str> {
self.custom_unit
}
#[cfg(feature = "alloc")]
#[allow(clippy::inherent_to_string_shadow_display)]
#[must_use]
/// Converts the formatted number to a `String`.
///
/// ## Examples
///
/// ```rust
/// use humat::Formatter;
///
/// let formatter = Formatter::SI;
/// let formatted = formatter.format(1_000);
/// assert_eq!(formatted.to_string(), "1.00 K");
/// ```
pub fn to_string(&self) -> String {
let separator = self.separator;
match self.number {
FormattedImpl::Int {
positive,
integer,
unit,
} => {
let sign = if positive { "" } else { "-" };
// TODO: fast number formatting?
match (unit, self.custom_unit) {
(Some(unit), Some(custom_unit)) => {
format!("{sign}{integer}{separator}{unit}{custom_unit}")
}
(Some(unit), None) => format!("{sign}{integer}{separator}{unit}"),
(None, Some(custom_unit)) => format!("{sign}{integer}{separator}{custom_unit}"),
(None, None) => format!("{sign}{integer}"),
}
}
FormattedImpl::F64 { number, unit } => {
let mut result = String::with_capacity(8 + DECIMAL_PLACES);
let mut formatted = ryuu::Formatter::format_f64(number);
let formatted = formatted.as_str_adjusting_dp::<DECIMAL_PLACES>();
match (unit, self.custom_unit) {
(Some(unit), Some(custom_unit)) => {
result.push_str(formatted);
result.push_str(separator);
result.push_str(unit);
result.push_str(custom_unit);
}
(Some(unit), None) => {
result.push_str(formatted);
result.push_str(separator);
result.push_str(unit);
}
(None, Some(custom_unit)) => {
result.push_str(formatted);
result.push_str(separator);
result.push_str(custom_unit);
}
(None, None) => {
result.push_str(formatted);
}
}
result
}
}
}
}
#[cfg(not(feature = "alloc"))]
impl<const DECIMAL_PLACES: usize> fmt::Display for Formatted<DECIMAL_PLACES> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let separator = self.separator;
match self.number {
FormattedImpl::Int {
positive,
integer,
unit,
} => {
let sign = if positive { "" } else { "-" };
match (unit, self.custom_unit) {
(Some(unit), Some(custom_unit)) => {
write!(f, "{sign}{integer}{separator}{unit}{custom_unit}")
}
(Some(unit), None) => write!(f, "{sign}{integer}{separator}{unit}"),
(None, Some(custom_unit)) => {
write!(f, "{sign}{integer}{separator}{custom_unit}")
}
(None, None) => write!(f, "{sign}{integer}"),
}
}
FormattedImpl::F64 { number, unit } => {
let mut formatted = ryuu::Formatter::format_f64(number);
let formatted = formatted.as_str_adjusting_dp::<DECIMAL_PLACES>();
match (unit, self.custom_unit) {
(Some(unit), Some(custom_unit)) => {
write!(f, "{formatted}{separator}{unit}{custom_unit}")
}
(Some(unit), None) => write!(f, "{formatted}{separator}{unit}"),
(None, Some(custom_unit)) => write!(f, "{formatted}{separator}{custom_unit}"),
(None, None) => write!(f, "{formatted}"),
}
}
}
}
}
#[cfg(feature = "alloc")]
impl<const DECIMAL_PLACES: usize> fmt::Display for Formatted<DECIMAL_PLACES> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.to_string().as_str())
}
}