Skip to content

Commit

Permalink
Return error on empty name
Browse files Browse the repository at this point in the history
  • Loading branch information
oblique committed Sep 17, 2022
1 parent 9def982 commit 3d2ac05
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ pub enum Error {
#[error("Invalid character in name")]
InvalidCharacter,

#[error("Name must not be empty")]
EmptyName,

#[error("Failed to create named lock: {0}")]
CreateFailed(#[source] std::io::Error),

Expand Down
32 changes: 30 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,19 @@ impl NamedLock {
///
/// This will create/open a [global] mutex with [`CreateMutexW`].
///
/// # Notes
///
/// * `name` must not be empty, otherwise an error is returned.
/// * `name` must not contain `\0`, `/`, nor `\`, otherwise an error is returned.
///
/// [`flock`]: https://linux.die.net/man/2/flock
/// [global]: https://docs.microsoft.com/en-us/windows/win32/termserv/kernel-object-namespaces
/// [`CreateMutexW`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexw
pub fn create(name: &str) -> Result<NamedLock> {
if name.is_empty() {
return Err(Error::EmptyName);
}

// On UNIX we want to restrict the user on `/tmp` directory,
// so we block the `/` character.
//
Expand Down Expand Up @@ -112,8 +120,8 @@ impl NamedLock {
///
/// # Notes
///
/// * This function does not append `.lock` on the path
/// * Parent directories must exist
/// * This function does not append `.lock` on the path.
/// * Parent directories must exist.
#[cfg(unix)]
#[cfg_attr(docsrs, doc(cfg(unix)))]
pub fn with_path<P>(path: P) -> Result<NamedLock>
Expand Down Expand Up @@ -263,4 +271,24 @@ mod tests {

Ok(())
}

#[test]
fn invalid_names() {
assert!(matches!(NamedLock::create(""), Err(Error::EmptyName)));

assert!(matches!(
NamedLock::create("abc/"),
Err(Error::InvalidCharacter)
));

assert!(matches!(
NamedLock::create("abc\\"),
Err(Error::InvalidCharacter)
));

assert!(matches!(
NamedLock::create("abc\0"),
Err(Error::InvalidCharacter)
));
}
}

0 comments on commit 3d2ac05

Please sign in to comment.