ringbuf.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. #[derive(Clone)]
  19. pub struct RingBuffer<T, const N: usize> {
  20. vals: [Option<T>; N],
  21. head: i64,
  22. tail: i64
  23. }
  24. impl<T, const N: usize> RingBuffer<T, N> {
  25. const LEN: usize = N;
  26. pub fn new() -> Self {
  27. Self { vals: [const { None }; N], head: -1, tail: -1 }
  28. }
  29. pub fn push(&mut self, v: T) {
  30. let len = Self::LEN as i64;
  31. self.head = (self.head + 1) % len;
  32. if self.head == self.tail {
  33. self.tail = (self.tail + 1) % len;
  34. }
  35. if self.tail < 0 {
  36. self.tail = 0;
  37. }
  38. let _ = std::mem::replace(&mut self.vals[self.head as usize], Some(v));
  39. }
  40. pub fn head(&self) -> Option<&T> {
  41. if self.head < 0 {
  42. return None
  43. }
  44. Some(self.vals[self.head as usize].as_ref().unwrap())
  45. }
  46. pub fn tail(&self) -> Option<&T> {
  47. if self.tail < 0 {
  48. return None
  49. }
  50. Some(self.vals[self.tail as usize].as_ref().unwrap())
  51. }
  52. }