use std::borrow::Borrow;
use std::fmt;
use display_more::DisplayOptionExt;
use crate::RaftTypeConfig;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::VoteOf;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize), serde(bound = ""))]
pub struct VoteRequest<C: RaftTypeConfig> {
pub vote: VoteOf<C>,
pub last_log_id: Option<LogIdOf<C>>,
}
impl<C> fmt::Display for VoteRequest<C>
where C: RaftTypeConfig
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{{vote:{}, last_log:{}}}", self.vote, self.last_log_id.display(),)
}
}
impl<C> VoteRequest<C>
where C: RaftTypeConfig
{
pub fn new(vote: VoteOf<C>, last_log_id: Option<LogIdOf<C>>) -> Self {
Self { vote, last_log_id }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize), serde(bound = ""))]
pub struct VoteResponse<C: RaftTypeConfig> {
pub vote: VoteOf<C>,
pub vote_granted: bool,
pub last_log_id: Option<LogIdOf<C>>,
}
impl<C> VoteResponse<C>
where C: RaftTypeConfig
{
pub fn new(vote: impl Borrow<VoteOf<C>>, last_log_id: Option<LogIdOf<C>>, granted: bool) -> Self {
Self {
vote: vote.borrow().clone(),
vote_granted: granted,
last_log_id: last_log_id.map(|x| x.borrow().clone()),
}
}
pub fn is_granted_to(&self, candidate_vote: &VoteOf<C>) -> bool {
&self.vote == candidate_vote
}
}
impl<C> fmt::Display for VoteResponse<C>
where C: RaftTypeConfig
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{{{}, last_log:{:?}}}",
self.vote,
self.last_log_id.as_ref().map(|x| x.to_string())
)
}
}