util.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. use std::{
  2. fs::File,
  3. io::BufReader,
  4. path::{Path, PathBuf},
  5. };
  6. use chrono::Utc;
  7. use clap::Parser;
  8. use rand::{distributions::Alphanumeric, thread_rng, Rng};
  9. use serde::{de::DeserializeOwned, Deserialize, Serialize};
  10. use darkfi::{util::cli::UrlConfig, Result};
  11. pub const CONFIG_FILE_CONTENTS: &[u8] = include_bytes!("../taud_config.toml");
  12. pub fn random_ref_id() -> String {
  13. thread_rng().sample_iter(&Alphanumeric).take(30).map(char::from).collect()
  14. }
  15. pub fn get_current_time() -> Timestamp {
  16. Timestamp(Utc::now().timestamp())
  17. }
  18. pub fn find_free_id(task_ids: &[u32]) -> u32 {
  19. for i in 1.. {
  20. if !task_ids.contains(&i) {
  21. return i
  22. }
  23. }
  24. 1
  25. }
  26. pub fn load<T: DeserializeOwned>(path: &Path) -> Result<T> {
  27. let file = File::open(path)?;
  28. let reader = BufReader::new(file);
  29. let value: T = serde_json::from_reader(reader)?;
  30. Ok(value)
  31. }
  32. pub fn save<T: Serialize>(path: &Path, value: &T) -> Result<()> {
  33. let file = File::create(path)?;
  34. serde_json::to_writer_pretty(file, value)?;
  35. Ok(())
  36. }
  37. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
  38. pub struct Settings {
  39. pub dataset_path: PathBuf,
  40. }
  41. impl Default for Settings {
  42. fn default() -> Self {
  43. Self { dataset_path: PathBuf::from("") }
  44. }
  45. }
  46. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, PartialOrd)]
  47. pub struct Timestamp(pub i64);
  48. /// taud cli
  49. #[derive(Parser)]
  50. #[clap(name = "taud")]
  51. pub struct CliTaud {
  52. /// Sets a custom config file
  53. #[clap(short, long)]
  54. pub config: Option<String>,
  55. /// Increase verbosity
  56. #[clap(short, parse(from_occurrences))]
  57. pub verbose: u8,
  58. }
  59. #[derive(Clone, Debug, Serialize, Deserialize)]
  60. pub struct TauConfig {
  61. /// path to dataset
  62. pub dataset_path: String,
  63. /// Path to DER-formatted PKCS#12 archive. (used only with tls listener url)
  64. pub tls_identity_path: String,
  65. /// The address where taud should bind its RPC socket
  66. pub rpc_listener_url: UrlConfig,
  67. }
  68. #[cfg(test)]
  69. mod tests {
  70. use super::*;
  71. #[test]
  72. fn find_free_id_test() -> Result<()> {
  73. let mut ids: Vec<u32> = vec![1, 3, 8, 9, 10, 3];
  74. let ids_empty: Vec<u32> = vec![];
  75. let ids_duplicate: Vec<u32> = vec![1; 100];
  76. let find_id = find_free_id(&ids);
  77. assert_eq!(find_id, 2);
  78. ids.push(find_id);
  79. assert_eq!(find_free_id(&ids), 4);
  80. assert_eq!(find_free_id(&ids_empty), 1);
  81. assert_eq!(find_free_id(&ids_duplicate), 2);
  82. Ok(())
  83. }
  84. }