util.rs 1.3 KB

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