Skip to main content

promql/
go_format.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The shortest float formats of Go's `strconv`, which Prometheus writes label values in.
16
17#[cfg(test)]
18mod tests;
19
20/// Go's `strconv.FormatFloat(value, 'f', -1, 64)`, the form of `count_values` labels.
21pub(crate) fn format_float_f(value: f64) -> String {
22    match special(value) {
23        Some(text) => text.to_string(),
24        None => {
25            let (negative, digits, point) = shortest(value);
26            positional(negative, &digits, point)
27        }
28    }
29}
30
31/// Prometheus `labels.FormatOpenMetricsFloat`, the form of `histogram_quantiles` labels: Go's
32/// shortest `'g'` format, with `.0` appended to an integer and `0`, `1` and `-1` written as
33/// `0.0`, `1.0` and `-1.0`.
34pub(crate) fn format_open_metrics_float(value: f64) -> String {
35    if value == 1.0 {
36        return "1.0".to_string();
37    }
38    if value == 0.0 {
39        return "0.0".to_string();
40    }
41    if value == -1.0 {
42        return "-1.0".to_string();
43    }
44    if let Some(text) = special(value) {
45        return text.to_string();
46    }
47    let mut text = format_float_g(value);
48    if !text.contains(['e', '.']) {
49        text.push_str(".0");
50    }
51    text
52}
53
54/// Go's `strconv.FormatFloat(value, 'g', -1, 64)`, which `%g` and `%v` print a float in: the
55/// shortest digits, with an exponent of at least two digits below 1e-4 and from 1e6 on.
56pub(crate) fn format_float_g(value: f64) -> String {
57    if let Some(text) = special(value) {
58        return text.to_string();
59    }
60    let (negative, digits, point) = shortest(value);
61    let exponent = point - 1;
62    if (-4..6).contains(&exponent) {
63        return positional(negative, &digits, point);
64    }
65    let mut text = String::from(if negative { "-" } else { "" });
66    text.push_str(&digits[..1]);
67    if digits.len() > 1 {
68        text.push('.');
69        text.push_str(&digits[1..]);
70    }
71    text.push_str(&format!(
72        "e{}{:02}",
73        if exponent < 0 { '-' } else { '+' },
74        exponent.abs()
75    ));
76    text
77}
78
79fn special(value: f64) -> Option<&'static str> {
80    match value {
81        f64::INFINITY => Some("+Inf"),
82        f64::NEG_INFINITY => Some("-Inf"),
83        _ if value.is_nan() => Some("NaN"),
84        _ => None,
85    }
86}
87
88/// The fewest significant digits of a finite `value` that round-trip, without trailing zeros, and
89/// the position of the decimal point among them: `value = ±0.digits × 10^point`. Zero is `"0"` at
90/// point 1.
91///
92/// When two candidates of that length are equally close, Go takes the even one while Rust's
93/// shortest formatting rounds up, so the digits are recomputed with Rust's exact formatting,
94/// which rounds half to even. The recomputed digits only count when they still parse back to
95/// `value`: just above a power of two the lower neighbour is half as far away, so the even
96/// candidate can name that neighbour, and only the other one round-trips.
97fn shortest(value: f64) -> (bool, String, i64) {
98    let shortest = format!("{value:e}");
99    let mantissa = shortest.split_once('e').expect("exponent format").0;
100    let significant = mantissa.chars().filter(char::is_ascii_digit).count();
101    let exact = format!("{value:.precision$e}", precision = significant - 1);
102    let chosen = if exact.parse::<f64>() == Ok(value) {
103        &exact
104    } else {
105        &shortest
106    };
107    let (mantissa, exponent) = chosen.split_once('e').expect("exponent format");
108    let exponent: i64 = exponent.parse().expect("integer exponent");
109    let (negative, mantissa) = match mantissa.strip_prefix('-') {
110        Some(unsigned) => (true, unsigned),
111        None => (false, mantissa),
112    };
113    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
114    let trimmed = digits.trim_end_matches('0');
115    let digits = if trimmed.is_empty() { "0" } else { trimmed };
116    (negative, digits.to_string(), exponent + 1)
117}
118
119/// `±0.digits × 10^point` in positional notation without trailing fractional zeros.
120fn positional(negative: bool, digits: &str, point: i64) -> String {
121    let mut out = String::from(if negative { "-" } else { "" });
122    if point <= 0 {
123        out.push_str("0.");
124        out.extend(std::iter::repeat_n('0', (-point) as usize));
125        out.push_str(digits);
126    } else if point as usize >= digits.len() {
127        out.push_str(digits);
128        out.extend(std::iter::repeat_n('0', point as usize - digits.len()));
129    } else {
130        let (whole, fraction) = digits.split_at(point as usize);
131        out.push_str(whole);
132        out.push('.');
133        out.push_str(fraction);
134    }
135    out
136}