raft_state.rs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. use crate::{
  2. log_array::LogArray, persister::PersistedRaftState, Index, Peer, Term,
  3. };
  4. #[derive(Copy, Clone, Debug, Eq, PartialEq)]
  5. pub(crate) enum State {
  6. Follower,
  7. Prevote,
  8. Candidate,
  9. Leader,
  10. }
  11. #[repr(align(64))]
  12. pub(crate) struct RaftState<Command> {
  13. pub current_term: Term,
  14. pub voted_for: Option<Peer>,
  15. pub log: LogArray<Command>,
  16. pub commit_index: Index,
  17. pub match_index: Vec<Index>,
  18. pub state: State,
  19. pub leader_id: Peer,
  20. }
  21. impl<Command> RaftState<Command> {
  22. pub fn create(peer_size: usize, me: Peer) -> Self {
  23. RaftState {
  24. current_term: Term(0),
  25. voted_for: None,
  26. log: LogArray::create(),
  27. commit_index: 0,
  28. match_index: vec![0; peer_size],
  29. state: State::Follower,
  30. leader_id: me,
  31. }
  32. }
  33. }
  34. impl<Command: Clone> RaftState<Command> {
  35. pub fn persisted_state(&self) -> PersistedRaftState<Command> {
  36. self.into()
  37. }
  38. }
  39. impl<Command> RaftState<Command> {
  40. pub fn is_leader(&self) -> bool {
  41. self.state == State::Leader
  42. }
  43. }