Skip to content

Add function for unbiased random numbers #309

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

Merged
merged 1 commit into from
Feb 4, 2019
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
20 changes: 20 additions & 0 deletions src/toxcore/crypto_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,19 @@ pub fn random_usize() -> usize {
random_u64() as usize
}

/// Return unbiased random number from `[0, limit)` interval.
pub fn random_limit_usize(limit: usize) -> usize {
// TODO: possibly migrate to rand crate, it has more performant version
// of this algorithm implemented with UniformSampler trait
let cap = usize::max_value() - usize::max_value() % limit;
loop {
let n = random_usize();
if n < cap {
return n % limit;
}
}
}

/** Check if Tox public key `PUBLICKEYBYTES` is valid. Should be used only for
input validation.

Expand Down Expand Up @@ -310,6 +323,13 @@ pub mod tests {
assert_ne!(a, b);
}

#[test]
fn random_limit_usize_test() {
crypto_init().unwrap();
let n = random_limit_usize(7);
assert!(n < 7);
}

#[test]
fn public_key_valid_test() {
crypto_init().unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/toxcore/dht/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,10 +508,10 @@ impl Server {
return Box::new(future::ok(()))
}

let mut random_node_idx = random_usize() % good_nodes.len();
let mut random_node_idx = random_limit_usize(good_nodes.len());
// Increase probability of sending packet to a close node (has lower index)
if random_node_idx != 0 {
random_node_idx -= random_usize() % (random_node_idx + 1);
random_node_idx -= random_limit_usize(random_node_idx + 1);
}

let random_node = &good_nodes[random_node_idx];
Expand Down