File tree 2 files changed +22
-2
lines changed
2 files changed +22
-2
lines changed Original file line number Diff line number Diff line change @@ -62,6 +62,19 @@ pub fn random_usize() -> usize {
62
62
random_u64 ( ) as usize
63
63
}
64
64
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
+
65
78
/** Check if Tox public key `PUBLICKEYBYTES` is valid. Should be used only for
66
79
input validation.
67
80
@@ -310,6 +323,13 @@ pub mod tests {
310
323
assert_ne ! ( a, b) ;
311
324
}
312
325
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
+
313
333
#[ test]
314
334
fn public_key_valid_test ( ) {
315
335
crypto_init ( ) . unwrap ( ) ;
Original file line number Diff line number Diff line change @@ -508,10 +508,10 @@ impl Server {
508
508
return Box :: new ( future:: ok ( ( ) ) )
509
509
}
510
510
511
- let mut random_node_idx = random_usize ( ) % good_nodes. len ( ) ;
511
+ let mut random_node_idx = random_limit_usize ( good_nodes. len ( ) ) ;
512
512
// Increase probability of sending packet to a close node (has lower index)
513
513
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 ) ;
515
515
}
516
516
517
517
let random_node = & good_nodes[ random_node_idx] ;
You can’t perform that action at this time.
0 commit comments