use std::io::BufRead;
use super::eval::Value;
pub struct StimulusParser<R: BufRead>(R);
impl<R: BufRead> StimulusParser<R> {
pub fn new(reader: R) -> Self {
Self(reader)
}
}
pub trait Stimulus {
type Vector: AsRef<[Value]>;
fn next_vector(&mut self) -> Option<Self::Vector>;
}
impl<'a> Stimulus for &'a [Vec<Value>] {
type Vector = &'a [Value];
fn next_vector(&mut self) -> Option<Self::Vector> {
let (first, remaining) = (*self).split_first()?;
*self = remaining;
Some(first.as_slice())
}
}
impl<R: BufRead> Stimulus for StimulusParser<R> {
type Vector = Vec<Value>;
fn next_vector(&mut self) -> Option<Self::Vector> {
let mut line = String::new();
let bytes_read = self
.0
.read_line(&mut line)
.expect("failed to read stimulus file");
if bytes_read == 0 {
return None;
}
let line = line.trim_end_matches(&['\r', '\n'][..]);
if line == "." {
return None;
}
let values: Vec<_> = line
.bytes()
.enumerate()
.map(|(column, byte)| match byte {
b'0' => 0,
b'1' => Value::MAX,
b'x' => {
panic!("column {}: 'x' is not currently supported", column + 1);
}
other => {
panic!(
"column {}: expected '0' or '1', found {:?}",
column + 1,
char::from(other)
);
}
})
.collect();
Some(values)
}
}