use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Seek, SeekFrom};
use super::super::FileStore;
use crate::conversation::ids::parse_conversation_id;
use crate::conversation::rows::{REDACTIONS, parse_redaction};
use crate::conversation::search::line_text;
use crate::conversation::{Error, Redaction};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TrailAt {
pub offset: u64,
pub rows: u64,
}
impl FileStore {
pub fn trail_page(
&self,
conversation_id: &str,
at: TrailAt,
limit: usize,
) -> Result<(Vec<Redaction>, Option<TrailAt>), Error> {
let _held = self.lock()?;
parse_conversation_id(conversation_id)?;
if limit < 1 {
return Err(Error::Value(format!("limit must be >= 1, got {limit}")));
}
self.settle(conversation_id)?;
let trail = self.conversation_file(conversation_id, REDACTIONS)?;
if !trail.is_file() {
if at == TrailAt::default() {
return Ok((Vec::new(), None));
}
return Err(changed(conversation_id));
}
let mut reader = BufReader::new(File::open(&trail)?);
if !row_start(&mut reader, at.offset)? {
return Err(changed(conversation_id));
}
let (mut acts, mut next) = (Vec::new(), at);
let mut buffer = String::new();
while acts.len() < limit {
buffer.clear();
let read = reader.read_line(&mut buffer)? as u64;
if read == 0 {
return Ok((acts, None));
}
next = TrailAt {
offset: next.offset + read,
rows: next.rows + 1,
};
let row = parse_redaction(line_text(&buffer), next.rows as usize, conversation_id)?;
acts.push(row);
}
let more = !reader.fill_buf()?.is_empty();
Ok((acts, more.then_some(next)))
}
}
fn row_start(reader: &mut BufReader<File>, offset: u64) -> io::Result<bool> {
if offset == 0 {
return Ok(true);
}
if offset > reader.get_ref().metadata()?.len() {
return Ok(false);
}
reader.seek(SeekFrom::Start(offset - 1))?;
let mut before = [0_u8];
reader.read_exact(&mut before)?;
Ok(before[0] == b'\n')
}
fn changed(conversation_id: &str) -> Error {
Error::Value(format!(
"the erasure trail of {conversation_id} changed while it was read; run the command again"
))
}
#[cfg(test)]
#[path = "trail_tests.rs"]
mod tests;