| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
extern crate libc; |
| 6 |
|
| 7 |
use std::ffi::CString; |
| 8 |
use std::ffi::OsStr; |
| 9 |
use std::hash::{Hash, Hasher}; |
| 10 |
use std::io; |
| 11 |
use std::mem; |
| 12 |
use std::os::raw::c_int; |
| 13 |
use std::os::unix::{ffi::OsStrExt, io::RawFd}; |
| 14 |
|
| 15 |
#[derive(Debug)] |
| 16 |
pub struct Fd { |
| 17 |
pub fileno: RawFd, |
| 18 |
} |
| 19 |
|
| 20 |
impl Fd { |
| 21 |
pub fn open(path: &OsStr, flags: c_int) -> io::Result<Fd> { |
| 22 |
let cpath = CString::new(path.as_bytes())?; |
| 23 |
let rv = unsafe { libc::open(cpath.as_ptr(), flags) }; |
| 24 |
if rv == -1 { |
| 25 |
return Err(io::Error::last_os_error()); |
| 26 |
} |
| 27 |
Ok(Fd { fileno: rv }) |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
impl Drop for Fd { |
| 32 |
fn drop(&mut self) { |
| 33 |
unsafe { libc::close(self.fileno) }; |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
impl PartialEq for Fd { |
| 38 |
fn eq(&self, other: &Fd) -> bool { |
| 39 |
let mut st: libc::stat = unsafe { mem::zeroed() }; |
| 40 |
let mut sto: libc::stat = unsafe { mem::zeroed() }; |
| 41 |
if unsafe { libc::fstat(self.fileno, &mut st) } == -1 { |
| 42 |
return false; |
| 43 |
} |
| 44 |
if unsafe { libc::fstat(other.fileno, &mut sto) } == -1 { |
| 45 |
return false; |
| 46 |
} |
| 47 |
(st.st_dev == sto.st_dev) & (st.st_ino == sto.st_ino) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
impl Eq for Fd {} |
| 52 |
|
| 53 |
impl Hash for Fd { |
| 54 |
fn hash<H: Hasher>(&self, state: &mut H) { |
| 55 |
let mut st: libc::stat = unsafe { mem::zeroed() }; |
| 56 |
if unsafe { libc::fstat(self.fileno, &mut st) } == -1 { |
| 57 |
return; |
| 58 |
} |
| 59 |
st.st_dev.hash(state); |
| 60 |
st.st_ino.hash(state); |
| 61 |
} |
| 62 |
} |