Skip to content

Commit

Permalink
Merge pull request #222 from allan2/main
Browse files Browse the repository at this point in the history
Update CI, add cargo fmt
  • Loading branch information
hannobraun committed Sep 17, 2024
2 parents f2cc1ab + 9807cf0 commit c4131fd
Show file tree
Hide file tree
Showing 10 changed files with 164 additions and 313 deletions.
54 changes: 30 additions & 24 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
@@ -1,40 +1,46 @@
name: Rust

env:
MSRV: "1.70"

on: [push, pull_request]

jobs:
build:

check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@beta
with:
components: clippy, rustfmt
- uses: Swatinem/rust-cache@v2
- name: cargo fmt
run: cargo fmt --all --check
- name: clippy
run: cargo clippy --all-targets --all-features -- -D warnings

build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: 1.70.0
override: true
components: clippy
- name: Check rust and cargo version
run: rustc -V && cargo -V
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
- name: Run Clippy lints
run: cargo clippy --verbose -- -D warnings
- name: Build (no default features)
run: cargo build --verbose --no-default-features
- name: Run tests (no default features)
run: cargo test --verbose --no-default-features
- name: Run Clippy lints (no default features)
run: cargo clippy --verbose --no-default-features -- -D warnings
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Check rustc and cargo version
run: rustc -V && cargo -V
- name: Build
run: cargo build --all-features --all-targets --verbose
- name: Run tests
run: cargo test --all-features --all-targets --verbose
- name: Build (no default features)
run: cargo build --no-default-features --all-targets --verbose
- name: Run tests (no default features)
run: cargo test --no-default-features --all-targets --verbose

miri:
name: "Miri"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Install Miri
run: |
rustup toolchain install nightly --component miri
Expand Down
27 changes: 9 additions & 18 deletions examples/stream.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,22 @@
use std::{
fs::File,
io,
thread,
time::Duration,
};
use std::{fs::File, io, thread, time::Duration};

use futures_util::StreamExt;
use inotify::{
Inotify,
WatchMask,
};
use inotify::{Inotify, WatchMask};
use tempfile::TempDir;

#[tokio::main]
async fn main() -> Result<(), io::Error> {
let inotify = Inotify::init()
.expect("Failed to initialize inotify");
let inotify = Inotify::init().expect("Failed to initialize inotify");

let dir = TempDir::new()?;

inotify.watches().add(dir.path(), WatchMask::CREATE | WatchMask::MODIFY)?;
inotify
.watches()
.add(dir.path(), WatchMask::CREATE | WatchMask::MODIFY)?;

thread::spawn::<_, Result<(), io::Error>>(move || {
loop {
File::create(dir.path().join("file"))?;
thread::sleep(Duration::from_millis(500));
}
thread::spawn::<_, Result<(), io::Error>>(move || loop {
File::create(dir.path().join("file"))?;
thread::sleep(Duration::from_millis(500));
});

let mut buffer = [0; 1024];
Expand Down
13 changes: 3 additions & 10 deletions examples/watch.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
use std::env;

use inotify::{
EventMask,
Inotify,
WatchMask,
};

use inotify::{EventMask, Inotify, WatchMask};

fn main() {
let mut inotify = Inotify::init()
.expect("Failed to initialize inotify");
let mut inotify = Inotify::init().expect("Failed to initialize inotify");

let current_dir = env::current_dir()
.expect("Failed to determine current directory");
let current_dir = env::current_dir().expect("Failed to determine current directory");

inotify
.watches()
Expand Down
86 changes: 21 additions & 65 deletions src/events.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use std::{
ffi::{
OsStr,
OsString,
},
ffi::{OsStr, OsString},
mem,
os::unix::ffi::OsStrExt,
sync::Weak,
Expand All @@ -13,7 +10,6 @@ use inotify_sys as ffi;
use crate::fd_guard::FdGuard;
use crate::watches::WatchDescriptor;


/// Iterator over inotify events
///
/// Allows for iteration over the events returned by
Expand All @@ -23,16 +19,14 @@ use crate::watches::WatchDescriptor;
/// [`Inotify::read_events`]: crate::Inotify::read_events
#[derive(Debug)]
pub struct Events<'a> {
fd : Weak<FdGuard>,
buffer : &'a [u8],
fd: Weak<FdGuard>,
buffer: &'a [u8],
num_bytes: usize,
pos : usize,
pos: usize,
}

impl<'a> Events<'a> {
pub(crate) fn new(fd: Weak<FdGuard>, buffer: &'a [u8], num_bytes: usize)
-> Self
{
pub(crate) fn new(fd: Weak<FdGuard>, buffer: &'a [u8], num_bytes: usize) -> Self {
Events {
fd,
buffer,
Expand All @@ -51,14 +45,12 @@ impl<'a> Iterator for Events<'a> {
self.pos += step;

Some(event)
}
else {
} else {
None
}
}
}


/// An inotify event
///
/// A file system event that describes a change that the user previously
Expand Down Expand Up @@ -105,23 +97,13 @@ pub struct Event<S> {
}

impl<'a> Event<&'a OsStr> {
fn new(fd: Weak<FdGuard>, event: &ffi::inotify_event, name: &'a OsStr)
-> Self
{
fn new(fd: Weak<FdGuard>, event: &ffi::inotify_event, name: &'a OsStr) -> Self {
let mask = EventMask::from_bits(event.mask)
.expect("Failed to convert event mask. This indicates a bug.");

let wd = crate::WatchDescriptor {
id: event.wd,
fd,
};
let wd = crate::WatchDescriptor { id: event.wd, fd };

let name = if name.is_empty() {
None
}
else {
Some(name)
};
let name = if name.is_empty() { None } else { Some(name) };

Event {
wd,
Expand All @@ -141,12 +123,7 @@ impl<'a> Event<&'a OsStr> {
/// # Panics
///
/// Panics if the buffer does not contain a full event, including its name.
pub(crate) fn from_buffer(
fd : Weak<FdGuard>,
buffer: &'a [u8],
)
-> (usize, Self)
{
pub(crate) fn from_buffer(fd: Weak<FdGuard>, buffer: &'a [u8]) -> (usize, Self) {
let event_size = mem::size_of::<ffi::inotify_event>();

// Make sure that the buffer is big enough to contain an event, without
Expand Down Expand Up @@ -184,16 +161,9 @@ impl<'a> Event<&'a OsStr> {
//
// The `unwrap` here is safe, because `splitn` always returns at
// least one result, even if the original slice contains no '\0'.
let name = name
.splitn(2, |b| b == &0u8)
.next()
.unwrap();
let name = name.splitn(2, |b| b == &0u8).next().unwrap();

let event = Event::new(
fd,
&ffi_event,
OsStr::from_bytes(name),
);
let event = Event::new(fd, &ffi_event, OsStr::from_bytes(name));

(bytes_consumed, event)
}
Expand All @@ -217,11 +187,9 @@ impl<'a> Event<&'a OsStr> {
}
}


/// An owned version of `Event`
pub type EventOwned = Event<OsString>;


bitflags! {
/// Indicates the type of an event
///
Expand Down Expand Up @@ -370,50 +338,38 @@ impl EventMask {
}
}


#[cfg(test)]
mod tests {
use std::{
io::prelude::*,
mem,
slice,
sync,
};
use std::{io::prelude::*, mem, slice, sync};

use inotify_sys as ffi;

use super::Event;


#[test]
fn from_buffer_should_not_mistake_next_event_for_name_of_previous_event() {
let mut buffer = [0u8; 1024];

// First, put a normal event into the buffer
let event = ffi::inotify_event {
wd: 0,
mask: 0,
wd: 0,
mask: 0,
cookie: 0,
len: 0, // no name following after event
len: 0, // no name following after event
};
let event = unsafe {
slice::from_raw_parts(
&event as *const _ as *const u8,
mem::size_of_val(&event),
)
slice::from_raw_parts(&event as *const _ as *const u8, mem::size_of_val(&event))
};
(&mut buffer[..]).write(event)
(&mut buffer[..])
.write_all(event)
.expect("Failed to write into buffer");

// After that event, simulate an event that starts with a non-zero byte.
buffer[mem::size_of_val(&event)] = 1;
buffer[mem::size_of_val(event)] = 1;

// Now create the event and verify that the name is actually `None`, as
// dictated by the value `len` above.
let (_, event) = Event::from_buffer(
sync::Weak::new(),
&buffer,
);
let (_, event) = Event::from_buffer(sync::Weak::new(), &buffer);
assert_eq!(event.name, None);
}
}
22 changes: 6 additions & 16 deletions src/fd_guard.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,19 @@
use std::{
ops::Deref,
os::unix::io::{
AsFd,
AsRawFd,
BorrowedFd,
FromRawFd,
IntoRawFd,
RawFd,
},
sync::atomic::{
AtomicBool,
Ordering,
},
os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd},
sync::atomic::{AtomicBool, Ordering},
};

use inotify_sys as ffi;


/// A RAII guard around a `RawFd` that closes it automatically on drop.
#[derive(Debug)]
pub struct FdGuard {
pub(crate) fd : RawFd,
pub(crate) fd: RawFd,
pub(crate) close_on_drop: AtomicBool,
}

impl FdGuard {

/// Indicate that the wrapped file descriptor should _not_ be closed
/// when the guard is dropped.
///
Expand All @@ -52,7 +40,9 @@ impl Deref for FdGuard {
impl Drop for FdGuard {
fn drop(&mut self) {
if self.close_on_drop.load(Ordering::Acquire) {
unsafe { ffi::close(self.fd); }
unsafe {
ffi::close(self.fd);
}
}
}
}
Expand Down
Loading

0 comments on commit c4131fd

Please sign in to comment.