use std::collections::HashMap;
use std::num::Wrapping;
use std::sync::Arc;
use fuser::Errno;
#[derive(Debug)]
pub(crate) struct DirectoryCache {
next_key: Wrapping<u64>,
entries: HashMap<u64, DirectoryCacheEntry>,
}
macro_rules! real_fh_or_reply_error {
($p:expr, $reply:expr) => {
match $p {
Some(value) => value,
_ => {
$reply.error(Errno::EINVAL);
return;
}
}
};
}
pub(crate) use real_fh_or_reply_error;
impl DirectoryCache {
pub(crate) fn new() -> DirectoryCache {
DirectoryCache {
next_key: Wrapping(1),
entries: HashMap::new(),
}
}
pub(crate) fn new_entry(&mut self, fh: u64) -> u64 {
let key = self.next_key.0;
self.entries.insert(key, DirectoryCacheEntry::new(fh));
self.next_key += Wrapping(1);
key
}
pub(crate) fn real_fh(&self, key: u64) -> Option<u64> {
self.entries.get(&key).map(|v| v.fh).or_else(|| {
log::error!("no real fh found for {key}!");
None
})
}
pub(crate) fn delete(&mut self, key: u64) {
self.entries.remove(&key);
}
}
#[derive(Debug)]
pub(crate) struct DirectoryCacheEntry {
pub(crate) fh: u64,
}
impl DirectoryCacheEntry {
pub(crate) fn new(fh: u64) -> DirectoryCacheEntry {
DirectoryCacheEntry { fh }
}
}
pub(crate) struct ReaddirState<P, E> {
pub(crate) entries: Vec<E>,
pub(crate) producer: Option<P>,
pub(crate) pending_error: Option<Errno>,
}
impl<P, E> ReaddirState<P, E> {
pub(crate) fn new(producer: P) -> Self {
Self {
entries: Vec::new(),
producer: Some(producer),
pending_error: None,
}
}
}
impl<P, E: std::fmt::Debug> std::fmt::Debug for ReaddirState<P, E> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ReaddirState")
.field("entries", &self.entries)
.field("producer_active", &self.producer.is_some())
.field("pending_error", &self.pending_error)
.finish()
}
}
#[derive(Debug)]
pub(crate) struct ReaddirCache<S> {
entries: HashMap<u64, Arc<S>>,
}
impl<S> ReaddirCache<S> {
pub(crate) fn new() -> Self {
Self {
entries: HashMap::new(),
}
}
pub(crate) fn insert(&mut self, key: u64, slot: S) {
self.entries.insert(key, Arc::new(slot));
}
pub(crate) fn get(&self, key: u64) -> Option<Arc<S>> {
self.entries.get(&key).cloned()
}
pub(crate) fn delete(&mut self, key: u64) {
self.entries.remove(&key);
}
}
#[cfg(test)]
mod tests {
use super::DirectoryCache;
#[test]
fn duplicate_target_handles_receive_distinct_cache_keys() {
let mut cache = DirectoryCache::new();
let first = cache.new_entry(0);
let second = cache.new_entry(0);
assert_ne!(first, second);
assert_eq!(cache.real_fh(first), Some(0));
assert_eq!(cache.real_fh(second), Some(0));
}
#[test]
fn missing_cache_key_has_no_real_handle() {
let cache = DirectoryCache::new();
assert_eq!(cache.real_fh(1), None);
}
}