use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use super::serving::Serving;
#[derive(Debug, PartialEq, Eq)]
pub enum Admit {
Go,
Paused,
Off(String),
}
pub struct Admission<'a> {
pub turn: &'a Path,
pub line: &'a str,
pub paused: &'a Path,
pub serving: Option<&'a Serving>,
}
impl Admission<'_> {
pub fn ours(&self) -> io::Result<bool> {
let mut file = match File::open(self.turn) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error),
};
let mut head = vec![0; self.line.len() + 1];
match file.read_exact(&mut head) {
Ok(()) => Ok(head.strip_suffix(b"\n") == Some(self.line.as_bytes())),
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => Ok(false),
Err(error) => Err(error),
}
}
pub fn allows(&self) -> io::Result<Admit> {
if self.paused.try_exists()? {
return Ok(Admit::Paused);
}
Ok(match self.serving.and_then(Serving::changed) {
Some(message) => Admit::Off(message),
None => Admit::Go,
})
}
pub fn admit(&self) -> io::Result<Admit> {
match self.ours()? {
true => self.allows(),
false => Ok(Admit::Paused),
}
}
}