raft_state.rs 932 B

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