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/// format decimal by specific significant figures
26pub fn decimal_sf(num: rust_decimal::Decimal, sig_figs: usize) -> rust_decimal::Decimal {
27    num.round_sf(sig_figs as _).unwrap()
28}
29
30/// Aligns the precision of one `f64` value to match another `f64` value.
31pub fn align_precision(a: f64, b: f64) -> f64 {
32    let precision_b = count_dp(b);
33    let precision_a = format!("{:.0$}", { precision_b });
34    let aligned_a = format!("{:.*}", precision_a.parse::<usize>().unwrap(), a);
35    aligned_a.parse().unwrap()
36}
37
38pub fn count_dp(num: f64) -> usize {
39    // Convert the f64 to a string representation
40    let num_str = format!("{num}");
41
42    // Find the position of the decimal point
43    if let Some(decimal_index) = num_str.find('.') {
44        // Count the number of characters after the decimal point
45        num_str.len() - decimal_index - 1
46    } else {
47        // If there is no decimal point, return 0
48        0
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn test_count_dp() {
58        assert_eq!(count_dp(1.5), 1);
59        assert_eq!(count_dp(1.1), 1);
60    }
61
62    #[test]
63    fn test_align_precision() {
64        let a = 123.456789;
65        let b = 78.9;
66        let aligned_a = align_precision(a, b);
67        assert_eq!(aligned_a, 123.5);
68
69        let a = 2.37;
70        let b = 631.3;
71        let aligned_a = align_precision(a, b);
72        assert_eq!(aligned_a, 2.4);
73    }
74}