Skip to content

Commit

Permalink
add some docs
Browse files Browse the repository at this point in the history
Signed-off-by: Bugen Zhao <[email protected]>
  • Loading branch information
BugenZhao committed Oct 18, 2024
1 parent 8dc638d commit a9472c6
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions src/common/src/hash/consistent_hash/compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,34 +16,28 @@ use std::num::NonZeroUsize;

use super::vnode::VirtualNode;

/// The different cases of `maybe_vnode_count` field in the protobuf message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum VnodeCount {
/// The field is a placeholder and has to be filled first before using it.
#[default]
Placeholder,
/// The field is set to a specific value.
Set(NonZeroUsize),
/// The field is unset because it's persisted in an older version.
Compat,
}

impl VnodeCount {
/// Creates a `VnodeCount` set to the given value.
pub fn set(v: impl TryInto<NonZeroUsize>) -> Self {
VnodeCount::Set(
v.try_into()
.unwrap_or_else(|_| panic!("vnode count must be non-zero")),
)
}

pub fn for_test() -> Self {
Self::set(VirtualNode::COUNT_FOR_TEST)
}

pub fn from_protobuf(v: Option<u32>) -> Self {
match v {
None => VnodeCount::Compat,
Some(0) => VnodeCount::Placeholder,
Some(v) => VnodeCount::set(v as usize),
}
}

/// Converts to protobuf representation for `maybe_vnode_count`.
pub fn to_protobuf(self) -> Option<u32> {
match self {
VnodeCount::Placeholder => Some(0),
Expand All @@ -52,25 +46,39 @@ impl VnodeCount {
}
}

pub fn value(self) -> usize {
self.value_opt().expect("vnode count not set")
/// Converts from protobuf representation of `maybe_vnode_count`.
pub fn from_protobuf(v: Option<u32>) -> Self {
match v {
None => VnodeCount::Compat,
Some(0) => VnodeCount::Placeholder,
Some(v) => VnodeCount::set(v as usize),
}
}

/// Returns the value of the vnode count, or `None` if it's a placeholder.
pub fn value_opt(self) -> Option<usize> {
match self {
VnodeCount::Placeholder => None,
VnodeCount::Set(v) => Some(v.get()),
VnodeCount::Compat => Some(VirtualNode::COUNT_FOR_COMPAT),
}
}

/// Returns the value of the vnode count. Panics if it's a placeholder.
pub fn value(self) -> usize {
self.value_opt().expect("vnode count not set")
}
}

/// A trait for accessing the vnode count field with backward compatibility.
pub trait VnodeCountCompat {
/// Get the `maybe_vnode_count` field.
fn vnode_count_inner(&self) -> VnodeCount;

/// Returns the vnode count, or [`VirtualNode::COUNT_FOR_COMPAT`] if the vnode count is not set,
/// typically for backward compatibility.
/// typically for backward compatibility. Panics if the field is a placeholder.
///
/// Equivalent to `self.vnode_count_inner().value()`.
///
/// See the documentation on the field of the implementing type for more details.
fn vnode_count(&self) -> usize {
Expand Down

0 comments on commit a9472c6

Please sign in to comment.