Skip to content

Commit

Permalink
feat(portability): Support Gauge::<f32, AtomicU32>
Browse files Browse the repository at this point in the history
  • Loading branch information
navaati committed Jul 17, 2024
1 parent ccb6ff8 commit 44e82dd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/encoding/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,9 @@ mod tests {
let gauge = Gauge::<u32, AtomicU32>::default();
registry.register("u32_gauge", "Gauge::<u32, AtomicU32>", gauge);

let gauge_f32 = Gauge::<f32, AtomicU32>::default();
registry.register("f32_gauge", "Gauge::<f32, AtomicU32>", gauge_f32);

let mut encoded = String::new();

encode(&mut encoded, &registry).unwrap();
Expand Down
48 changes: 48 additions & 0 deletions src/metrics/gauge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,54 @@ impl Atomic<f64> for AtomicU64 {
}
}

impl Atomic<f32> for AtomicU32 {
fn inc(&self) -> f32 {
self.inc_by(1.0)
}

fn inc_by(&self, v: f32) -> f32 {
let mut old_u32 = self.load(Ordering::Relaxed);
let mut old_f32;
loop {
old_f32 = f32::from_bits(old_u32);
let new = f32::to_bits(old_f32 + v);
match self.compare_exchange_weak(old_u32, new, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => break,
Err(x) => old_u32 = x,
}
}

old_f32
}

fn dec(&self) -> f32 {
self.dec_by(1.0)
}

fn dec_by(&self, v: f32) -> f32 {
let mut old_u32 = self.load(Ordering::Relaxed);
let mut old_f32;
loop {
old_f32 = f32::from_bits(old_u32);
let new = f32::to_bits(old_f32 - v);
match self.compare_exchange_weak(old_u32, new, Ordering::Relaxed, Ordering::Relaxed) {
Ok(_) => break,
Err(x) => old_u32 = x,
}
}

old_f32
}

fn set(&self, v: f32) -> f32 {
f32::from_bits(self.swap(f32::to_bits(v), Ordering::Relaxed))
}

fn get(&self) -> f32 {
f32::from_bits(self.load(Ordering::Relaxed))
}
}

impl<N, A> TypedMetric for Gauge<N, A> {
const TYPE: MetricType = MetricType::Gauge;
}
Expand Down

0 comments on commit 44e82dd

Please sign in to comment.