1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
use crate::{Line, Point}; use ::lazy_static::lazy_static; use ::rand::rngs::SmallRng; use ::rand::{Rng, SeedableRng}; use ::std::ops::Add; use ::std::ops::Sub; use ::std::sync::Mutex; lazy_static! { static ref GLOBAL_RNG: Mutex<SmallRng> = { let rng = SmallRng::seed_from_u64(100); Mutex::new(rng) }; } #[derive(Copy, Clone)] pub struct Random { min: f32, max: f32, } impl Random { pub fn new(min: f32, max: f32) -> Self { Self { min, max } } pub fn random(&self) -> f32 { random(self.min, self.max) } } pub fn random(min: f32, max: f32) -> f32 { GLOBAL_RNG.lock().unwrap().gen_range(min..max) } impl Add<f32> for Random { type Output = f32; fn add(self, other: f32) -> f32 { other + self.random() } } impl Add<Point<f32>> for Random { type Output = Point; fn add(self, Point(x, y): Point) -> Point { Point(self + x, self + y) } } impl Add<Line<f32>> for Random { type Output = Line; fn add(self, Line(start, end): Line) -> Line { Line(self + start, self + end) } } impl Sub<f32> for Random { type Output = f32; fn sub(self, other: f32) -> f32 { other - self.random() } } impl Sub<Point<f32>> for Random { type Output = Point; fn sub(self, Point(x, y): Point) -> Point { Point(self - x, self - y) } } impl Sub<Line<f32>> for Random { type Output = Line; fn sub(self, Line(start, end): Line) -> Line { Line(self - start, self - end) } }