atm0s_small_p2p/
utils.rs

1use std::{
2    fmt::{Debug, Display},
3    time::{SystemTime, UNIX_EPOCH},
4};
5
6pub fn now_ms() -> u64 {
7    // Get the current time
8    let now = SystemTime::now();
9
10    // Calculate the duration since the UNIX epoch
11    let duration = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
12
13    // Return the total milliseconds
14    duration.as_millis() as u64
15}
16
17pub trait ErrorExt {
18    fn print_on_err(&self, prefix: &str);
19}
20
21pub trait ErrorExt2 {
22    fn print_on_err2(&self, prefix: &str);
23}
24
25impl<T, E: Display> ErrorExt for Result<T, E> {
26    fn print_on_err(&self, prefix: &str) {
27        if let Err(e) = self {
28            log::error!("{prefix} got error {e}")
29        }
30    }
31}
32
33impl<T, E: Debug> ErrorExt2 for Result<T, E> {
34    fn print_on_err2(&self, prefix: &str) {
35        if let Err(e) = self {
36            log::error!("{prefix} got error {e:?}")
37        }
38    }
39}
40
41// Define the macro
42#[macro_export]
43macro_rules! return_on_err {
44    ($result:expr, $prefix:expr) => {
45        match $result {
46            Ok(value) => value,
47            Err(e) => {
48                log::error!("{}: {:?}", $prefix, e);
49                return; // Adjust return type as needed (e.g., return None; for Option)
50            }
51        }
52    };
53}