use wtf_string::Wtf16String;
use crate::notify::Change;
use crate::queue::{Sender, StandingSlot, WatchId};
use crate::watch::{RetryMode, VolumeChangePolicy};
const SEPARATOR: u16 = b'\\' as u16;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RouteScope {
Directory {
subtree: bool,
},
File {
leaf: Wtf16String,
},
}
impl RouteScope {
pub(crate) fn needs_kernel_subtree(&self) -> bool {
matches!(self, RouteScope::Directory { subtree: true })
}
fn matches(&self, name: &[u16], case_sensitive: bool) -> bool {
match self {
RouteScope::Directory { subtree: true } => true,
RouteScope::Directory { subtree: false } => is_direct_child(name),
RouteScope::File { leaf } => {
is_direct_child(name) && names_match(name, leaf.as_units(), case_sensitive)
}
}
}
}
fn is_direct_child(name: &[u16]) -> bool {
!name.contains(&SEPARATOR)
}
fn names_match(a: &[u16], b: &[u16], case_sensitive: bool) -> bool {
use windows_sys::Win32::Foundation::{FALSE, TRUE};
use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
let a_len = i32::try_from(a.len()).unwrap_or(i32::MAX);
let b_len = i32::try_from(b.len()).unwrap_or(i32::MAX);
let ignore_case = if case_sensitive { FALSE } else { TRUE };
let result = unsafe { CompareStringOrdinal(a.as_ptr(), a_len, b.as_ptr(), b_len, ignore_case) };
result == CSTR_EQUAL
}
pub(crate) struct Route {
pub(crate) watch: WatchId,
pub(crate) scope: RouteScope,
pub(crate) sink: Sender,
pub(crate) retry: RetryMode,
pub(crate) report_liveness: bool,
pub(crate) on_volume_change: VolumeChangePolicy,
pub(crate) fault_slot: Option<StandingSlot>,
}
impl Route {
pub(crate) fn select(&self, changes: &[Change], case_sensitive: bool) -> Vec<Change> {
changes
.iter()
.filter(|change| self.scope.matches(change.name.as_wide(), case_sensitive))
.cloned()
.collect()
}
}
impl std::fmt::Debug for Route {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Route")
.field("watch", &self.watch)
.field("scope", &self.scope)
.field("retry", &self.retry)
.field("report_liveness", &self.report_liveness)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests;