use super::{Context, Input, Result};
pub struct Memory<'a> {
lines: std::str::SplitInclusive<'a, char>,
}
impl Memory<'_> {
pub fn new(code: &str) -> Memory<'_> {
let lines = code.split_inclusive('\n');
Memory { lines }
}
}
impl<'a> From<&'a str> for Memory<'a> {
fn from(code: &'a str) -> Memory<'a> {
Memory::new(code)
}
}
impl Input for Memory<'_> {
async fn next_line(&mut self, _context: &Context) -> Result {
Ok(self.lines.next().unwrap_or("").to_owned())
}
}
#[cfg(test)]
mod tests {
use super::{Context, Input, Memory};
use futures_util::FutureExt as _;
#[test]
fn memory_empty_source() {
let mut input = Memory::new("");
let context = Context::default();
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "");
}
#[test]
fn memory_one_line() {
let mut input = Memory::new("one\n");
let context = Context::default();
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "one\n");
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "");
}
#[test]
fn memory_three_lines() {
let mut input = Memory::new("one\ntwo\nthree");
let context = Context::default();
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "one\n");
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "two\n");
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "three");
let line = input.next_line(&context).now_or_never().unwrap().unwrap();
assert_eq!(line, "");
}
}