[GH-ISSUE #253] Inappropriate use of the rand module #122

Closed
opened 2026-03-07 22:22:11 +03:00 by kerem · 0 comments
Owner

Originally created by @briansmith on GitHub (Oct 24, 2017).
Original GitHub issue: https://github.com/hickory-dns/hickory-dns/issues/253

I noticed some issues with the use of the rand crate.

        let mut rand = rand::thread_rng();

        for _ in 0..100 {
            let id = rand.gen_range(0_u16, u16::max_value());

            if !self.active_requests.contains_key(&id) {
                return Async::Ready(id);
            }
        }
  1. rand.gen_range(0_u16, u16::max_value()) will never return u16::max_value() because the upper bound is exclusive, not inclusive.
  2. The documentation for rand.gen_range() says that if multiple calls are made, then distributions::Range should be used instead; see the documentation for why.

I believe the correct fix is to use the Rand implementation for u16, i.e. let id = u16::rand(&rng);

Originally created by @briansmith on GitHub (Oct 24, 2017). Original GitHub issue: https://github.com/hickory-dns/hickory-dns/issues/253 I noticed some issues with the use of the `rand` crate. ```rust let mut rand = rand::thread_rng(); for _ in 0..100 { let id = rand.gen_range(0_u16, u16::max_value()); if !self.active_requests.contains_key(&id) { return Async::Ready(id); } } ``` 1. `rand.gen_range(0_u16, u16::max_value())` will never return `u16::max_value()` because the upper bound is exclusive, not inclusive. 2. The documentation for `rand.gen_range()` says that if multiple calls are made, then `distributions::Range` should be used instead; see the documentation for why. I believe the correct fix is to use the `Rand` implementation for `u16`, i.e. `let id = u16::rand(&rng);`
kerem 2026-03-07 22:22:11 +03:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/hickory-dns#122
No description provided.