rustvil 0.9.0

Rustvil, a collection of various Rust utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
#[cfg(any(feature = "full-resolve", feature = "expand-user"))]
use std::path::PathBuf;

use std::{
    fs::{
        File, OpenOptions, Permissions, copy, create_dir, create_dir_all, hard_link, read,
        read_to_string, remove_dir, remove_dir_all, remove_file, rename, set_permissions, write,
    },
    io::{self},
    ops::{Deref, DerefMut},
    path::Path,
};

/// A RAII guard, which calls [`(*self).unlock()`](std::fs::File::unlock) on a drop.
#[derive(Debug)]
pub struct FileLockGuard {
    file: File,
}

impl Drop for FileLockGuard {
    fn drop(&mut self) {
        drop(self.file.unlock())
    }
}

impl Deref for FileLockGuard {
    type Target = File;

    fn deref(&self) -> &Self::Target {
        &self.file
    }
}

impl DerefMut for FileLockGuard {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.file
    }
}

/// Options for controlling the [`PathExt::mkdir`]
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub enum MkdirOptions {
    /// Equivalent of the `mkdir $path`.
    WithoutParents,
    /// Equivalent of the `mkdir -p $path`.
    WithParents,
}

mod sealed {
    use std::path::Path;

    pub trait Sealed {}
    impl Sealed for Path {}
}

/// Whether the [`PathExt::lock`]/[`PathExt::lock_shared`] should block the current thread.
#[derive(Debug, Hash, Clone, Copy, PartialEq, Eq)]
pub enum ShouldBlock {
    No,
    Yes,
}

/// Extension trait for the [`Path`] with additional filesystem operations.
///
/// Most of it are [`std::fs`] wrappers, changing from a functional to an OOP style, but there are some
/// interesting methods.
///
/// ```rust,no_run
/// # use rustvil::fs::*;
/// # use std::path::Path;
/// # fn get_path() -> ! { loop {} }
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let path: &Path = get_path();
/// // Now you can do extra things like:
/// let _file = path.touch()?; // Creates a file and its parent directories.
/// path.rm()?;
/// path.mkdir(MkdirOptions::WithParents)?;
///
/// // You can also lock the file, to prevent any races (even across different processes)
/// let _guard = path.lock(ShouldBlock::Yes)?;
/// // ...
/// drop(_guard);
/// // Cleanup created files.
/// path.rmtree()?;
/// # Ok(())
/// # }
pub trait PathExt: sealed::Sealed {
    /// Touch the file and its parent directories.
    ///
    /// # Returns
    /// [`Ok(File)`](std::fs::File) if created successfully, otherwise an error, as reported by
    /// the [`PathExt::mkdir`] or the [`OpenOptions::open`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use rustvil::fs::PathExt;
    /// # use std::path::PathBuf;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let buf = PathBuf::from("file.txt");
    /// let path = buf.as_path();
    /// let file = path.touch()?;
    /// # Ok(())
    /// # }
    /// ```
    fn touch(&self) -> io::Result<File>;

    /// Create directories at given [`Path`].
    ///
    /// # Returns
    /// [`Ok(())`](Ok) if created successfully, otherwise an error, as reported by
    /// the [`create_dir`], or the [`create_dir_all`].
    ///
    /// Note that this function will return `Ok(())`, if [`create_dir`] returns `Err` with kind
    /// [`ErrorKind::AlreadyExists`](io::ErrorKind::AlreadyExists).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use rustvil::fs::*;
    /// # use std::path::PathBuf;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let buf = PathBuf::from("a/b");
    /// let path = buf.as_path();
    /// path.mkdir(MkdirOptions::WithParents)?;
    /// # Ok(())
    /// # }
    /// ```
    fn mkdir(&self, opts: MkdirOptions) -> io::Result<()>;

    /// Locks exclusively `self`, creating a file if needed.
    ///
    /// This is essentially [`self.touch()?`](PathExt::touch) followed by [`File::lock`]/[`File::try_lock`], with RAII bloat.
    ///
    /// # Returns
    /// [`Ok(FileLockGuard)`](FileLockGuard) on a success.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use rustvil::fs::*;
    /// # use std::path::PathBuf;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let buf = PathBuf::from("lockfile.lock");
    /// let path = buf.as_path();
    ///
    /// let lock = path.lock(ShouldBlock::Yes)?;
    /// // Critical section...
    /// drop(lock);
    ///
    /// let lock = path.lock(ShouldBlock::No)?;
    /// drop(lock);
    /// # Ok(())
    /// # }
    /// ```
    fn lock(&self, should_block: ShouldBlock) -> io::Result<FileLockGuard>;

    /// Locks shared `self`, creating a file if needed.
    ///
    /// This is essentially [`self.touch()?`](PathExt::touch) followed by [`File::lock_shared`]/[`File::try_lock_shared`], with RAII bloat.
    ///
    /// # Returns
    /// [`Ok(FileLockGuard)`](FileLockGuard) on a success.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use rustvil::fs::*;
    /// # use std::path::PathBuf;
    /// # use std::path::Path;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let buf = PathBuf::from("lockfile.lock");
    /// let path = buf.as_path();
    ///
    /// let lock1 = path.lock_shared(ShouldBlock::Yes)?;
    /// let lock2 = path.lock_shared(ShouldBlock::No)?;
    /// drop(lock1);
    /// drop(lock2);
    /// # Ok(())
    /// # }
    /// ```
    fn lock_shared(&self, should_block: ShouldBlock) -> io::Result<FileLockGuard>;

    /// Resolve `self` fully, as best as possible.
    ///
    /// Unlike [`std::fs::canonicalize`], this function __doesn't__ fail, if `self` points to a
    /// non-existing file.
    ///
    /// This function requires the __full-resolve__ feature.
    #[cfg(feature = "full-resolve")]
    #[cfg_attr(docsrs, doc(cfg(feature = "full-resolve")))]
    fn resolve(&self) -> io::Result<PathBuf>;

    /// Canonicalize `self` fully: expand `~` into the `$HOME`.
    ///
    /// Also, because of the current implementation, this function will fail, if `self` is not a
    /// `UTF-8` path.
    ///
    /// This function requires the __expand-user__ feature.
    #[cfg(feature = "expand-user")]
    #[cfg_attr(docsrs, doc(cfg(feature = "expand-user")))]
    fn expand_user(&self) -> io::Result<PathBuf>;

    /// Canonicalize `self` fully: expand `~` into a `home`.
    ///
    /// Also, because of the current implementation, this function will fail, if `self` is not a
    /// `UTF-8` path.
    ///
    /// This function requires the __expand-user__ feature.
    #[cfg(feature = "expand-user")]
    #[cfg_attr(docsrs, doc(cfg(feature = "expand-user")))]
    fn expand_user_with(&self, home: impl AsRef<str>) -> io::Result<PathBuf>;

    /// Canonicalize `self` fully: expand `~` into a `home()`.
    ///
    /// Also, because of the current implementation, this function will fail, if `self` is not a
    /// `UTF-8` path.
    ///
    /// This function requires the __expand-user__ feature.
    #[cfg(feature = "expand-user")]
    #[cfg_attr(docsrs, doc(cfg(feature = "expand-user")))]
    fn expand_user_with_fn<F, H>(&self, home: F) -> io::Result<PathBuf>
    where
        H: AsRef<str>,
        F: FnOnce() -> H;

    /// Returns `true` if path exists on a disk and points to an executable file.
    ///
    /// Current implementation only considers `unix` and `windows` cfg's, any other always returns
    /// `false`.
    fn is_executable(&self) -> bool;

    /// A wrapper around [`std::fs::copy`].
    fn copy_to(&self, to: impl AsRef<Path>) -> io::Result<u64>;

    /// A wrapper around [`std::fs::hard_link`].
    fn hard_link_to(&self, to: impl AsRef<Path>) -> io::Result<()>;

    /// A wrapper around [`std::fs::read`].
    fn read(&self) -> io::Result<Vec<u8>>;

    /// A wrapper around [`std::fs::read_to_string`].
    fn read_to_string(&self) -> io::Result<String>;

    /// A wrapper around [`std::fs::rename`].
    fn rename_to(&self, to: impl AsRef<Path>) -> io::Result<()>;

    /// A wrapper around [`std::fs::remove_file`].
    fn rm(&self) -> io::Result<()>;

    /// A wrapper around [`std::fs::remove_dir`].
    fn rmdir(&self) -> io::Result<()>;

    /// A wrapper around [`std::fs::remove_dir_all`].
    fn rmtree(&self) -> io::Result<()>;

    /// A wrapper around [`std::fs::set_permissions`].
    fn set_permissions(&self, permissions: Permissions) -> io::Result<()>;

    /// A wrapper around [`std::fs::write`].
    fn write(&self, contents: impl AsRef<[u8]>) -> io::Result<()>;
}

impl PathExt for Path {
    // FIXME: Take `OpenOptions` as a parameter?
    fn touch(&self) -> io::Result<File> {
        if let Some(parent) = self.parent() {
            parent.mkdir(MkdirOptions::WithParents)?;
        }
        let mut opts = OpenOptions::new();
        opts.read(true).write(true).create(true).truncate(false);
        #[cfg(unix)]
        {
            use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
            if let Ok(metadata) = self.metadata() {
                // RDWR for all.
                const MASK: u32 = 0o666;
                let permissions = metadata.permissions().mode();
                opts.mode(permissions & MASK);
            }
        }
        opts.open(self)
    }

    fn mkdir(&self, opts: MkdirOptions) -> io::Result<()> {
        let result = match opts {
            MkdirOptions::WithoutParents => create_dir(self),
            MkdirOptions::WithParents => create_dir_all(self),
        };
        match result {
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
            _ => result,
        }
    }

    fn lock(&self, should_block: ShouldBlock) -> io::Result<FileLockGuard> {
        let file = self.touch()?;
        let result = if matches!(should_block, ShouldBlock::Yes) {
            file.lock()
        } else {
            file.try_lock().map_err(|err| match err {
                std::fs::TryLockError::Error(error) => error,
                std::fs::TryLockError::WouldBlock => io::Error::from(io::ErrorKind::WouldBlock),
            })
        };
        result.map(|_| FileLockGuard { file })
    }

    fn lock_shared(&self, should_block: ShouldBlock) -> io::Result<FileLockGuard> {
        let file = self.touch()?;
        let result = if matches!(should_block, ShouldBlock::Yes) {
            file.lock_shared()
        } else {
            file.try_lock_shared().map_err(|err| match err {
                std::fs::TryLockError::Error(error) => error,
                std::fs::TryLockError::WouldBlock => io::Error::from(io::ErrorKind::WouldBlock),
            })
        };
        result.map(|_| FileLockGuard { file })
    }

    #[cfg(unix)]
    fn is_executable(&self) -> bool {
        use std::os::unix::prelude::*;
        self.metadata()
            .map(|metadata| {
                // Note: This should be the same as 0o111.
                #[allow(clippy::unnecessary_cast)] // On macOS those are u16, on Linux they are u32.
                const EXEC_MASK: u32 = (libc::S_IXUSR | libc::S_IXGRP | libc::S_IXOTH) as u32;
                const _: () = assert!(EXEC_MASK == 0o111, "bits mismatch");
                metadata.is_file() && metadata.permissions().mode() & EXEC_MASK != 0
            })
            .unwrap_or(false)
    }

    #[cfg(windows)]
    fn is_executable(&self) -> bool {
        self.is_file()
    }

    // TODO: Implement.
    #[cfg(not(any(unix, windows)))]
    fn is_executable(&self) -> bool {
        false
    }

    fn copy_to(&self, to: impl AsRef<Path>) -> io::Result<u64> {
        copy(self, to)
    }

    fn hard_link_to(&self, to: impl AsRef<Path>) -> io::Result<()> {
        hard_link(self, to)
    }

    fn read(&self) -> io::Result<Vec<u8>> {
        read(self)
    }

    fn read_to_string(&self) -> io::Result<String> {
        read_to_string(self)
    }

    fn rename_to(&self, to: impl AsRef<Path>) -> io::Result<()> {
        rename(self, to)
    }

    fn rm(&self) -> io::Result<()> {
        remove_file(self)
    }

    fn rmdir(&self) -> io::Result<()> {
        remove_dir(self)
    }

    fn rmtree(&self) -> io::Result<()> {
        remove_dir_all(self)
    }

    fn set_permissions(&self, permissions: Permissions) -> io::Result<()> {
        set_permissions(self, permissions)
    }

    fn write(&self, contents: impl AsRef<[u8]>) -> io::Result<()> {
        write(self, contents)
    }

    #[cfg(feature = "full-resolve")]
    fn resolve(&self) -> io::Result<PathBuf> {
        use soft_canonicalize::soft_canonicalize;
        soft_canonicalize(self)
    }

    #[cfg(feature = "expand-user")]
    fn expand_user(&self) -> io::Result<PathBuf> {
        use shellexpand::tilde;
        let Some(as_str) = self.to_str() else {
            return Err(io::Error::other("path is not an UTF-8 string"));
        };
        Ok(PathBuf::from(tilde(as_str).into_owned()))
    }

    #[cfg(feature = "expand-user")]
    fn expand_user_with(&self, home: impl AsRef<str>) -> io::Result<PathBuf> {
        self.expand_user_with_fn(|| home)
    }

    #[cfg(feature = "expand-user")]
    fn expand_user_with_fn<F, H>(&self, home: F) -> io::Result<PathBuf>
    where
        H: AsRef<str>,
        F: FnOnce() -> H,
    {
        use shellexpand::tilde_with_context;
        let Some(as_str) = self.to_str() else {
            return Err(io::Error::other("path is not an UTF-8 string"));
        };
        Ok(PathBuf::from(
            tilde_with_context(as_str, || Some(home())).into_owned(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use claim::{assert_err, assert_ok};
    use tempfile::tempdir;

    use std::io::{Read, Write};
    use std::sync::{Arc, Barrier};
    use std::thread;
    use std::time::Duration;
    use tempfile::NamedTempFile;

    #[test]
    fn create_new_file_should_work() {
        let tmp = tempdir().expect("needed for tests");
        let mut new_file = tmp.path().to_path_buf();
        new_file.push("x");
        assert_ok!(new_file.touch());
    }

    #[test]
    fn multiple_touch() {
        let tmp = tempdir().expect("needed for tests");
        let mut new_file = tmp.path().to_path_buf();
        new_file.push("x");
        let mut file = new_file.touch().unwrap();
        file.write_all("test".as_bytes()).unwrap();
        let mut new_handle = new_file.touch().unwrap();
        let mut content = String::new();
        let read_bytes = new_handle.read_to_string(&mut content).unwrap();
        assert_eq!(read_bytes, 4);
        assert_eq!(content, "test");
    }

    #[test]
    fn create_dirs() {
        {
            let tmp = tempdir().expect("needed for tests");
            let mut new_file = tmp.path().to_path_buf();
            new_file.push("x");
            new_file.push("y");
            assert_ok!(new_file.mkdir(MkdirOptions::WithParents));
        }

        {
            let tmp = tempdir().expect("needed for tests");
            let mut new_file = tmp.path().to_path_buf();
            new_file.push("x");
            assert_ok!(new_file.mkdir(MkdirOptions::WithParents));
        }

        {
            let tmp = tempdir().expect("needed for tests");
            let mut new_file = tmp.path().to_path_buf();
            new_file.push("x");
            assert_ok!(new_file.mkdir(MkdirOptions::WithoutParents));
        }

        {
            let tmp = tempdir().expect("needed for tests");
            let mut new_file = tmp.path().to_path_buf();
            new_file.push("x");
            new_file.push("y");
            assert_err!(new_file.mkdir(MkdirOptions::WithoutParents));
        }
    }

    #[test]
    fn mkdir_doesnt_screw_paths() {
        let tmp = tempdir().expect("needed for tests");
        let mut new_file = tmp.path().to_path_buf();
        let mut copy = new_file.clone();
        let mut copy2 = new_file.clone();
        new_file.push("x");
        new_file.push("y");
        assert_ok!(new_file.mkdir(MkdirOptions::WithParents));
        assert_ok!(new_file.mkdir(MkdirOptions::WithoutParents));
        copy.push("x");
        copy.push("file");
        copy2.push("x");
        assert_ok!(copy.touch());
        assert_ok!(copy2.mkdir(MkdirOptions::WithParents));
        assert_ok!(copy2.mkdir(MkdirOptions::WithoutParents));
        assert!(copy.exists());
        assert!(copy2.exists());
        assert!(new_file.exists());
    }

    #[test]
    fn lock_blocking_should_work() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let lock = assert_ok!(path.lock(ShouldBlock::Yes));
        drop(lock);
    }

    #[test]
    fn lock_non_blocking_should_work() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let lock = assert_ok!(path.lock(ShouldBlock::No));
        drop(lock);
    }

    #[test]
    fn lock_shared_blocking_should_work() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let lock = assert_ok!(path.lock_shared(ShouldBlock::Yes));
        drop(lock);
    }

    #[test]
    fn lock_shared_non_blocking_should_work() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let lock = assert_ok!(path.lock_shared(ShouldBlock::No));
        drop(lock);
    }

    #[test]
    fn multiple_shared_locks_can_coexist() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let lock1 = assert_ok!(path.lock_shared(ShouldBlock::Yes));
        let lock2 = assert_ok!(path.lock_shared(ShouldBlock::No));
        let lock3 = assert_ok!(path.lock_shared(ShouldBlock::No));

        drop(lock1);
        drop(lock2);
        drop(lock3);
    }

    #[test]
    fn exclusive_lock_prevents_another_exclusive_lock() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let _lock1 = assert_ok!(path.lock(ShouldBlock::Yes));
        let result = path.lock(ShouldBlock::No);

        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);
    }

    #[test]
    fn exclusive_lock_prevents_shared_lock() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let _lock1 = assert_ok!(path.lock(ShouldBlock::Yes));
        let result = path.lock_shared(ShouldBlock::No);

        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);
    }

    #[test]
    fn shared_lock_prevents_exclusive_lock() {
        use tempfile::NamedTempFile;
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let path = lockfile.path();

        let _lock1 = assert_ok!(path.lock_shared(ShouldBlock::Yes));
        let result = path.lock(ShouldBlock::No);

        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);
    }

    #[test]
    fn multithreaded_exclusive_locks_are_mutually_exclusive() {
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let lockpath = Arc::new(lockfile.path().to_path_buf());
        let barrier = Arc::new(Barrier::new(2));

        let lockpath_clone = Arc::clone(&lockpath);
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            let lock = assert_ok!(lockpath_clone.as_path().lock(ShouldBlock::Yes));
            barrier_clone.wait();
            thread::sleep(Duration::from_millis(100));
            drop(lock);
        });

        barrier.wait();
        thread::sleep(Duration::from_millis(10));

        let result = lockpath.as_path().lock(ShouldBlock::No);
        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);

        handle.join().expect("thread should not panic");

        assert_ok!(lockpath.as_path().lock(ShouldBlock::No));
    }

    #[test]
    fn multithreaded_shared_locks_can_coexist() {
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let lockpath = Arc::new(lockfile.path().to_path_buf());
        let barrier = Arc::new(Barrier::new(3));

        let mut handles = vec![];

        for _ in 0..2 {
            let lockpath_clone = Arc::clone(&lockpath);
            let barrier_clone = Arc::clone(&barrier);

            let handle = thread::spawn(move || {
                let _lock = assert_ok!(lockpath_clone.as_path().lock_shared(ShouldBlock::Yes));
                barrier_clone.wait();
            });

            handles.push(handle);
        }

        let _lock = assert_ok!(lockpath.as_path().lock_shared(ShouldBlock::Yes));
        barrier.wait();

        for handle in handles {
            handle.join().expect("thread should not panic");
        }
    }

    #[test]
    fn multithreaded_exclusive_lock_blocks_shared_locks() {
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let lockpath = Arc::new(lockfile.path().to_path_buf());
        let barrier = Arc::new(Barrier::new(2));

        let lockpath_clone = Arc::clone(&lockpath);
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            let lock = assert_ok!(lockpath_clone.as_path().lock(ShouldBlock::Yes));
            barrier_clone.wait();
            thread::sleep(Duration::from_millis(100));
            drop(lock);
        });

        barrier.wait();
        thread::sleep(Duration::from_millis(10));

        let result = lockpath.as_path().lock_shared(ShouldBlock::No);
        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);

        handle.join().expect("thread should not panic");

        assert_ok!(lockpath.as_path().lock_shared(ShouldBlock::No));
    }

    #[test]
    fn multithreaded_shared_lock_blocks_exclusive_lock() {
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let lockpath = Arc::new(lockfile.path().to_path_buf());
        let barrier = Arc::new(Barrier::new(2));

        let lockpath_clone = Arc::clone(&lockpath);
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            let lock = assert_ok!(lockpath_clone.as_path().lock_shared(ShouldBlock::Yes));
            barrier_clone.wait();
            thread::sleep(Duration::from_millis(100));
            drop(lock);
        });

        barrier.wait();
        thread::sleep(Duration::from_millis(10));

        let result = lockpath.as_path().lock(ShouldBlock::No);
        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);

        handle.join().expect("thread should not panic");

        assert_ok!(lockpath.as_path().lock(ShouldBlock::No));
    }

    #[test]
    fn multithreaded_multiple_shared_then_exclusive() {
        let lockfile = NamedTempFile::new().expect("needed for tests");
        let lockpath = Arc::new(lockfile.path().to_path_buf());
        let barrier = Arc::new(Barrier::new(4));

        let mut handles = vec![];

        for _ in 0..3 {
            let lockpath_clone = Arc::clone(&lockpath);
            let barrier_clone = Arc::clone(&barrier);

            let handle = thread::spawn(move || {
                let lock = assert_ok!(lockpath_clone.as_path().lock_shared(ShouldBlock::Yes));
                barrier_clone.wait();
                thread::sleep(Duration::from_millis(50));
                drop(lock);
            });

            handles.push(handle);
        }

        barrier.wait();
        thread::sleep(Duration::from_millis(10));

        let result = lockpath.as_path().lock(ShouldBlock::No);
        assert_err!(&result);
        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::WouldBlock);

        for handle in handles {
            handle.join().expect("thread should not panic");
        }

        assert_ok!(lockpath.as_path().lock(ShouldBlock::Yes));
    }
}