Skip to main content

confluent_kafka/common/metrics/
quota.rs

1// Copyright 2025 Confluent Inc.
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//! An upper or lower bound for metrics (`org.apache.kafka.common.metrics.Quota`).
16
17/// An upper or lower bound for metrics.
18#[derive(Clone, Debug)]
19#[doc(alias = "org.apache.kafka.common.metrics.Quota")]
20pub struct Quota {
21    upper: bool,
22    bound: f64,
23}
24
25impl Quota {
26    /// Creates a quota with the given bound and whether it is an upper bound.
27    ///
28    /// # Arguments
29    ///
30    /// - `bound` - the bound value
31    /// - `upper` - `true` for an upper bound, `false` for a lower bound
32    #[doc(alias = "org.apache.kafka.common.metrics.Quota#Quota")]
33    pub fn new(bound: f64, upper: bool) -> Self {
34        Self { bound, upper }
35    }
36
37    /// Creates an upper-bound quota.
38    ///
39    /// # Arguments
40    ///
41    /// - `upper_bound` - the highest acceptable value
42    ///
43    /// # Returns
44    ///
45    /// The upper-bound quota.
46    #[doc(alias = "org.apache.kafka.common.metrics.Quota#upperBound")]
47    pub fn upper_bound(upper_bound: f64) -> Self {
48        Self::new(upper_bound, true)
49    }
50
51    /// Creates a lower-bound quota.
52    ///
53    /// # Arguments
54    ///
55    /// - `lower_bound` - the lowest acceptable value
56    ///
57    /// # Returns
58    ///
59    /// The lower-bound quota.
60    #[doc(alias = "org.apache.kafka.common.metrics.Quota#lowerBound")]
61    pub fn lower_bound(lower_bound: f64) -> Self {
62        Self::new(lower_bound, false)
63    }
64
65    /// Returns whether this quota is an upper bound.
66    #[doc(alias = "org.apache.kafka.common.metrics.Quota#isUpperBound")]
67    pub fn is_upper_bound(&self) -> bool {
68        self.upper
69    }
70
71    /// Returns the bound value.
72    #[doc(alias = "org.apache.kafka.common.metrics.Quota#bound")]
73    pub fn bound(&self) -> f64 {
74        self.bound
75    }
76
77    /// Returns whether the given value is acceptable under this quota.
78    ///
79    /// # Arguments
80    ///
81    /// - `value` - the value to check against the bound
82    #[doc(alias = "org.apache.kafka.common.metrics.Quota#acceptable")]
83    pub fn acceptable(&self, value: f64) -> bool {
84        (self.upper && value <= self.bound) || (!self.upper && value >= self.bound)
85    }
86}
87
88impl Quota {
89    /// The bound as Java's `Double.doubleToLongBits` reads it: its bits, with
90    /// every `NaN` folded into the canonical one.
91    fn bound_bits(&self) -> u64 {
92        if self.bound.is_nan() {
93            f64::NAN.to_bits()
94        } else {
95            self.bound.to_bits()
96        }
97    }
98}
99
100/// Java's `Quota.equals` compares `bound` with the primitive `==`, under which
101/// `NaN` differs from itself and `0.0` equals `-0.0`. A lawful `Eq` must be
102/// reflexive, so the bound is compared as Java's `Double.equals` compares it
103/// instead: every `NaN` is equal, and the two zeros differ. Any other bound
104/// compares as in Java.
105impl PartialEq for Quota {
106    fn eq(&self, other: &Self) -> bool {
107        self.bound_bits() == other.bound_bits() && self.upper == other.upper
108    }
109}
110
111impl Eq for Quota {}
112
113/// Hashes what [`PartialEq`] compares. Java hashes `(int) bound`, which would
114/// put `0.0` and `-0.0`, now unequal, under one hash; the Rust hash only has
115/// to agree with Rust's equality, so it takes the bits.
116impl std::hash::Hash for Quota {
117    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
118        self.bound_bits().hash(state);
119        self.upper.hash(state);
120    }
121}
122
123impl std::fmt::Display for Quota {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        if self.upper {
126            write!(f, "upper={}", self.bound)
127        } else {
128            write!(f, "lower={}", self.bound)
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn test_quotas_equality() {
139        let quota1 = Quota::upper_bound(10.5);
140        let quota2 = Quota::upper_bound(10.5);
141        assert_eq!(quota1, quota2, "Quota with same upper bound should be equal");
142
143        let quota3 = Quota::lower_bound(10.5);
144        let quota4 = Quota::lower_bound(10.5);
145        assert_eq!(quota3, quota4, "Quota with same lower bound should be equal");
146
147        assert_ne!(
148            quota1, quota3,
149            "Quota with same bound but different upper/lower should not be equal"
150        );
151    }
152
153    // New test, no Java original: the NaN and signed-zero cases where a lawful
154    // `Eq` cannot follow Java's primitive `==` (see `PartialEq for Quota`).
155    #[test]
156    fn test_quota_equality_reads_the_bound_as_double_equals() {
157        use std::hash::BuildHasher;
158        let state = std::collections::hash_map::RandomState::new();
159        let nan = Quota::upper_bound(f64::NAN);
160        let other_nan = Quota::upper_bound(f64::from_bits(f64::NAN.to_bits() ^ 1));
161        assert_eq!(nan, Quota::upper_bound(f64::NAN));
162        assert_eq!(nan, other_nan);
163        assert_eq!(state.hash_one(nan), state.hash_one(other_nan));
164        assert_ne!(Quota::upper_bound(0.0), Quota::upper_bound(-0.0));
165    }
166
167    #[test]
168    fn test_acceptable() {
169        let upper = Quota::upper_bound(5.0);
170        assert!(upper.acceptable(5.0));
171        assert!(upper.acceptable(4.0));
172        assert!(!upper.acceptable(6.0));
173
174        let lower = Quota::lower_bound(5.0);
175        assert!(lower.acceptable(5.0));
176        assert!(lower.acceptable(6.0));
177        assert!(!lower.acceptable(4.0));
178    }
179}