1use std::{ffi::CStr, mem, num::NonZero, os::fd};
2
3use dope_sys::{Errno, kernel};
4
5use super::{Event, Watch};
6
7pub(super) fn create(path: &CStr) -> Result<fd::OwnedFd, Errno> {
8 use fd::AsRawFd as _;
9
10 let file = unsafe {
12 <fd::OwnedFd as dope_sys::io::fd::raw::Adopt>::try_adopt::<crate::Uring, Errno>(
13 libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC),
14 )
15 }?;
16 let raw = unsafe {
18 libc::inotify_add_watch(
19 file.as_raw_fd(),
20 path.as_ptr(),
21 libc::IN_MOVED_TO
22 | libc::IN_MOVE_SELF
23 | libc::IN_DELETE_SELF
24 | libc::IN_ONLYDIR
25 | libc::IN_DONT_FOLLOW,
26 )
27 };
28 unsafe { kernel::raw::Status::new(raw).try_value::<crate::Uring, Errno>() }?;
30 Ok(file)
31}
32
33pub struct Events<'a>(&'a [u8]);
34
35pub unsafe fn events<'a>(_: &Watch, bytes: &'a [u8]) -> Events<'a> {
38 Events(bytes)
39}
40
41impl<'a> Iterator for Events<'a> {
42 type Item = Event<'a>;
43
44 fn next(&mut self) -> Option<Self::Item> {
45 if self.0.is_empty() {
46 return None;
47 }
48 const HEADER: usize = mem::size_of::<libc::inotify_event>();
49 let event = unsafe {
51 self.0
52 .as_ptr()
53 .cast::<libc::inotify_event>()
54 .read_unaligned()
55 };
56 let (record, rest) = unsafe { self.0.split_at_unchecked(HEADER + event.len as usize) };
58 self.0 = rest;
59 Some(match event.mask & !libc::IN_ISDIR {
60 libc::IN_MOVED_TO => Event::MovedIn(&record[HEADER..]),
61 libc::IN_Q_OVERFLOW => Event::Overflow,
62 _ => Event::Invalidated(unsafe { NonZero::new_unchecked(event.mask) }),
64 })
65 }
66}