cog_task/util/
helper.rs

1use eyre::{eyre, Result};
2use serde::Serialize;
3use spin_sleep::{SpinSleeper, SpinStrategy};
4
5const APPROX_EQ_EPS: f64 = 1e-6;
6const SPIN_DURATION: u32 = 100_000_000; // equivalent to 100ms
7const SPIN_STRATEGY: SpinStrategy = SpinStrategy::SpinLoopHint;
8
9pub fn approx_eq(x: f64, y: f64) -> bool {
10    (x - y).abs() < APPROX_EQ_EPS
11}
12
13pub fn f64_as_bool(x: f64) -> Result<bool> {
14    if approx_eq(x, 0.0) {
15        Ok(false)
16    } else if approx_eq(x, 1.0) {
17        Ok(true)
18    } else {
19        Err(eyre!("Tried to read a non-boolean float as bool."))
20    }
21}
22
23pub fn f64_as_i64(x: f64) -> Result<i64> {
24    let int = x.round();
25    if approx_eq(x, int) {
26        Ok(int as i64)
27    } else {
28        Err(eyre!("Tried to read a non-integer float as int."))
29    }
30}
31
32#[inline(always)]
33pub fn spin_sleeper() -> SpinSleeper {
34    SpinSleeper::new(SPIN_DURATION).with_spin_strategy(SPIN_STRATEGY)
35}
36
37#[inline(always)]
38pub fn f32_with_precision(x: f32, precision: u8) -> f32 {
39    let precision = 10_f32.powi(precision as i32);
40    (x * precision).round() / precision
41}
42
43#[inline(always)]
44pub fn f64_with_precision(x: f32, precision: u8) -> f64 {
45    let shift = 10_f64.powi(precision as i32);
46    (x as f64 * shift).round() / shift
47}
48
49#[inline]
50pub fn str_with_precision(x: f32, precision: u8) -> String {
51    let shift = 10_f64.powi(precision as i32);
52    let string = format!("{}", (x as f64 * shift).round());
53    let (int, frac) = string.split_at(string.len() - precision as usize);
54    let int = if int.is_empty() { "0" } else { int };
55    if frac.is_empty() {
56        int.to_owned()
57    } else {
58        format!("{int}.{frac}")
59    }
60}
61
62pub trait Hash: Serialize {
63    fn hash(&self) -> String {
64        use sha2::{Digest, Sha256};
65        let mut hasher = Sha256::default();
66        hasher.update(&serde_cbor::to_vec(&self).unwrap());
67        hex::encode(hasher.finalize())
68    }
69}