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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
///all structs
#[allow(warnings)]
pub mod structs {
/// A Linear Congruential Generator (LCG) is a simple type of random number generator
/// that produces a sequence of pseudo-random numbers based on a linear recurrence relation.
pub struct LCG {
seed: u128,
a: u128,
c: u128,
m: u128,
}
impl LCG {
/// Creates a new LCG instance with the specified initial seed is timestamp as nanoseconds.
///
/// ```rust
///use doe::*;
///let lcg = LCG::new();
///for _ in 0..10000{
/// let data = lcg.random_in_range(1..=20).to_string().push_back("\n");
/// fs::fs::append_data_to_file("doe.txt", data).unwrap();
///}
/// ```
/// # Returns
///
/// A new `LCG` instance with the specified seed and default constants.
pub fn new() -> LCG {
let seed = std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
Self::init(seed, 1664525, 1013904223, 2u128.pow(32))
}
///random_in_range
/// ```rust
///use doe::*;
///let lcg = LCG::new();
///for _ in 0..10000{
/// lcg.random_in_range(-30..30).dprintln();
///}
/// ```
///
pub fn random_in_range(&self, range: impl std::ops::RangeBounds<i128>) -> i128 {
let min = match range.start_bound() {
std::ops::Bound::Included(v) => *v,
std::ops::Bound::Excluded(v) => *v,
std::ops::Bound::Unbounded => 0,
};
let max = match range.end_bound() {
std::ops::Bound::Included(v) => *v + 1,
std::ops::Bound::Excluded(v) => *v,
std::ops::Bound::Unbounded => i128::MAX,
};
let random = Self::new().random();
let sub = (max - min) as f64;
f64::floor(random * sub) as i128 + min
}
///random_in_range_f64
///```rust
///use doe::*;
///let lcg = LCG::new();
///for _ in 0..10000{
/// lcg.random_in_range_f64(-30.0..30.0).dprintln();
///}
/// ```
pub fn random_in_range_f64(&self, range: impl std::ops::RangeBounds<f64>) -> f64 {
let min = match range.start_bound() {
std::ops::Bound::Included(v) => *v,
std::ops::Bound::Excluded(v) => *v,
std::ops::Bound::Unbounded => 0.0,
};
let max = match range.end_bound() {
std::ops::Bound::Included(v) => *v,
std::ops::Bound::Excluded(v) => *v,
std::ops::Bound::Unbounded => f64::MAX,
};
let random = Self::new().random();
let sub = max - min;
(random * sub) + min
}
/// Creates a new LCG instance with the specified initial seed value.
///
/// # Arguments
///
/// * `seed` - The initial seed value for the LCG.
///
/// # Returns
///
/// A new `LCG` instance with the specified seed and default constants.
pub fn new_with_seed(seed: u128) -> LCG {
Self::init(seed, 1664525, 1013904223, 2u128.pow(32))
}
/// Creates a new LCG instance with the specified initial seed value and constants.
///
/// # Arguments
///
/// * `seed` - The initial seed value for the LCG.
/// * `a` - The multiplier constant for the LCG.
/// * `c` - The increment constant for the LCG.
/// * `m` - The modulus constant for the LCG.
///
/// # Returns
///
/// A new `LCG` instance with the specified seed and constants.
pub fn init(seed: u128, a: u128, c: u128, m: u128) -> LCG {
LCG { seed, a, c, m }
}
/// Generates the next random number in the sequence.
///
/// # Returns
///
/// The next pseudo-random number in the sequence as a `f64` value between 0 and 1.
pub fn random(&mut self) -> f64 {
self.seed = (self.a * self.seed + self.c) % self.m;
self.seed as f64 / self.m as f64
}
}
use std::default::Default;
use std::fmt::{self, Display};
use std::ops::{Deref, RangeBounds};
///## implments Bfn struct and bfn! macro for Box<dyn Fn()> trait object
///```rust
///fn main() {
/// use doe::*;
///
/// #[derive(Debug)]
/// struct Demo<'a>{
/// name:&'a str
/// }
/// fn func()->Demo<'static>{
/// let d = Demo{name: "andrew"};
/// d
/// }
/// let f1 = bfn!(func);
/// f1.call().dprintln();
///
/// fn sum()->usize{
/// 9+89
/// }
/// let f2 = Bfn::new(Box::new(sum));//or bfn!(sum);
/// f2.call().println();
///}
///```
pub struct Bfn<T: Unpin>(Box<dyn Fn() -> T>);
impl<T: Unpin> Bfn<T> {
pub fn new(v: Box<dyn Fn() -> T>) -> Self {
Self(v)
}
pub fn new_fn(v: &'static dyn Fn() -> T) -> Self {
Self::new(Box::new(v))
}
pub fn call(&self) -> T {
self.0.deref()()
}
}
///## implments Bts struct and bts! macro for Box<\dyn ToString> trait object
/// ```rust
///fn main() {
/// use doe::*;
/// let mut s:Bts = bts!("Trait Object, it's ");
/// s.push(bts!(100));
/// s.push_str("% safe");
/// s.dprintln();//"Trait Object, it's 100% safe"
/// s.as_bytes().dprintln();//[84, 114, 97, 105, 116, 32, 79, 98, 106, 101, 99, 116, 44, 32, 105, 116, 39, 115, 32, 49, 48, 48, 37, 32, 115, 97, 102, 101]
/// s.chars().dprintln();//['T', 'r', 'a', 'i', 't', ' ', 'O', 'b', 'j', 'e', 'c', 't', ',', ' ', 'i', 't', '\'', 's', ' ', '1', '0', '0', '%', ' ', 's', 'a', 'f', 'e']
/// let b = Into::<Bts>::into("b".to_string());
/// let b = Bts::from("demo");
///}
///```
pub struct Bts(Box<dyn ToString>);
impl Bts {
///
/// ```rust
///fn main() {
/// use doe::*;
/// let mut s:Bts = bts!("Trait Object, it's ");
/// s.push(bts!(100));
/// s.push_str("% safe");
/// s.dprintln();//"Trait Object, it's 100% safe"
/// s.as_bytes().dprintln();//[84, 114, 97, 105, 116, 32, 79, 98, 106, 101, 99, 116, 44, 32, 105, 116, 39, 115, 32, 49, 48, 48, 37, 32, 115, 97, 102, 101]
/// s.chars().dprintln();//['T', 'r', 'a', 'i', 't', ' ', 'O', 'b', 'j', 'e', 'c', 't', ',', ' ', 'i', 't', '\'', 's', ' ', '1', '0', '0', '%', ' ', 's', 'a', 'f', 'e']
/// let b = Into::<Bts>::into("b".to_string());
/// let b = Bts::from("demo");
///}
///```
pub fn new(v: Box<dyn ToString>) -> Bts {
Self(v)
}
pub fn push_str(&mut self, string: &str) {
let mut self_string = self.0.to_string();
self_string.push_str(string);
self.0 = Box::new(self_string);
}
///
/// ```rust
/// use doe::*;
/// let mut s:Bts = bts!("Trait Object, it's ");
/// s.push(bts!(100));
/// s.push_str("% safe");
/// s.println();//"Trait Object, it's 100% safe"
/// s.as_bytes().dprintln();//[84, 114, 97, 105, 116, 32, 79, 98, 106, 101, 99, 116, 44, 32, 105, 116, 39, 115, 32, 49, 48, 48, 37, 32, 115, 97, 102, 101]
/// s.chars().dprintln();//['T', 'r', 'a', 'i', 't', ' ', 'O', 'b', 'j', 'e', 'c', 't', ',', ' ', 'i', 't', '\'', 's', ' ', '1', '0', '0', '%', ' ', 's', 'a', 'f', 'e']
/// let b = Into::<Bts>::into("b".to_string());
/// let b = Bts::from("demo");
///```
pub fn push(&mut self, bts: Bts) {
let mut self_string = self.0.to_string();
self_string.push_str(&bts.0.as_ref().to_string());
self.0 = Box::new(self_string);
}
pub fn chars(&self) -> Vec<char> {
self.0.to_string().chars().collect()
}
pub fn as_bytes(&self) -> Vec<u8> {
self.0.to_string().as_bytes().to_vec()
}
// pub fn to_string(&self) -> String {
// self.0.to_string()
// }
}
impl Default for Bts {
fn default() -> Self {
crate::bts!("")
}
}
impl Unpin for Bts {}
unsafe impl Sync for Bts {}
unsafe impl Send for Bts {}
impl std::panic::RefUnwindSafe for Bts {}
impl std::panic::UnwindSafe for Bts {}
impl fmt::Debug for Bts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.0.to_string())
}
}
impl fmt::Display for Bts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0.to_string())
}
}
impl Clone for Bts {
fn clone(&self) -> Self {
Bts::new(Box::new(self.0.to_string()))
}
}
impl From<String> for Bts {
fn from(s: String) -> Self {
Bts(Box::new(s))
}
}
impl<T: core::fmt::Debug> From<Vec<T>> for Bts {
fn from(s: Vec<T>) -> Self {
Bts(Box::new(format!("{:?}", s)))
}
}
impl From<&str> for Bts {
fn from(s: &str) -> Self {
Bts(Box::new(s.to_string()))
}
}
extern crate alloc;
use alloc::sync::Arc;
use core::mem::{self, ManuallyDrop};
use core::task::{RawWaker, RawWakerVTable, Waker};
/// Converts a closure into a [`Waker`].
///
/// The closure gets called every time the waker is woken.
///
/// # Examples
///
/// ```
/// use doe::waker_fn;
///
/// let waker = waker_fn(|| println!("woken"));
///
/// waker.wake_by_ref(); // Prints "woken".
/// waker.wake(); // Prints "woken".
/// ```
pub fn waker_fn<F: Fn() + Send + Sync + 'static>(f: F) -> Waker {
let raw = Arc::into_raw(Arc::new(f)) as *const ();
let vtable = &Helper::<F>::VTABLE;
unsafe { Waker::from_raw(RawWaker::new(raw, vtable)) }
}
struct Helper<F>(F);
impl<F: Fn() + Send + Sync + 'static> Helper<F> {
const VTABLE: RawWakerVTable = RawWakerVTable::new(
Self::clone_waker,
Self::wake,
Self::wake_by_ref,
Self::drop_waker,
);
unsafe fn clone_waker(ptr: *const ()) -> RawWaker {
let arc = ManuallyDrop::new(Arc::from_raw(ptr as *const F));
mem::forget(arc.clone());
RawWaker::new(ptr, &Self::VTABLE)
}
unsafe fn wake(ptr: *const ()) {
let arc = Arc::from_raw(ptr as *const F);
(arc)();
}
unsafe fn wake_by_ref(ptr: *const ()) {
let arc = ManuallyDrop::new(Arc::from_raw(ptr as *const F));
(arc)();
}
unsafe fn drop_waker(ptr: *const ()) {
drop(Arc::from_raw(ptr as *const F));
}
}
}