util.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. fs::{File, OpenOptions},
  20. os::unix::prelude::OpenOptionsExt,
  21. path::Path,
  22. };
  23. use log::debug;
  24. use darkfi::{Error, Result};
  25. use rand::{distributions::Alphanumeric, rngs::OsRng, Rng};
  26. use crate::task_info::{TaskEvent, TaskInfo};
  27. /*
  28. pub fn find_free_id(task_ids: &[u32]) -> u32 {
  29. for i in 1.. {
  30. if !task_ids.contains(&i) {
  31. return i
  32. }
  33. }
  34. 1
  35. }
  36. */
  37. pub fn set_event(task_info: &mut TaskInfo, action: &str, author: &str, content: &str) {
  38. debug!(target: "tau", "TaskInfo::set_event()");
  39. if !content.is_empty() {
  40. task_info.events.push(TaskEvent::new(action.into(), author.into(), content.into()));
  41. }
  42. }
  43. pub fn pipe_write<P: AsRef<Path>>(path: P) -> Result<File> {
  44. OpenOptions::new()
  45. .write(true)
  46. .append(true)
  47. .custom_flags(libc::O_NONBLOCK)
  48. .open(path)
  49. .map_err(Error::from)
  50. }
  51. pub fn gen_id(len: usize) -> String {
  52. OsRng.sample_iter(&Alphanumeric).take(len).map(char::from).collect()
  53. }
  54. // #[cfg(test)]
  55. // mod tests {
  56. // use super::*;
  57. // use darkfi::Result;
  58. // #[test]
  59. // fn find_free_id_test() -> Result<()> {
  60. // let mut ids: Vec<u32> = vec![1, 3, 8, 9, 10, 3];
  61. // let ids_empty: Vec<u32> = vec![];
  62. // let ids_duplicate: Vec<u32> = vec![1; 100];
  63. // let find_id = find_free_id(&ids);
  64. // assert_eq!(find_id, 2);
  65. // ids.push(find_id);
  66. // assert_eq!(find_free_id(&ids), 4);
  67. // assert_eq!(find_free_id(&ids_empty), 1);
  68. // assert_eq!(find_free_id(&ids_duplicate), 2);
  69. // Ok(())
  70. // }
  71. // }