unix_named_pipe/
ext.rs

1//! Provides an extension to `std::fs::File` which implements useful
2//! utilities for working with FIFOs.
3
4use std::fs;
5use std::io;
6use std::os::unix::fs::FileTypeExt;
7
8/// Definitions for `std::fs::File` extensions for FIFOs
9pub trait FileFIFOExt {
10    fn is_fifo(&self) -> io::Result<bool>;
11}
12
13impl FileFIFOExt for fs::File {
14    /// Returns a wrapped boolean to designate if the underlying
15    /// file is a FIFO device.
16    /// 
17    /// # Examples
18    /// 
19    /// ```
20    /// # extern crate unix_named_pipe;
21    /// # use std::fs;
22    /// use unix_named_pipe::*;
23    /// 
24    /// # let file_name = "/tmp/fifo.5";
25    /// # create(file_name, None).expect("could not create fifo");
26    /// let file = open_read(file_name).expect("could not open fifo for reading");
27    /// assert_eq!(file.is_fifo().unwrap(), true);
28    /// # fs::remove_file(file_name).expect("could not remove fifo");
29    /// ```
30    fn is_fifo(&self) -> io::Result<bool> {
31        let metadata = self.metadata()?;
32        Ok(metadata.file_type().is_fifo())
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::super::{create, open_read};
39    use super::*;
40    use std::fs;
41
42    #[test]
43    fn is_fifo() {
44        let file_name = "/tmp/a-fifo";
45        create(file_name, None).expect("could not create fifo");
46
47        let file = open_read(file_name).expect("could not open fifo for reading");
48        assert_eq!(file.is_fifo().unwrap(), true);
49
50        fs::remove_file(file_name).expect("could not remove fifo");
51    }
52
53    #[test]
54    fn is_not_fifo() {
55        let file_name = "/tmp/file.txt";
56        fs::write(file_name, b"\n").expect("could not write data to file");
57
58        let file = open_read(file_name).expect("could not open file for reading");
59        assert_eq!(file.is_fifo().unwrap(), false);
60
61        fs::remove_file(file_name).expect("could not remove file");
62    }
63
64}