use crate::error::EntryError;
use crate::predicate::{EntryMeta, EntryType, MetaMask};
use crate::syntax::CodePoint;
use crate::sys::signal::Signal;
use crossbeam_queue::ArrayQueue;
use std::collections::VecDeque;
use std::num::NonZeroU64;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ContainerId(pub NonZeroU64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DecisionToken(pub NonZeroU64);
#[derive(Debug)]
pub struct IdSpace(AtomicU64);
impl IdSpace {
pub fn new() -> Self {
Self(AtomicU64::new(1))
}
pub fn next_raw(&self) -> NonZeroU64 {
let v = self.0.fetch_add(1, Ordering::Relaxed);
NonZeroU64::new(v).expect("id space overflow")
}
pub fn next_container(&self) -> ContainerId {
ContainerId(self.next_raw())
}
pub fn next_decision(&self) -> DecisionToken {
DecisionToken(self.next_raw())
}
}
impl Default for IdSpace {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Name {
units: Vec<CodePoint>,
}
impl Name {
pub fn from_code_points(units: &[CodePoint]) -> Self {
Self {
units: units.to_vec(),
}
}
pub fn code_points(&self) -> &[CodePoint] {
&self.units
}
pub fn to_string_lossy(&self) -> String {
self.units
.iter()
.map(|&c| char::from_u32(c).unwrap_or('\u{FFFD}'))
.collect()
}
pub fn len(&self) -> usize {
self.units.len()
}
pub fn is_empty(&self) -> bool {
self.units.is_empty()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContainerName {
Entry(Name),
Root(u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PatternMask {
words: Box<[u64]>,
}
impl PatternMask {
pub fn new(num_patterns: usize) -> Self {
let words = num_patterns.div_ceil(64).max(1);
Self {
words: vec![0u64; words].into_boxed_slice(),
}
}
pub fn from_indices(num_patterns: usize, indices: &[usize]) -> Self {
let mut m = Self::new(num_patterns);
for &i in indices {
m.set(i);
}
m
}
pub fn set(&mut self, index: usize) {
self.words[index / 64] |= 1u64 << (index % 64);
}
pub fn contains(&self, index: usize) -> bool {
self.words
.get(index / 64)
.is_some_and(|w| w & (1u64 << (index % 64)) != 0)
}
pub fn any(&self) -> bool {
self.words.iter().any(|&w| w != 0)
}
pub fn count(&self) -> usize {
self.words.iter().map(|w| w.count_ones() as usize).sum()
}
pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
self.words.iter().enumerate().flat_map(|(wi, &w)| {
(0..64)
.filter(move |b| w & (1u64 << b) != 0)
.map(move |b| wi * 64 + b)
})
}
}
#[derive(Clone, Copy, Debug)]
pub struct EntryMetaOwned {
pub present: MetaMask,
pub depth: u32,
pub entry_type: EntryType,
pub is_reparse: bool,
pub reparse_tag: u32,
pub attributes: u32,
pub size: u64,
pub btime: i64,
pub mtime: i64,
pub atime: i64,
pub ctime: i64,
}
impl EntryMetaOwned {
pub fn from_meta(meta: &EntryMeta, present: MetaMask) -> Self {
Self {
present,
depth: meta.depth,
entry_type: meta.entry_type,
is_reparse: meta.is_reparse,
reparse_tag: meta.reparse_tag,
attributes: meta.attributes,
size: meta.size,
btime: meta.btime,
mtime: meta.mtime,
atime: meta.atime,
ctime: meta.ctime,
}
}
pub fn borrow<'a>(&self, name: &'a [CodePoint]) -> EntryMeta<'a> {
EntryMeta {
name,
depth: self.depth,
entry_type: self.entry_type,
is_reparse: self.is_reparse,
reparse_tag: self.reparse_tag,
attributes: self.attributes,
size: self.size,
btime: self.btime,
mtime: self.mtime,
atime: self.atime,
ctime: self.ctime,
}
}
}
#[derive(Clone, Debug)]
pub struct ContainerEnter {
pub id: ContainerId,
pub parent: Option<ContainerId>,
pub name: ContainerName,
}
#[derive(Clone, Copy, Debug)]
pub struct ContainerEnd {
pub id: ContainerId,
}
#[derive(Clone, Debug)]
pub struct Match {
pub container: ContainerId,
pub name: Name,
pub matched: PatternMask,
pub meta: EntryMetaOwned,
}
#[derive(Debug)]
pub struct CqError {
pub container: Option<ContainerId>,
pub root: Option<u32>,
pub error: EntryError,
}
#[derive(Clone, Debug)]
pub struct DecisionRequest {
pub token: DecisionToken,
pub container: ContainerId,
pub name: Name,
pub meta: EntryMetaOwned,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TerminalReason {
Completed,
Cancelled,
Failed,
}
#[derive(Clone, Copy, Debug)]
pub struct Terminal {
pub reason: TerminalReason,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum CqItem {
ContainerEnter(ContainerEnter),
Match(Match),
ContainerEnd(ContainerEnd),
Error(CqError),
DecisionRequest(DecisionRequest),
Blocked(Blocked),
Terminal(Terminal),
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Blocked {
pub container: ContainerId,
pub name: Name,
pub reason: BlockReason,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlockReason {
RootEscape,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decision {
Accept,
Reject,
}
#[derive(Debug)]
pub enum SqOp {
Cancel,
DecisionAnswer {
token: DecisionToken,
decision: Decision,
},
}
#[derive(Debug)]
pub struct CompletionRing {
queue: ArrayQueue<CqItem>,
nonempty: Signal,
space: Signal,
}
impl CompletionRing {
pub fn with_capacity(capacity: usize) -> Self {
assert!(capacity > 0, "ring capacity must be non-zero");
Self {
queue: ArrayQueue::new(capacity),
nonempty: Signal::new(),
space: Signal::new(),
}
}
pub fn capacity(&self) -> usize {
self.queue.capacity()
}
pub fn len(&self) -> usize {
self.queue.len()
}
pub fn is_empty(&self) -> bool {
self.queue.is_empty()
}
pub fn is_full(&self) -> bool {
self.queue.is_full()
}
pub fn try_push(&self, item: CqItem) -> Result<(), CqItem> {
match self.queue.push(item) {
Ok(()) => {
self.nonempty.notify();
Ok(())
}
Err(item) => Err(item),
}
}
pub fn push_blocking(&self, item: CqItem) {
let mut item = item;
loop {
match self.try_push(item) {
Ok(()) => return,
Err(back) => {
item = back;
self.space.wait();
}
}
}
}
pub fn wait_space_timeout(&self, timeout: std::time::Duration) -> bool {
self.space.wait_timeout(timeout)
}
pub fn wake_producers(&self) {
self.space.notify();
}
pub fn pop(&self) -> Option<CqItem> {
let item = self.queue.pop();
if item.is_some() {
self.space.notify();
if !self.queue.is_empty() {
self.nonempty.notify();
}
}
item
}
pub fn drain(&self) -> Vec<CqItem> {
let mut out = Vec::new();
while let Some(item) = self.pop() {
out.push(item);
}
out
}
pub fn wait_pop(&self) -> CqItem {
loop {
if let Some(item) = self.pop() {
return item;
}
self.nonempty.wait();
}
}
pub fn wait_nonempty(&self) {
while self.queue.is_empty() {
self.nonempty.wait();
}
self.nonempty.notify();
}
}
#[derive(Debug, Default)]
pub struct SubmissionQueue {
inner: Mutex<VecDeque<SqOp>>,
signal: Signal,
}
impl SubmissionQueue {
pub fn new() -> Self {
Self::default()
}
pub fn submit(&self, op: SqOp) {
self.inner.lock().unwrap().push_back(op);
self.signal.notify();
}
pub fn try_next(&self) -> Option<SqOp> {
self.inner.lock().unwrap().pop_front()
}
pub fn drain(&self) -> Vec<SqOp> {
self.inner.lock().unwrap().drain(..).collect()
}
pub fn wait(&self) {
while self.inner.lock().unwrap().is_empty() {
self.signal.wait();
}
}
pub fn wait_timeout(&self, timeout: std::time::Duration) -> bool {
if !self.inner.lock().unwrap().is_empty() {
return true;
}
self.signal.wait_timeout(timeout)
}
pub fn is_empty(&self) -> bool {
self.inner.lock().unwrap().is_empty()
}
}