Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 75278ee

Browse files
committedJan 31, 2019
feat(crypto_core): add function for unbiased random numbers
1 parent 2c66392 commit 75278ee

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed
 

‎src/toxcore/crypto_core.rs

+11
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,17 @@ pub fn random_usize() -> usize {
6262
random_u64() as usize
6363
}
6464

65+
/// Return unbiased random number from `[0, limit)` interval.
66+
pub fn random_limit_usize(limit: usize) -> usize {
67+
let cap = usize::max_value() - usize::max_value() % limit;
68+
loop {
69+
let n = random_usize();
70+
if n < cap {
71+
return n % limit;
72+
}
73+
}
74+
}
75+
6576
/** Check if Tox public key `PUBLICKEYBYTES` is valid. Should be used only for
6677
input validation.
6778

‎src/toxcore/dht/server/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -508,10 +508,10 @@ impl Server {
508508
return Box::new(future::ok(()))
509509
}
510510

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

517517
let random_node = &good_nodes[random_node_idx];

0 commit comments

Comments
 (0)
Please sign in to comment.