Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token: add constructor and normalization #948

Merged
merged 1 commit into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/compare-tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ async fn main() -> Result<()> {
)
.await?;

let t = prepared.calculate_token(&(pk,))?.unwrap().value;
let t = prepared.calculate_token(&(pk,))?.unwrap().value();

println!(
"Token endpoints for query: {:?}",
session
.get_cluster_data()
.get_token_endpoints("examples_ks", Token { value: t })
.get_token_endpoints("examples_ks", Token::new(t))
.iter()
.map(|(node, _shard)| node.address)
.collect::<Vec<NodeAddr>>()
Expand Down
36 changes: 35 additions & 1 deletion scylla/src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,42 @@ use std::num::NonZeroU16;
use thiserror::Error;

#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]

/// Token is a result of computing a hash of a primary key
///
/// It is basically an i64 with one caveat: i64::MIN is not
/// a valid token. It is used to represent infinity.
/// For this reason tokens are normalized - i64::MIN
/// is replaced with i64::MAX. See this fragment of
/// Scylla code for more information:
/// <https://github.com/scylladb/scylladb/blob/4be70bfc2bc7f133cab492b4aac7bab9c790a48c/dht/token.hh#L32>
///
/// This struct is a wrapper over i64 that performs this normalization
/// when initialized using `new()` method.
pub struct Token {
pub value: i64,
value: i64,
}

impl Token {
/// Creates a new token with given value, normalizing the value if necessary
#[inline]
pub fn new(value: i64) -> Self {
Self {
value: if value == i64::MIN { i64::MAX } else { value },
}
}

/// Invalid Token - contains i64::MIN as value.
///
/// This is (currently) only required by CDCPartitioner.
/// See the following comment:
/// https://github.com/scylladb/scylla-rust-driver/blob/049dc3546d24e45106fed0fdb985ec2511ab5192/scylla/src/transport/partitioner.rs#L312-L322
pub(crate) const INVALID: Self = Token { value: i64::MIN };

#[inline]
pub fn value(&self) -> i64 {
self.value
}
}

pub type Shard = u32;
Expand Down
Loading
Loading