use std::cell::RefCell;
use std::collections::BTreeMap;
use raf_source::{Entry, EntryKind, FileId, Opened, RelPath, Tree, TreeError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Op {
Read,
Open,
OpenedRead,
Identity,
List,
Entry,
}
#[derive(Debug, Default)]
struct Tally {
ops: BTreeMap<Op, usize>,
paths: BTreeMap<(Op, String), usize>,
read_log: Vec<String>,
reads_by_id: BTreeMap<FileId, usize>,
calls: usize,
}
pub(crate) struct Counting<T: Tree> {
inner: T,
ceiling: Option<usize>,
tally: RefCell<Tally>,
}
impl<T: Tree> Counting<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner,
ceiling: None,
tally: RefCell::new(Tally::default()),
}
}
pub(crate) fn with_ceiling(mut self, ceiling: usize) -> Self {
self.ceiling = Some(ceiling);
self
}
pub(crate) fn count(&self, op: Op) -> usize {
self.tally.borrow().ops.get(&op).copied().unwrap_or(0)
}
pub(crate) fn count_at(&self, op: Op, path: &str) -> usize {
self.tally
.borrow()
.paths
.get(&(op, path.to_owned()))
.copied()
.unwrap_or(0)
}
pub(crate) fn total(&self) -> usize {
self.tally.borrow().calls
}
pub(crate) fn read_log(&self) -> Vec<String> {
self.tally.borrow().read_log.clone()
}
pub(crate) fn files_read_once(&self) -> usize {
let tally = self.tally.borrow();
assert!(
tally.reads_by_id.values().all(|count| *count == 1),
"{:?}",
tally.reads_by_id
);
tally.reads_by_id.len()
}
fn note(&self, op: Op, path: &RelPath) {
let mut tally = self.tally.borrow_mut();
*tally.ops.entry(op).or_default() += 1;
*tally.paths.entry((op, path.to_string())).or_default() += 1;
if op != Op::OpenedRead {
tally.calls += 1;
if let Some(ceiling) = self.ceiling {
assert!(
tally.calls <= ceiling,
"tree operation ceiling {ceiling} passed by {op:?} of {path}"
);
}
}
}
fn handed_out(&self, path: &RelPath, id: FileId) {
let mut tally = self.tally.borrow_mut();
tally.read_log.push(path.to_string());
*tally.reads_by_id.entry(id).or_default() += 1;
}
}
impl<T: Tree> Tree for Counting<T> {
fn read(&self, path: &RelPath, max_bytes: u64) -> Result<String, TreeError> {
self.note(Op::Read, path);
let id = self.inner.identity(path)?;
self.handed_out(path, id);
self.inner.read(path, max_bytes)
}
fn read_unseen(
&self,
path: &RelPath,
max_bytes: u64,
seen: &dyn Fn(&FileId) -> bool,
) -> Result<Opened, TreeError> {
self.note(Op::Open, path);
let opened = self.inner.read_unseen(path, max_bytes, seen)?;
if let Opened::Read { id, .. } = &opened {
self.note(Op::OpenedRead, path);
self.handed_out(path, id.clone());
}
Ok(opened)
}
fn identity(&self, path: &RelPath) -> Result<FileId, TreeError> {
self.note(Op::Identity, path);
self.inner.identity(path)
}
fn list(&self, path: &RelPath) -> Result<Vec<Entry>, TreeError> {
self.note(Op::List, path);
self.inner.list(path)
}
fn entry(&self, path: &RelPath) -> Result<Option<EntryKind>, TreeError> {
self.note(Op::Entry, path);
self.inner.entry(path)
}
}