util.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 crate::task_info::{TaskEvent, TaskInfo};
  26. pub fn find_free_id(task_ids: &[u32]) -> u32 {
  27. for i in 1.. {
  28. if !task_ids.contains(&i) {
  29. return i
  30. }
  31. }
  32. 1
  33. }
  34. pub fn set_event(task_info: &mut TaskInfo, action: &str, author: &str, content: &str) {
  35. debug!(target: "tau", "TaskInfo::set_event()");
  36. if !content.is_empty() {
  37. task_info.events.0.push(TaskEvent::new(action.into(), author.into(), content.into()));
  38. }
  39. }
  40. pub fn pipe_write<P: AsRef<Path>>(path: P) -> Result<File> {
  41. OpenOptions::new()
  42. .write(true)
  43. .append(true)
  44. .custom_flags(libc::O_NONBLOCK)
  45. .open(path)
  46. .map_err(Error::from)
  47. }
  48. #[cfg(test)]
  49. mod tests {
  50. use super::*;
  51. use darkfi::Result;
  52. #[test]
  53. fn find_free_id_test() -> Result<()> {
  54. let mut ids: Vec<u32> = vec![1, 3, 8, 9, 10, 3];
  55. let ids_empty: Vec<u32> = vec![];
  56. let ids_duplicate: Vec<u32> = vec![1; 100];
  57. let find_id = find_free_id(&ids);
  58. assert_eq!(find_id, 2);
  59. ids.push(find_id);
  60. assert_eq!(find_free_id(&ids), 4);
  61. assert_eq!(find_free_id(&ids_empty), 1);
  62. assert_eq!(find_free_id(&ids_duplicate), 2);
  63. Ok(())
  64. }
  65. }