persister.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use parking_lot::Mutex;
  2. #[derive(Clone)]
  3. pub struct State {
  4. pub bytes: bytes::Bytes,
  5. pub snapshot: Vec<u8>,
  6. }
  7. pub struct Persister {
  8. state: Mutex<State>,
  9. }
  10. impl Persister {
  11. pub fn new() -> Self {
  12. Self {
  13. state: Mutex::new(State {
  14. bytes: bytes::Bytes::new(),
  15. snapshot: vec![],
  16. }),
  17. }
  18. }
  19. }
  20. impl Default for Persister {
  21. fn default() -> Self {
  22. Self::new()
  23. }
  24. }
  25. impl ruaft::Persister for Persister {
  26. fn read_state(&self) -> bytes::Bytes {
  27. self.state.lock().bytes.clone()
  28. }
  29. fn save_state(&self, data: bytes::Bytes) {
  30. self.state.lock().bytes = data;
  31. }
  32. fn state_size(&self) -> usize {
  33. self.state.lock().bytes.len()
  34. }
  35. fn save_snapshot_and_state(&self, state: bytes::Bytes, snapshot: &[u8]) {
  36. let mut this = self.state.lock();
  37. this.bytes = state;
  38. this.snapshot = snapshot.to_vec();
  39. }
  40. }
  41. impl Persister {
  42. pub fn read(&self) -> State {
  43. self.state.lock().clone()
  44. }
  45. pub fn restore(&self, state: State) {
  46. *self.state.lock() = state;
  47. }
  48. pub fn snapshot_size(&self) -> usize {
  49. self.state.lock().snapshot.len()
  50. }
  51. }