Skip to main content

common_query/
prometheus.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/// Canonical Prometheus stale-marker NaN bit pattern.
16pub const PROMETHEUS_STALE_NAN_BITS: u64 = 0x7ff0_0000_0000_0002;
17
18/// Formats a floating-point value for the Prometheus HTTP API.
19pub fn format_prometheus_float(value: f64) -> String {
20    if value == f64::INFINITY {
21        "+Inf".to_string()
22    } else if value == f64::NEG_INFINITY {
23        "-Inf".to_string()
24    } else {
25        value.to_string()
26    }
27}
28
29/// Returns whether `value` is the canonical Prometheus stale-marker NaN.
30#[inline]
31pub fn is_prometheus_stale_nan(value: f64) -> bool {
32    value.to_bits() == PROMETHEUS_STALE_NAN_BITS
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn recognizes_only_the_canonical_stale_marker() {
41        assert!(is_prometheus_stale_nan(f64::from_bits(
42            0x7ff0_0000_0000_0002
43        )));
44        assert!(!is_prometheus_stale_nan(f64::from_bits(
45            0x7ff8_0000_0000_0000
46        )));
47    }
48
49    #[test]
50    fn formats_prometheus_float_values() {
51        assert_eq!(format_prometheus_float(f64::INFINITY), "+Inf");
52        assert_eq!(format_prometheus_float(f64::NEG_INFINITY), "-Inf");
53        assert_eq!(format_prometheus_float(f64::NAN), "NaN");
54        assert_eq!(format_prometheus_float(1.5), "1.5");
55    }
56}