tina-core 0.0.2

Tina platform
Documentation
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
//! Dynamic formatting of numbers into human readable forms.
//!
//! Did you encounter cases where Rust doesn't represent numbers the way you expect?
//!
//! ```
//! for i in 1..=10 {
//!     println!("{}", 0.1 * i as f64);
//! }
//! ```
//!
//! You get this:
//!
//! ```text
//! 0.1
//! 0.2
//! 0.30000000000000004
//! 0.4
//! 0.5
//! 0.6000000000000001
//! 0.7000000000000001
//! 0.8
//! 0.9
//! 1
//! ```
//!
//! That's actually not a Rust issue, but rather [how floats are represented in binary](https://en.wikipedia.org/wiki/Double-precision_floating-point_format).
//!
//! Yet rounding error is not the only reason to customize number formatting. A table of numbers
//! should be formatted consistently for comparison; above, 1.0 would be better than 1. Large
//! numbers may need to have grouped digits (e.g. 42,000) or be in scientific or metric notation
//! (4.2e+4, 42k). Reported numerical results should be rounded to significant digits (4021 becomes
//! 4000) and so on.
//!
//! The parser is modeled after Python 3's [format specification mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language)
//! [(PEP3101)](https://www.python.org/dev/peps/pep-3101/) with some minor implementation details changes.
//!
//! The general form of a format specifier is:
//!
//! ```text
//! [[fill]align][sign][symbol][0][width][,][.precision][type]
//! ```
//!
//! The _fill_ can be any character. The presence of a fill character is signaled by the align
//! character following it, which must be one of the following:
//!
//! `>` - Forces the field to be right-aligned within the available space.
//!
//! `<` - Forces the field to be left-aligned within the available space.
//!
//! `^` - Forces the field to be centered within the available space.
//!
//! `=` - like `>`, but with any sign and symbol to the left of any padding.
//!
//! The _sign_ can be:
//!
//! `-` - nothing for zero or positive and a minus sign for negative (default behavior).
//!
//! `+` - a plus sign for zero or positive and a minus sign for negative.
//!
//! ` ` (space) - a space for zero or positive and a minus sign for negative.
//!
//! The _symbol_ can be:
//!
//! The `#` option causes the “alternate form” to be used for the conversion. The alternate
//! form is defined differently for different types. For integers, when binary (`b`), octal
//! (`o` or `O`), or hexadecimal (`x` or `X`) output is used, this option adds the prefix
//! respective "0b", "0o", "0O" or "0x" to the output value. For floats, the alternate form
//! causes the result of the conversion to always contain a decimal-point character,
//! even if no digits follow it.
//!
//! The zero (0) option enables zero-padding; this implicitly sets fill to 0 and align to =.
//!
//! The _width_ defines the minimum field width; if not specified, then the width will be
//! determined by the content.
//!
//! The comma (,) option enables the use of a group separator, such as a comma for thousands.
//!
//! Depending on the _type_, the _precision_ either indicates the number of digits that follow
//! the decimal point (types `f` and `%`), or the number of significant digits (types `e`
//! and `s`). If the precision is not specified, it defaults to 6 for all types. Precision
//! is ignored for integer formats (types `b`, `o`, `d`, `x` and `X`).
//!
//! The available _type_ values are:
//!
//! `e` - exponent notation.
//!
//! `f` - fixed point notation.
//!
//! `s` - decimal notation with an SI prefix, rounded to significant digits.
//!
//! `%` - multiply by 100, and then decimal notation with a percent sign.
//!
//! `b` - binary notation, rounded to integer.
//!
//! `o` - octal notation, rounded to integer.
//!
//! `d` - decimal notation, rounded to integer.
//!
//! `x` - hexadecimal notation, using lower-case letters, rounded to integer.
//!
//! `X` - hexadecimal notation, using upper-case letters, rounded to integer.
//!
//!
//! # Examples
//!
//! ```
//!
//! use ruoyi_base::common::util::num_format::NumberFormat;
//! let num = NumberFormat::new();
//!
//! assert_eq!(num.format(".1f", 0.06).expect("format"), "0.1");
//! assert_eq!(num.format("#.0f", 10.1).expect("format"), "10."); // float alternate form (always show a decimal point)
//! assert_eq!(num.format("+14d", 2_147_483_647).expect("format"), "   +2147483647");
//! assert_eq!(num.format("#b", 3).expect("format"), "0b11");
//! assert_eq!(num.format("b", 3).expect("format"), "11");
//! assert_eq!(num.format("#X", 48879).expect("format"), "0xBEEF");
//! assert_eq!(num.format(".2s", 42e6).expect("format"), "42M");
//! assert_eq!(num.format(".^20d", 12).expect("format"), ".........12........."); // dot filled and centered
//! assert_eq!(num.format("+10.0f", 255).expect("format"), "      +255");
//! assert_eq!(num.format(".0%", 0.123).expect("format"), "12%");
//! assert_eq!(num.format("+016,.2s", 42e12).expect("format"), "+000,000,000,042T"); // grouped zero-padded with a mandatory sign, SI-prefixed with 2 significant digits
//! ```
//!
//! # Note
//!
//! A current limitation is that the number to be formatted should implement the `Into<f64>`
//! trait. While this covers a broad range of use cases, for big numbers (>u64::MAX) some
//! precision will be lost.
use crate::tina::data::AppResult;
use crate::{app_error_from, app_system_error};
use regex::{Captures, Regex};
use std::cmp::{max, min};

const PREFIXES: [&str; 17] = ["y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];

/// A struct that defines the formatting specs and implements the formatting behavior.
///
/// Defines the characters used as a decimal symbol as well as the character used to
/// delimit groups of characters in the integer part of the number.
pub struct NumberFormat {
    decimal: char,
    group_delimiter: char,
}

/// Represents a destructured specification of a provided format pattern string.
#[derive(Debug)]
struct FormatSpec<'a> {
    zero: bool,
    fill: Option<&'a str>,
    align: Option<&'a str>,
    sign: Option<&'a str>,
    symbol: Option<&'a str>,
    width: Option<usize>,
    grouping: Option<&'a str>,
    precision: Option<i32>,
    format_type: Option<&'a str>,
}

impl<'a> From<Captures<'a>> for FormatSpec<'a> {
    /// Create a `FormatSpec` instance from a parsed format pattern string.
    fn from(c: Captures<'a>) -> Self {
        let mut spec = Self {
            fill: c.get(1).map(|m| m.as_str()).or(Some(" ")),
            align: c.get(2).map(|m| m.as_str()),
            sign: c.get(3).map(|m| m.as_str()).or(Some("-")),
            symbol: c.get(4).map(|m| m.as_str()),
            zero: c.get(5).is_some(),
            width: c.get(6).map(|m| m.as_str().parse().unwrap_or(0)).or(Some(0)),
            grouping: c.get(7).map(|m| m.as_str()),
            precision: c.get(8).map(|m| m.as_str()[1..].parse().unwrap_or(6)).or(Some(6)),
            format_type: c.get(9).map(|m| m.as_str()),
        };

        // If zero fill is specified, padding goes after sign and before digits.
        if spec.zero || (spec.fill.unwrap_or_default() == "0" && spec.align.unwrap_or_default() == "=") {
            spec.zero = true;
            spec.fill = Some("0");
            spec.align = Some("=");
        }

        // Ignore precision for decimal notation.
        if spec.format_type.unwrap_or_default() == "d" {
            spec.precision = Some(0);
        };

        spec
    }
}

impl Default for NumberFormat {
    fn default() -> Self {
        Self::new()
    }
}

impl NumberFormat {
    /// Create a new instance of HumanNumberFormat.
    pub fn new() -> Self {
        Self {
            decimal: '.',
            group_delimiter: ',',
        }
    }

    #[allow(dead_code)]
    fn get_significant_digits(input: &str) -> usize {
        let contains_dot = input.contains('.');
        let mut dot_counted = false;
        let mut insignificant = 0;
        for char in input.chars() {
            match char {
                '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => break,
                '.' => {
                    insignificant += 1;
                    dot_counted = true;
                }
                _ => insignificant += 1,
            }
        }

        if !contains_dot {
            for char in input.chars().rev() {
                match char {
                    '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => break,
                    _ => insignificant += 1,
                }
            }
        }

        input.len() - insignificant - (contains_dot && !dot_counted) as usize
    }

    /// Computes the decimal coefficient and exponent of the specified number `value` with supplied
    /// amount of significant digits. For example, decompose_to_coefficient_and_exponent(1.23, Option<2>)
    /// returns ("12", 0).
    fn decompose_to_coefficient_and_exponent(&self, value: f64, significant_digits: Option<usize>) -> (String, isize) {
        // Use exponential formatting to get the expected number of significant digits.
        let formatted_value = if significant_digits.is_some() {
            let precision = if significant_digits.unwrap_or(0) == 0 {
                0
            } else {
                significant_digits.unwrap_or(0) - 1
            };
            format!("{:.1$e}", value, precision)
        } else {
            format!("{:e}", value)
        };

        let exp_tokens: Vec<&str> = formatted_value.split('e').collect::<Vec<&str>>();
        let exponent = exp_tokens[1].parse().unwrap_or(0);

        // The `formatted_num` can have 2 shapes: `1e2` and `1.2e2`. Remove the decimal character
        // in case it's in the latter form.
        if exp_tokens[0].len() == 1 {
            (exp_tokens[0].to_owned(), exponent)
        } else {
            let dot_idx = exp_tokens[0].chars().position(|c| c == self.decimal).unwrap_or(0);
            (format!("{}{}", &exp_tokens[0][..dot_idx], &exp_tokens[0][dot_idx + 1..]), exponent)
        }
    }

    /// Compute the [SI prefix](https://en.wikipedia.org/wiki/Metric_prefix) of the number and scale it accordingly.
    fn format_si_prefix(&self, value: f64, precision: Option<i32>) -> (String, isize) {
        let (coefficient, exponent) = self.decompose_to_coefficient_and_exponent(value, precision.map(|p| p as usize));
        let prefix_exponent = max(-8, min(8, (exponent as f32 / 3_f32).floor() as isize));
        let i: isize = exponent - prefix_exponent * 3 + 1;
        let n: isize = coefficient.len() as isize;

        if i == n {
            (coefficient, prefix_exponent)
        } else if i > n {
            (format!("{}{}", coefficient, "0".repeat((i - n) as usize)), prefix_exponent)
        } else if i > 0 {
            (format!("{}{}{}", &coefficient[..i as usize], self.decimal, &coefficient[i as usize..]), prefix_exponent)
        } else {
            // less than 1 yocto
            (
                format!(
                    "0{}{}{}",
                    self.decimal,
                    "0".repeat(i.unsigned_abs()),
                    self.decompose_to_coefficient_and_exponent(
                        value,
                        precision.and(Some(max(0, precision.map(|p| (p - i.abs() as i32 - 1) as usize).unwrap_or(0))))
                    )
                    .0
                ),
                prefix_exponent,
            )
        }
    }

    /// Parse the formatting pattern and return a format specification based on the pattern.
    ///
    /// The parser is modeled after Python 3's [format specification mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language)
    /// [(PEP3101)](https://www.python.org/dev/peps/pep-3101/) with some minor implementation
    /// details changes.
    ///
    /// The format spec pattern is the following: [[fill]align][sign][symbol][0][width][,][.precision][type]
    fn parse_pattern<'a>(&self, pattern: &'a str) -> AppResult<FormatSpec<'a>> {
        let re = Regex::new(r"^(?:(.)?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([A-Za-z%])?$").map_err(app_error_from!())?;
        Ok(FormatSpec::from(re.captures(pattern).ok_or_else(|| crate::app_system_error!("no captures"))?))
    }

    /// Group digits using the `group_delimiter` character.
    ///
    /// A width is going to be specified (>0) only when the formatted value should be filled in
    /// with "0" characters before the number itself (e.g. using a "020f" or "0=12f" pattern).
    ///
    /// If width > 0, the result will fit into the provided width.
    /// In case the width > 0 and the grouped value starts with the grouping character
    /// (e.g. width = 4, value = 0001 -> ,001), it will be formatted as 0,001, since ,001
    /// is not a valid representation.
    ///
    /// If width = 0, the result will group all passed digits without truncating any of them.
    fn group_value(&self, value: &str, width: usize) -> String {
        let mut reversed_chars: Vec<&[char]> = Vec::new();
        let input_chars: Vec<char> = value.chars().rev().collect();
        let separator: [char; 1] = [self.group_delimiter];

        // After the below loop, an input of "1234" is going to be
        // transformed into `vec![['4', '3', '2'], [','], ['1'], [',']]`.
        for group in input_chars.chunks(3) {
            reversed_chars.push(group);
            reversed_chars.push(&separator);
        }
        // pop last grouping character since it is going to become the leading one after reverse.
        reversed_chars.pop();

        // Flatten the reversed_chars vec
        let grouped: Vec<&char> = reversed_chars.into_iter().flatten().collect();

        // Assure the grouped value fits into provided width in case width > 0
        if width > 0 && grouped.len() > width {
            // If the first character is going to be the group delimiter,
            // keep the one preceding the group delimiter.
            let to_skip = if grouped[width - 1] == &separator[0] {
                grouped.len() - width - 1
            } else {
                grouped.len() - width
            };
            grouped.into_iter().rev().skip(to_skip).collect::<String>()
        } else {
            grouped.into_iter().rev().collect::<String>()
        }
    }

    /// Format the number using scientific notation. The exponent is always represented with
    /// the corresponding sign and at least 2 digits (e.g. 1e+01, 2.1e-02, 42.12e+210).
    ///
    /// The `format_type` is either a small "e" or a capital "E". Also, the format spec pattern
    /// might require displaying a decimal point even if the formatted number does not contain
    /// any decimal digits.
    fn get_formatted_exp_value(&self, format_type: &str, value: f64, precision: usize, include_decimal_point: bool) -> String {
        let formatted = format!("{:.1$e}", value, precision);
        let tokens = formatted.split(format_type).collect::<Vec<&str>>();

        let exp_suffix = if &tokens[1][0..1] == "-" {
            if tokens[1].len() == 2 {
                format!("-0{}", &tokens[1][1..])
            } else {
                tokens[1].to_owned()
            }
        } else {
            format!("+{:0>2}", &tokens[1])
        };

        let possible_decimal = if include_decimal_point && precision == 0 {
            format_args!("{}", self.decimal).to_string()
        } else {
            "".to_owned()
        };

        format!("{}{}{}{}", &tokens[0], possible_decimal, format_type, exp_suffix)
    }

    /// Compute the sign prefix to display based on num sign and format spec.
    ///
    /// If the number is negative, always show "-" sign.
    /// Otherwise, if the format spec contains:
    ///   - "+" sign, show a "+" sign for positive numbers
    ///   - " " a blank space, leave a blank space for positive numbers
    ///
    /// If the format_spec does not contain any info regarding the sign, use an empty string.
    fn get_sign_prefix(&self, is_negative: bool, format_spec: &FormatSpec) -> &str {
        if is_negative {
            "-"
        } else if format_spec.sign.unwrap_or("") == "+" {
            "+"
        } else if format_spec.sign.unwrap_or("") == " " {
            " "
        } else {
            ""
        }
    }

    /// Format a number to a specific human readable form defined by the format spec pattern.
    /// The method takes in a string specifier and a number and returns the string representation
    /// of the formatted number.
    pub fn format<T: Into<f64>>(&self, pattern: &str, input: T) -> AppResult<String> {
        let format_spec = self.parse_pattern(pattern)?;

        let input_f64: f64 = input.into();
        let mut value_is_negative: bool = input_f64.is_sign_negative();

        let mut decimal_part = String::new();
        let mut si_prefix_exponent: &str = "";
        let unit_of_measurement: &str = match format_spec.format_type {
            Some("%") => "%",
            _ => "",
        };

        let mut value = match format_spec.format_type {
            Some("%") => format!(
                "{:.1$}",
                input_f64.abs() * 100_f64,
                format_spec.precision.ok_or_else(|| app_system_error!("no precision"))? as usize
            ),
            Some("b") => format!("{:#b}", input_f64.abs() as i64)[2..].into(),
            Some("o") | Some("O") => format!("{:#o}", input_f64.abs() as i64)[2..].into(),
            Some("x") => format!("{:#x}", input_f64.abs() as i64)[2..].into(),
            Some("X") => format!("{:#X}", input_f64.abs() as i64)[2..].into(),
            Some("f") if format_spec.symbol.unwrap_or_default() == "#" => {
                let maybe_decimal = if format_spec.precision.unwrap_or(-1) == 0 {
                    self.decimal.to_string()
                } else {
                    "".to_string()
                };
                format!(
                    "{:.2$}{}",
                    input_f64.abs(),
                    maybe_decimal,
                    format_spec.precision.ok_or_else(|| app_system_error!("no precision"))? as usize
                )
            }
            Some("e") => self.get_formatted_exp_value(
                "e",
                input_f64.abs(),
                format_spec.precision.ok_or_else(|| app_system_error!("no precision"))? as usize,
                format_spec.symbol.unwrap_or_default() == "#",
            ),
            Some("E") => self.get_formatted_exp_value(
                "E",
                input_f64.abs(),
                format_spec.precision.ok_or_else(|| app_system_error!("no precision"))? as usize,
                format_spec.symbol.unwrap_or_default() == "#",
            ),
            Some("s") => {
                let (val, si_prefix) = self.format_si_prefix(input_f64.abs(), format_spec.precision);
                si_prefix_exponent = PREFIXES[(8 + si_prefix) as usize];
                val
            }
            _ => format!("{:.1$}", input_f64.abs(), format_spec.precision.ok_or_else(|| app_system_error!("no precision"))? as usize),
        };

        // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
        if format_spec.format_type != Some("x")
            && format_spec.format_type != Some("X")
            && value_is_negative
            && value.parse::<f64>().map_err(app_error_from!())? == 0_f64
            && format_spec.sign.unwrap_or("+") != "+"
        {
            value_is_negative = false;
        }

        let sign_prefix = self.get_sign_prefix(value_is_negative, &format_spec);

        let leading_part = match format_spec.symbol {
            Some("#") => match format_spec.format_type {
                Some("b") => "0b",
                Some("o") => "0o",
                Some("x") => "0x",
                Some("O") => "0O",
                Some("X") => "0x",
                _ => "",
            },
            _ => "",
        };

        // Split the integer part of the value for grouping purposes and attach the decimal part as suffix.
        let chars = value.chars().enumerate();
        for (i, c) in chars {
            if "0123456789".find(c).is_none() {
                decimal_part = value[i..].to_owned();
                value = value[..i].to_owned();
                break;
            }
        }

        // Compute the prefix and suffix.
        let prefix = format!("{}{}", sign_prefix, leading_part);
        let suffix = format!("{}{}{}", decimal_part, si_prefix_exponent, unit_of_measurement);

        // If should group and filling character is different than "0",
        // group digits before applying padding.
        if format_spec.grouping.is_some() && !format_spec.zero {
            value = self.group_value(&value, 0)
        }

        // Compute the padding.
        let length = prefix.len() + value.to_string().len() + suffix.len();
        let mut padding = if length < format_spec.width.ok_or_else(|| crate::app_system_error!("no width"))? {
            vec![format_spec.fill.unwrap_or(""); format_spec.width.ok_or_else(|| crate::app_system_error!("no width"))? - length].join("")
        } else {
            "".to_owned()
        };

        // If "0" is the filling character, grouping is applied after computing padding.
        if format_spec.grouping.is_some() && format_spec.zero {
            value = self.group_value(
                format!("{}{}", &padding, value).as_str(),
                if !padding.is_empty() {
                    format_spec.width.ok_or_else(|| crate::app_system_error!("no width"))? - suffix.len()
                } else {
                    0
                },
            );
            padding = "".to_owned();
        };

        Ok(match format_spec.align {
            Some("<") => format!("{}{}{}{}", prefix, value, suffix, padding),
            Some("=") => format!("{}{}{}{}", prefix, padding, value, suffix),
            Some("^") => format!("{}{}{}{}{}", &padding[..padding.len() / 2], prefix, value, suffix, &padding[padding.len() / 2..]),
            _ => format!("{}{}{}{}", padding, prefix, value, suffix),
        })
    }
}