Skip to content

Commit 3d2ac05

Browse files
committed
Return error on empty name
1 parent 9def982 commit 3d2ac05

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/error.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ pub enum Error {
99
#[error("Invalid character in name")]
1010
InvalidCharacter,
1111

12+
#[error("Name must not be empty")]
13+
EmptyName,
14+
1215
#[error("Failed to create named lock: {0}")]
1316
CreateFailed(#[source] std::io::Error),
1417

src/lib.rs

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,19 @@ impl NamedLock {
7878
///
7979
/// This will create/open a [global] mutex with [`CreateMutexW`].
8080
///
81+
/// # Notes
82+
///
83+
/// * `name` must not be empty, otherwise an error is returned.
84+
/// * `name` must not contain `\0`, `/`, nor `\`, otherwise an error is returned.
8185
///
8286
/// [`flock`]: https://linux.die.net/man/2/flock
8387
/// [global]: https://docs.microsoft.com/en-us/windows/win32/termserv/kernel-object-namespaces
8488
/// [`CreateMutexW`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexw
8589
pub fn create(name: &str) -> Result<NamedLock> {
90+
if name.is_empty() {
91+
return Err(Error::EmptyName);
92+
}
93+
8694
// On UNIX we want to restrict the user on `/tmp` directory,
8795
// so we block the `/` character.
8896
//
@@ -112,8 +120,8 @@ impl NamedLock {
112120
///
113121
/// # Notes
114122
///
115-
/// * This function does not append `.lock` on the path
116-
/// * Parent directories must exist
123+
/// * This function does not append `.lock` on the path.
124+
/// * Parent directories must exist.
117125
#[cfg(unix)]
118126
#[cfg_attr(docsrs, doc(cfg(unix)))]
119127
pub fn with_path<P>(path: P) -> Result<NamedLock>
@@ -263,4 +271,24 @@ mod tests {
263271

264272
Ok(())
265273
}
274+
275+
#[test]
276+
fn invalid_names() {
277+
assert!(matches!(NamedLock::create(""), Err(Error::EmptyName)));
278+
279+
assert!(matches!(
280+
NamedLock::create("abc/"),
281+
Err(Error::InvalidCharacter)
282+
));
283+
284+
assert!(matches!(
285+
NamedLock::create("abc\\"),
286+
Err(Error::InvalidCharacter)
287+
));
288+
289+
assert!(matches!(
290+
NamedLock::create("abc\0"),
291+
Err(Error::InvalidCharacter)
292+
));
293+
}
266294
}

0 commit comments

Comments
 (0)