use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
use std::sync::{Mutex, PoisonError};
use dive_eval::{Counter, Host, HostError, RunConfig};
use dive_ir::StdOp;
use dive_value::{Ctx, ErrorKind, Value};
use crate::random::{
RandomError, RandomSource, Stream, Streams, random_element, random_set_of_subsets,
random_subset,
};
const UNSET: i64 = i64::MIN;
#[derive(Debug)]
pub struct RunHost {
inputs: Option<std::sync::Arc<dyn dive_eval::inputs::InputSource>>,
streams: Streams,
stream: Mutex<Stream>,
level: AtomicI64,
counters: [AtomicI64; 6],
config: Mutex<Option<RunConfig>>,
exit: AtomicBool,
}
fn counter_index(c: Counter) -> usize {
match c {
Counter::Generated => 0,
Counter::Distinct => 1,
Counter::Queue => 2,
Counter::Diameter => 3,
Counter::Initial => 4,
Counter::DurationSecs => 5,
}
}
impl RunHost {
#[must_use]
pub fn new(streams: Streams, config: Option<RunConfig>) -> Self {
Self {
inputs: None,
streams,
stream: Mutex::new(streams.startup()),
level: AtomicI64::new(UNSET),
counters: std::array::from_fn(|_| AtomicI64::new(UNSET)),
config: Mutex::new(config),
exit: AtomicBool::new(false),
}
}
#[must_use]
pub fn with_inputs(
mut self,
inputs: std::sync::Arc<dyn dive_eval::inputs::InputSource>,
) -> Self {
self.inputs = Some(inputs);
self
}
#[must_use]
pub fn streams(&self) -> Streams {
self.streams
}
pub fn restart(&self) {
*self.stream.lock().unwrap_or_else(PoisonError::into_inner) = self.streams.startup();
}
pub fn expand(&self, fp: u64) {
*self.stream.lock().unwrap_or_else(PoisonError::into_inner) = self.streams.state(fp);
}
#[must_use]
pub fn stream(&self) -> Stream {
*self.stream.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn set_stream(&self, stream: Stream) {
*self.stream.lock().unwrap_or_else(PoisonError::into_inner) = stream;
}
pub fn skip(&self, words: u64) {
let mut s = self.stream.lock().unwrap_or_else(PoisonError::into_inner);
for _ in 0..words {
let _ = s.next_bits(32);
}
}
pub fn set_level(&self, level: i64) {
self.level.store(level, Ordering::Relaxed);
}
pub fn clear_level(&self) {
self.level.store(UNSET, Ordering::Relaxed);
}
pub fn set_counter(&self, c: Counter, value: Option<i64>) {
self.counters[counter_index(c)].store(value.unwrap_or(UNSET), Ordering::Relaxed);
}
pub fn set_config(&self, config: Option<RunConfig>) {
*self.config.lock().unwrap_or_else(PoisonError::into_inner) = config;
}
#[must_use]
pub fn exit_requested(&self) -> bool {
self.exit.load(Ordering::Relaxed)
}
}
fn host_error(e: &RandomError) -> HostError {
match e {
RandomError::Value(v) if v.kind() == ErrorKind::DiveLimit => HostError {
code: 0,
message: v.message().to_owned(),
},
_ => HostError {
code: e.tlc_code(),
message: e.message(),
},
}
}
impl Host for RunHost {
fn input(
&self,
request: &dive_eval::inputs::InputRequest,
) -> Option<Result<dive_eval::inputs::InputResponse, HostError>> {
self.inputs.as_ref().map(|inputs| inputs.request(request))
}
fn random(&self, op: StdOp, args: &[Value], ctx: Ctx) -> Option<Result<Value, HostError>> {
let mut stream = self.stream.lock().unwrap_or_else(PoisonError::into_inner);
let mut bits = |n| stream.next_bits(n);
let r = match (op, args) {
(StdOp::TlcRandomElement, [s]) => random_element(s, ctx, &mut bits),
(StdOp::RandomizationRandomSubset, [k, s]) => random_subset(k, s, ctx, &mut bits),
(StdOp::RandomizationRandomSetOfSubsets, [k, n, s]) => {
random_set_of_subsets(k, n, s, ctx, &mut bits)
}
_ => return None,
};
Some(r.map_err(|e| host_error(&e)))
}
fn level(&self) -> Option<i64> {
let l = self.level.load(Ordering::Relaxed);
(l != UNSET).then_some(l)
}
fn counter(&self, c: Counter) -> Option<i64> {
let v = self.counters[counter_index(c)].load(Ordering::Relaxed);
(v != UNSET).then_some(v)
}
fn config(&self) -> Option<RunConfig> {
self.config
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
fn request_exit(&self) -> bool {
self.exit.store(true, Ordering::Relaxed);
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::random::RandomMode;
use dive_value::Int;
#[test]
fn draws_from_the_startup_stream_then_the_state_stream() {
let ctx = Ctx::tlc();
let host = RunHost::new(Streams::new(7, RandomMode::Tlc), None);
let s = Value::interval(Int::Small(1), Int::Small(1_000_000), ctx);
let first = host
.random(StdOp::TlcRandomElement, std::slice::from_ref(&s), ctx)
.and_then(Result::ok);
assert_eq!(first, Some(Value::Int(730_700)));
host.restart();
let again = host
.random(StdOp::TlcRandomElement, std::slice::from_ref(&s), ctx)
.and_then(Result::ok);
assert_eq!(again, first);
assert_eq!(host.level(), None);
host.set_level(3);
assert_eq!(host.level(), Some(3));
host.clear_level();
assert_eq!(host.level(), None);
assert!(!host.exit_requested());
assert!(host.request_exit());
assert!(host.exit_requested());
}
#[test]
fn skipping_matches_drawing_one_word_at_a_time() {
for mode in [RandomMode::Tlc, RandomMode::Dive] {
let host = RunHost::new(Streams::new(7, mode), None);
host.expand(42);
let start = host.stream();
let mut by_hand = start;
for _ in 0..5 {
let _ = by_hand.next_bits(31);
}
host.skip(5);
assert_eq!(host.stream(), by_hand);
host.set_stream(start);
assert_eq!(host.stream(), host.streams().state(42));
}
}
}