1use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
17use std::sync::{Mutex, PoisonError};
18
19use dive_eval::{Counter, Host, HostError, RunConfig};
20use dive_ir::StdOp;
21use dive_value::{Ctx, ErrorKind, Value};
22
23use crate::random::{
24 RandomError, RandomSource, Stream, Streams, random_element, random_set_of_subsets,
25 random_subset,
26};
27
28const UNSET: i64 = i64::MIN;
30
31#[derive(Debug)]
33pub struct RunHost {
34 inputs: Option<std::sync::Arc<dyn dive_eval::inputs::InputSource>>,
35 streams: Streams,
36 stream: Mutex<Stream>,
37 level: AtomicI64,
38 counters: [AtomicI64; 6],
39 config: Mutex<Option<RunConfig>>,
40 exit: AtomicBool,
41}
42
43fn counter_index(c: Counter) -> usize {
44 match c {
45 Counter::Generated => 0,
46 Counter::Distinct => 1,
47 Counter::Queue => 2,
48 Counter::Diameter => 3,
49 Counter::Initial => 4,
50 Counter::DurationSecs => 5,
51 }
52}
53
54impl RunHost {
55 #[must_use]
58 pub fn new(streams: Streams, config: Option<RunConfig>) -> Self {
59 Self {
60 inputs: None,
61 streams,
62 stream: Mutex::new(streams.startup()),
63 level: AtomicI64::new(UNSET),
64 counters: std::array::from_fn(|_| AtomicI64::new(UNSET)),
65 config: Mutex::new(config),
66 exit: AtomicBool::new(false),
67 }
68 }
69
70 #[must_use]
72 pub fn with_inputs(
73 mut self,
74 inputs: std::sync::Arc<dyn dive_eval::inputs::InputSource>,
75 ) -> Self {
76 self.inputs = Some(inputs);
77 self
78 }
79
80 #[must_use]
82 pub fn streams(&self) -> Streams {
83 self.streams
84 }
85
86 pub fn restart(&self) {
89 *self.stream.lock().unwrap_or_else(PoisonError::into_inner) = self.streams.startup();
90 }
91
92 pub fn expand(&self, fp: u64) {
95 *self.stream.lock().unwrap_or_else(PoisonError::into_inner) = self.streams.state(fp);
96 }
97
98 #[must_use]
100 pub fn stream(&self) -> Stream {
101 *self.stream.lock().unwrap_or_else(PoisonError::into_inner)
102 }
103
104 pub fn set_stream(&self, stream: Stream) {
106 *self.stream.lock().unwrap_or_else(PoisonError::into_inner) = stream;
107 }
108
109 pub fn skip(&self, words: u64) {
114 let mut s = self.stream.lock().unwrap_or_else(PoisonError::into_inner);
115 for _ in 0..words {
116 let _ = s.next_bits(32);
117 }
118 }
119
120 pub fn set_level(&self, level: i64) {
122 self.level.store(level, Ordering::Relaxed);
123 }
124
125 pub fn clear_level(&self) {
137 self.level.store(UNSET, Ordering::Relaxed);
138 }
139
140 pub fn set_counter(&self, c: Counter, value: Option<i64>) {
142 self.counters[counter_index(c)].store(value.unwrap_or(UNSET), Ordering::Relaxed);
143 }
144
145 pub fn set_config(&self, config: Option<RunConfig>) {
147 *self.config.lock().unwrap_or_else(PoisonError::into_inner) = config;
148 }
149
150 #[must_use]
152 pub fn exit_requested(&self) -> bool {
153 self.exit.load(Ordering::Relaxed)
154 }
155}
156
157fn host_error(e: &RandomError) -> HostError {
158 match e {
159 RandomError::Value(v) if v.kind() == ErrorKind::DiveLimit => HostError {
160 code: 0,
161 message: v.message().to_owned(),
162 },
163 _ => HostError {
164 code: e.tlc_code(),
165 message: e.message(),
166 },
167 }
168}
169
170impl Host for RunHost {
171 fn input(
172 &self,
173 request: &dive_eval::inputs::InputRequest,
174 ) -> Option<Result<dive_eval::inputs::InputResponse, HostError>> {
175 self.inputs.as_ref().map(|inputs| inputs.request(request))
176 }
177 fn random(&self, op: StdOp, args: &[Value], ctx: Ctx) -> Option<Result<Value, HostError>> {
178 let mut stream = self.stream.lock().unwrap_or_else(PoisonError::into_inner);
179 let mut bits = |n| stream.next_bits(n);
180 let r = match (op, args) {
181 (StdOp::TlcRandomElement, [s]) => random_element(s, ctx, &mut bits),
182 (StdOp::RandomizationRandomSubset, [k, s]) => random_subset(k, s, ctx, &mut bits),
183 (StdOp::RandomizationRandomSetOfSubsets, [k, n, s]) => {
184 random_set_of_subsets(k, n, s, ctx, &mut bits)
185 }
186 _ => return None,
187 };
188 Some(r.map_err(|e| host_error(&e)))
189 }
190
191 fn level(&self) -> Option<i64> {
192 let l = self.level.load(Ordering::Relaxed);
193 (l != UNSET).then_some(l)
194 }
195
196 fn counter(&self, c: Counter) -> Option<i64> {
197 let v = self.counters[counter_index(c)].load(Ordering::Relaxed);
198 (v != UNSET).then_some(v)
199 }
200
201 fn config(&self) -> Option<RunConfig> {
202 self.config
203 .lock()
204 .unwrap_or_else(PoisonError::into_inner)
205 .clone()
206 }
207
208 fn request_exit(&self) -> bool {
209 self.exit.store(true, Ordering::Relaxed);
210 true
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use crate::random::RandomMode;
218 use dive_value::Int;
219
220 #[test]
221 fn draws_from_the_startup_stream_then_the_state_stream() {
222 let ctx = Ctx::tlc();
223 let host = RunHost::new(Streams::new(7, RandomMode::Tlc), None);
224 let s = Value::interval(Int::Small(1), Int::Small(1_000_000), ctx);
225 let first = host
226 .random(StdOp::TlcRandomElement, std::slice::from_ref(&s), ctx)
227 .and_then(Result::ok);
228 assert_eq!(first, Some(Value::Int(730_700)));
230 host.restart();
231 let again = host
232 .random(StdOp::TlcRandomElement, std::slice::from_ref(&s), ctx)
233 .and_then(Result::ok);
234 assert_eq!(again, first);
235 assert_eq!(host.level(), None);
236 host.set_level(3);
237 assert_eq!(host.level(), Some(3));
238 host.clear_level();
239 assert_eq!(host.level(), None);
240 assert!(!host.exit_requested());
241 assert!(host.request_exit());
242 assert!(host.exit_requested());
243 }
244
245 #[test]
246 fn skipping_matches_drawing_one_word_at_a_time() {
247 for mode in [RandomMode::Tlc, RandomMode::Dive] {
248 let host = RunHost::new(Streams::new(7, mode), None);
249 host.expand(42);
250 let start = host.stream();
251 let mut by_hand = start;
252 for _ in 0..5 {
253 let _ = by_hand.next_bits(31);
254 }
255 host.skip(5);
256 assert_eq!(host.stream(), by_hand);
257 host.set_stream(start);
258 assert_eq!(host.stream(), host.streams().state(42));
259 }
260 }
261}