use std::fmt::Write;
use std::hash::{Hash, Hasher};
use malachitebft_metrics::prometheus::encoding::EncodeLabelValue;
#[derive(Clone, Copy, Debug)]
pub struct PeerType {
is_persistent: bool,
is_validator: bool,
}
impl PartialEq for PeerType {
fn eq(&self, other: &Self) -> bool {
self.primary_type_str() == other.primary_type_str()
}
}
impl Eq for PeerType {}
impl Hash for PeerType {
fn hash<H: Hasher>(&self, state: &mut H) {
self.primary_type_str().hash(state);
}
}
impl PeerType {
pub fn new(is_persistent: bool, is_validator: bool) -> Self {
Self {
is_persistent,
is_validator,
}
}
pub fn with_validator_status(self, is_validator: bool) -> Self {
Self {
is_persistent: self.is_persistent,
is_validator,
}
}
pub fn with_persistent(self, is_persistent: bool) -> Self {
Self {
is_persistent,
is_validator: self.is_validator,
}
}
pub fn primary_type_str(&self) -> &'static str {
match (self.is_validator, self.is_persistent) {
(true, _) => "validator", (false, true) => "persistent_peer", (false, false) => "full_node", }
}
pub fn is_persistent(&self) -> bool {
self.is_persistent
}
pub fn is_validator(&self) -> bool {
self.is_validator
}
}
impl EncodeLabelValue for PeerType {
fn encode(
&self,
encoder: &mut malachitebft_metrics::prometheus::encoding::LabelValueEncoder,
) -> Result<(), std::fmt::Error> {
encoder.write_str(self.primary_type_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_with_persistent_preserves_validator_status() {
let validator = PeerType::new(false, true);
let persistent_validator = validator.with_persistent(true);
assert!(persistent_validator.is_persistent());
assert!(persistent_validator.is_validator());
let non_persistent_validator = persistent_validator.with_persistent(false);
assert!(!non_persistent_validator.is_persistent());
assert!(non_persistent_validator.is_validator());
}
}