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
use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Rc;
pub trait Source {
fn read_u64(&mut self) -> u64;
#[inline(always)]
fn read_f64(&mut self) -> f64 {
self.read_u64() as f64 / (::std::u64::MAX as f64 + 1.0)
}
#[inline(always)]
fn read<T: Element>(&mut self) -> T where Self: Sized {
Element::from(self)
}
#[inline(always)]
fn iter<'l, T: Element>(&'l mut self) -> Sequence<'l, Self, T> where Self: Sized {
Sequence { source: self, phantom: PhantomData }
}
}
pub struct Sequence<'l, S: ?Sized, E> where S: Source + 'l, E: Element + 'l {
source: &'l mut S,
phantom: PhantomData<&'l E>,
}
pub trait Element {
fn from<T: Source>(&mut T) -> Self;
}
impl<'l, S, E> Iterator for Sequence<'l, S, E> where S: Source, E: Element {
type Item = E;
#[inline(always)]
fn next(&mut self) -> Option<E> {
Some(self.source.read())
}
}
impl Element for f64 {
#[inline(always)]
fn from<T: Source>(source: &mut T) -> f64 {
source.read_f64()
}
}
impl Element for u64 {
#[inline(always)]
fn from<T: Source>(source: &mut T) -> u64 {
source.read_u64()
}
}
#[derive(Clone)]
pub struct Default(Rc<RefCell<Xorshift128Plus>>);
impl Default {
#[inline(always)]
pub fn seed(self, seed: [u64; 2]) -> Default {
*self.0.borrow_mut() = Xorshift128Plus::new(seed);
self
}
}
impl Source for Default {
#[inline(always)]
fn read_u64(&mut self) -> u64 {
self.0.borrow_mut().read_u64()
}
}
#[inline(always)]
pub fn default() -> Default {
thread_local!(static DEFAULT: Rc<RefCell<Xorshift128Plus>> = {
Rc::new(RefCell::new(Xorshift128Plus::new([42, 69])))
});
Default(DEFAULT.with(|source| source.clone()))
}
mod xorshift;
pub use self::xorshift::Xorshift128Plus;