use std::cmp::Ordering;
use win_text_sys::{Case, CompareStringOrdinalError, compare_string_ordinal};
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 {
let case = if case_sensitive {
Case::Sensitive
} else {
Case::Insensitive
};
equal_from(compare_string_ordinal(a, b, case), a, b)
}
fn equal_from(result: Result<Ordering, CompareStringOrdinalError>, a: &[u16], b: &[u16]) -> bool {
match result {
Ok(ordering) => ordering == Ordering::Equal,
Err(CompareStringOrdinalError::TooLong { .. }) => a == b,
Err(CompareStringOrdinalError::Call(_)) => false,
}
}
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;