Skip to content

Commit 286bc66

Browse files
committed
feat(crypto_core): add function for unbiased random numbers
1 parent 3910c66 commit 286bc66

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/toxcore/crypto_core.rs

+20
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,19 @@ 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+
// TODO: possibly migrate to rand crate, it has more performant version
68+
// of this algorithm implemented with UniformSampler trait
69+
let cap = usize::max_value() - usize::max_value() % limit;
70+
loop {
71+
let n = random_usize();
72+
if n < cap {
73+
return n % limit;
74+
}
75+
}
76+
}
77+
6578
/** Check if Tox public key `PUBLICKEYBYTES` is valid. Should be used only for
6679
input validation.
6780
@@ -310,6 +323,13 @@ pub mod tests {
310323
assert_ne!(a, b);
311324
}
312325

326+
#[test]
327+
fn random_limit_usize_test() {
328+
crypto_init().unwrap();
329+
let n = random_limit_usize(7);
330+
assert!(n < 7);
331+
}
332+
313333
#[test]
314334
fn public_key_valid_test() {
315335
crypto_init().unwrap();

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)