raft_state.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. pub(crate) struct RaftState<Command> {
  12. pub current_term: Term,
  13. pub voted_for: Option<Peer>,
  14. pub log: LogArray<Command>,
  15. pub commit_index: Index,
  16. pub last_applied: 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. last_applied: 0,
  29. match_index: vec![0; peer_size],
  30. state: State::Follower,
  31. leader_id: me,
  32. }
  33. }
  34. }
  35. impl<Command: Clone> RaftState<Command> {
  36. pub fn persisted_state(&self) -> PersistedRaftState<Command> {
  37. self.into()
  38. }
  39. }
  40. impl<Command> RaftState<Command> {
  41. pub fn is_leader(&self) -> bool {
  42. self.state == State::Leader
  43. }
  44. }