use std::fmt;
use std::io::Cursor;
use byteorder::{LittleEndian, ReadBytesExt};
use crate::cluster::node;
use crate::Key;
#[derive(Debug, Clone)]
pub struct Partition<'a> {
pub namespace: &'a str,
pub partition_id: usize,
}
impl<'a> Partition<'a> {
pub const fn new(namespace: &'a str, partition_id: usize) -> Self {
Partition {
namespace,
partition_id,
}
}
pub fn new_by_key(key: &'a Key) -> Self {
let mut rdr = Cursor::new(&key.digest[0..2]);
Partition {
namespace: &key.namespace,
partition_id: rdr.read_u16::<LittleEndian>().unwrap() as usize & (node::PARTITIONS - 1),
}
}
}
impl PartialEq for Partition<'_> {
fn eq(&self, other: &Partition) -> bool {
self.namespace == other.namespace && self.partition_id == other.partition_id
}
}
impl fmt::Display for Partition<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
format!("Partition ({}: {})", self.namespace, self.partition_id).fmt(f)
}
}