persister.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. use std::convert::TryFrom;
  2. use bytes::Bytes;
  3. use crate::{LogEntry, Peer, RaftState, Term};
  4. pub trait Persister: Send + Sync {
  5. fn read_state(&self) -> Bytes;
  6. fn save_state(&self, bytes: Bytes);
  7. }
  8. #[derive(Serialize, Deserialize)]
  9. pub(crate) struct PersistedRaftState {
  10. pub current_term: Term,
  11. pub voted_for: Option<Peer>,
  12. pub log: Vec<LogEntry>,
  13. }
  14. impl<T: AsRef<RaftState>> From<T> for PersistedRaftState {
  15. fn from(raft_state: T) -> Self {
  16. Self::from(raft_state.as_ref())
  17. }
  18. }
  19. impl From<&RaftState> for PersistedRaftState {
  20. fn from(raft_state: &RaftState) -> Self {
  21. Self {
  22. current_term: raft_state.current_term,
  23. voted_for: raft_state.voted_for,
  24. log: raft_state.log.clone(),
  25. }
  26. }
  27. }
  28. impl TryFrom<Bytes> for PersistedRaftState {
  29. type Error = bincode::Error;
  30. fn try_from(value: Bytes) -> Result<Self, Self::Error> {
  31. bincode::deserialize(value.as_ref())
  32. }
  33. }
  34. impl Into<Bytes> for PersistedRaftState {
  35. fn into(self) -> Bytes {
  36. bincode::serialize(&self)
  37. .expect("Serialization should not fail")
  38. .into()
  39. }
  40. }