use coarsetime::Instant;
use i18n_progress::{Progress, View};
use crate::event::Name;
const TAIL_CAP: usize = 4096;
pub(crate) struct Run {
pub(crate) id: u32,
pub(crate) name: Name,
pub(crate) weight: u64,
pub(crate) begin: Instant,
pub(crate) text: String,
pub(crate) reply: bool,
}
impl Run {
pub(crate) fn push_tail(&mut self, s: &str, reply: bool) {
if self.reply != reply {
self.reply = reply;
self.text.clear();
}
self.text.push_str(s);
if self.text.len() > TAIL_CAP {
let mut cut = self.text.len() - TAIL_CAP;
while !self.text.is_char_boundary(cut) {
cut += 1;
}
self.text.drain(..cut);
}
}
}
pub(crate) struct Ended {
pub(crate) name: Name,
pub(crate) secs: f32,
pub(crate) err: Option<String>,
}
pub(crate) struct Board {
pub(crate) progress: Progress,
pub(crate) run_li: Vec<Run>,
pub(crate) hit: usize,
pub(crate) ok: usize,
pub(crate) fail: usize,
begin: Instant,
}
impl Board {
pub(crate) fn new() -> Self {
Self {
progress: Progress::new(0, 0),
run_li: Vec::new(),
hit: 0,
ok: 0,
fail: 0,
begin: Instant::now(),
}
}
pub(crate) fn plan(&mut self, weight: u64, job: usize) {
self.progress = Progress::new(weight, job);
}
pub(crate) fn hit(&mut self, weight: u64) {
self.hit += 1;
self.progress.skip(weight);
}
pub(crate) fn start(&mut self, id: u32, name: Name, weight: u64) {
self.progress.start();
self.run_li.push(Run {
id,
name,
weight,
begin: Instant::now(),
text: String::new(),
reply: false,
});
}
pub(crate) fn run(&mut self, id: u32) -> Option<&mut Run> {
self.run_li.iter_mut().find(|run| run.id == id)
}
pub(crate) fn end(&mut self, id: u32, err: Option<String>) -> Option<(Run, Ended)> {
let pos = self.run_li.iter().position(|run| run.id == id)?;
let mut run = self.run_li.remove(pos);
if err.is_some() {
self.fail += 1;
self.progress.skip(run.weight);
} else {
self.ok += 1;
self.progress.finish(run.weight);
}
let ended = Ended {
name: Name {
lang: std::mem::take(&mut run.name.lang),
file: std::mem::take(&mut run.name.file),
},
secs: secs(run.begin),
err,
};
Some((run, ended))
}
pub(crate) fn view(&self) -> View {
self.progress.view()
}
pub(crate) fn secs(&self) -> f32 {
secs(self.begin)
}
}
pub(crate) fn secs(begin: Instant) -> f32 {
begin.elapsed().as_f64() as f32
}