util.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. use chrono::{NaiveDateTime, Utc};
  2. use serde::{de::DeserializeOwned, Deserialize, Serialize};
  3. use std::{fs::File, io::BufReader, path::PathBuf};
  4. use crate::{
  5. util::serial::{SerialDecodable, SerialEncodable},
  6. Result,
  7. };
  8. /// Util function to load a structure saved as a JSON in the provided path file, using serde crate.
  9. pub fn load<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
  10. let file = File::open(path)?;
  11. let reader = BufReader::new(file);
  12. let value: T = serde_json::from_reader(reader)?;
  13. Ok(value)
  14. }
  15. /// Util function to save a structure as a JSON in the provided path file, using serde crate.
  16. pub fn save<T: Serialize>(path: &PathBuf, value: &T) -> Result<()> {
  17. let file = File::create(path)?;
  18. serde_json::to_writer_pretty(file, value)?;
  19. Ok(())
  20. }
  21. /// Util structure to represend chrono UTC timestamps.
  22. #[derive(Debug, Clone, Serialize, Deserialize, SerialDecodable, SerialEncodable)]
  23. pub struct Timestamp(pub i64);
  24. impl Timestamp {
  25. /// Calculates elapsed time of a Timestamp.
  26. pub fn elapsed(self) -> u64 {
  27. let start_time = NaiveDateTime::from_timestamp(self.0, 0);
  28. let end_time = NaiveDateTime::from_timestamp(Utc::now().timestamp(), 0);
  29. let diff = end_time - start_time;
  30. diff.num_seconds().try_into().unwrap()
  31. }
  32. }
  33. /// Util function to generate a Timestamp of current time.
  34. pub fn get_current_time() -> Timestamp {
  35. Timestamp(Utc::now().timestamp())
  36. }