res.rs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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 crate::error::{Error, Result};
  19. pub type ResourceId = u32;
  20. pub struct ResourceManager<T> {
  21. resources: Vec<(ResourceId, Option<T>)>,
  22. freed: Vec<usize>,
  23. id_counter: ResourceId,
  24. }
  25. impl<T> ResourceManager<T> {
  26. pub fn new() -> Self {
  27. Self { resources: vec![], freed: vec![], id_counter: 0 }
  28. }
  29. pub fn alloc(&mut self, rsrc: T) -> ResourceId {
  30. let id = self.id_counter;
  31. self.id_counter += 1;
  32. if self.freed.is_empty() {
  33. let idx = self.resources.len();
  34. self.resources.push((id, Some(rsrc)));
  35. } else {
  36. let idx = self.freed.pop().unwrap();
  37. let _ = std::mem::replace(&mut self.resources[idx], (id, Some(rsrc)));
  38. }
  39. id
  40. }
  41. pub fn get(&self, id: ResourceId) -> Option<&T> {
  42. for (idx, (rsrc_id, rsrc)) in self.resources.iter().enumerate() {
  43. if self.freed.contains(&idx) {
  44. continue
  45. }
  46. if *rsrc_id == id {
  47. return rsrc.as_ref()
  48. }
  49. }
  50. None
  51. }
  52. pub fn free(&mut self, id: ResourceId) -> Result<()> {
  53. for (idx, (rsrc_id, rsrc)) in self.resources.iter_mut().enumerate() {
  54. if self.freed.contains(&idx) {
  55. return Err(Error::ResourceNotFound)
  56. }
  57. if *rsrc_id == id {
  58. *rsrc = None;
  59. self.freed.push(idx);
  60. return Ok(())
  61. }
  62. }
  63. Err(Error::ResourceNotFound)
  64. }
  65. }