util: implement generic random_range
This commit is contained in:
parent
1a32e1c46f
commit
3ab3c478c3
|
@ -50,7 +50,7 @@ impl Client {
|
|||
|
||||
// Select an upstream randomly
|
||||
fn select_upstream(&self) -> String {
|
||||
let idx = crate::util::random() * self.options.upstream_urls.len() as f64;
|
||||
let idx = crate::util::random_range(0, self.options.upstream_urls.len() as u16);
|
||||
self.options.upstream_urls[idx as usize].clone()
|
||||
}
|
||||
|
||||
|
@ -61,7 +61,7 @@ impl Client {
|
|||
let mut builder = MessageBuilder::new_udp();
|
||||
// Set up the header
|
||||
let header = builder.header_mut();
|
||||
header.set_id((crate::util::random() * u16::MAX as f64) as u16);
|
||||
header.set_id(crate::util::random_range(0, u16::MAX));
|
||||
header.set_qr(false); // For queries, QR = false
|
||||
header.set_opcode(Opcode::Query);
|
||||
header.set_rd(true); // Ask for recursive queries
|
||||
|
|
18
src/util.rs
18
src/util.rs
|
@ -1,6 +1,7 @@
|
|||
use bytes::Bytes;
|
||||
use domain_core::bits::message::Message;
|
||||
use js_sys::{Math, Promise};
|
||||
use std::ops::Add;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
@ -32,3 +33,20 @@ pub async fn fetch_rs(req: &Request) -> Result<JsValue, JsValue> {
|
|||
pub fn random() -> f64 {
|
||||
unsafe { Math::random() }
|
||||
}
|
||||
|
||||
pub fn random_range<T>(min: T, max: T) -> T
|
||||
where
|
||||
T: Ord + Into<f64> + FromFloat<f64> + Add<Output = T>,
|
||||
{
|
||||
min + T::from_float(random() * max.into())
|
||||
}
|
||||
|
||||
pub trait FromFloat<F> {
|
||||
fn from_float(f: F) -> Self;
|
||||
}
|
||||
|
||||
impl FromFloat<f64> for u16 {
|
||||
fn from_float(f: f64) -> u16 {
|
||||
f as u16
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue