Skip to main content

endpoint_libs/libs/
utils.rs

1use eyre::Result;
2
3pub fn get_log_id() -> u64 {
4    chrono::Utc::now().timestamp_micros() as _
5}
6
7pub fn get_conn_id() -> u32 {
8    chrono::Utc::now().timestamp_micros() as _
9}
10
11pub fn get_time_milliseconds() -> i64 {
12    chrono::Utc::now().timestamp_millis()
13}
14pub fn get_time_micros() -> i64 {
15    chrono::Utc::now().timestamp_micros()
16}
17pub fn hex_decode(s: &[u8]) -> Result<Vec<u8>> {
18    if s.starts_with(b"0x") {
19        Ok(hex::decode(&s[2..])?)
20    } else {
21        Ok(hex::decode(s)?)
22    }
23}
24
25/// Aligns the precision of one `f64` value to match another `f64` value.
26pub fn align_precision(a: f64, b: f64) -> f64 {
27    let precision_b = count_dp(b);
28    let precision_a = format!("{:.0$}", { precision_b });
29    let aligned_a = format!("{:.*}", precision_a.parse::<usize>().unwrap(), a);
30    aligned_a.parse().unwrap()
31}
32
33pub fn count_dp(num: f64) -> usize {
34    // Convert the f64 to a string representation
35    let num_str = format!("{num}");
36
37    // Find the position of the decimal point
38    if let Some(decimal_index) = num_str.find('.') {
39        // Count the number of characters after the decimal point
40        num_str.len() - decimal_index - 1
41    } else {
42        // If there is no decimal point, return 0
43        0
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_count_dp() {
53        assert_eq!(count_dp(1.5), 1);
54        assert_eq!(count_dp(1.1), 1);
55    }
56
57    #[test]
58    fn test_align_precision() {
59        let a = 123.456789;
60        let b = 78.9;
61        let aligned_a = align_precision(a, b);
62        assert_eq!(aligned_a, 123.5);
63
64        let a = 2.37;
65        let b = 631.3;
66        let aligned_a = align_precision(a, b);
67        assert_eq!(aligned_a, 2.4);
68    }
69}