use std::borrow::Cow;
use std::fs::File;
use std::io::{BufRead, BufReader, Split};
use std::path::PathBuf;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use choon::{MeasureThresholds, Measured};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Kept<'a> {
pub file: Cow<'a, str>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file_bytes: Option<Cow<'a, [u8]>>,
pub version: Cow<'a, str>,
pub measure: Cow<'a, MeasureThresholds>,
pub measured: Cow<'a, Measured>,
}
#[derive(Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
struct Named {
file: String,
#[serde(default)]
file_bytes: Option<Vec<u8>>,
}
impl Named {
#[cfg(unix)]
fn path(self) -> PathBuf {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
match self.file_bytes {
Some(bytes) => OsString::from_vec(bytes).into(),
None => self.file.into(),
}
}
#[cfg(not(unix))]
fn path(self) -> PathBuf {
self.file.into()
}
}
pub struct Group {
pub line: usize,
pub path: Result<PathBuf, String>,
pub lines: Vec<(usize, Vec<u8>)>,
}
fn fault(line: usize, why: impl std::fmt::Display) -> String {
format!("measures file line {line}: {why}")
}
pub fn unparsed(line: usize, error: &serde_json::Error) -> String {
let said = error.to_string();
let place = format!(" at line {} column {}", error.line(), error.column());
fault(line, said.strip_suffix(&place).unwrap_or(&said))
}
type Line = (usize, Result<Named, String>, Vec<u8>);
pub struct Groups {
lines: Split<BufReader<File>>,
read: usize,
ahead: Option<Line>,
failed: bool,
}
impl Groups {
pub fn new(file: File) -> Self {
Self {
lines: BufReader::new(file).split(b'\n'),
read: 0,
ahead: None,
failed: false,
}
}
pub fn until<'a>(
mut self,
stop: &'a AtomicBool,
total: &'a OnceLock<usize>,
) -> impl Iterator<Item = Group> + 'a {
let mut given = 0;
std::iter::from_fn(move || {
let Some(group) = self.next() else {
total.get_or_init(|| given);
return None;
};
if stop.load(Ordering::Relaxed) {
return None;
}
given += 1;
Some(group)
})
}
fn line(&mut self) -> Option<Line> {
while !self.failed {
let line = self.lines.next()?;
self.read += 1;
match line {
Ok(bytes) if bytes.trim_ascii().is_empty() => {}
Ok(bytes) => {
let named = serde_json::from_slice(&bytes).map_err(|e| unparsed(self.read, &e));
return Some((self.read, named, bytes));
}
Err(e) => {
self.failed = true;
return Some((self.read, Err(fault(self.read, e)), Vec::new()));
}
}
}
None
}
}
impl Iterator for Groups {
type Item = Group;
fn next(&mut self) -> Option<Group> {
let (line, named, bytes) = self.ahead.take().or_else(|| self.line())?;
let mut lines = vec![(line, bytes)];
if let Ok(named) = &named {
loop {
match self.line() {
Some((line, Ok(next), bytes)) if next == *named => lines.push((line, bytes)),
ahead => {
self.ahead = ahead;
break;
}
}
}
}
Some(Group {
line,
path: named.map(Named::path),
lines,
})
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use super::Groups;
#[test]
fn a_stop_after_the_last_group_leaves_the_file_read_to_its_end() {
let dir = tempfile::tempdir().unwrap();
let measures = dir.path().join("measures.jsonl");
let lines = "{\"file\": \"a\"}\n{\"file\": \"a\"}\n\n{\"file\": \"b\"}\n";
std::fs::write(&measures, lines).unwrap();
let groups = || Groups::new(File::open(&measures).unwrap());
let (stop, total) = (AtomicBool::new(false), OnceLock::new());
let mut read = groups().until(&stop, &total);
assert_eq!(read.next().unwrap().lines.len(), 2);
assert_eq!(read.next().unwrap().line, 4);
assert_eq!(total.get(), None);
stop.store(true, Ordering::Relaxed);
assert!(read.next().is_none());
assert_eq!(total.get(), Some(&2));
let (stop, total) = (AtomicBool::new(false), OnceLock::new());
let mut read = groups().until(&stop, &total);
assert!(read.next().is_some());
stop.store(true, Ordering::Relaxed);
assert!(read.next().is_none());
assert_eq!(total.get(), None);
}
}