2020-06-10 19:08:42 +05:30
|
|
|
use nix::sys::stat;
|
|
|
|
use nix::sys::stat::{FileStat, SFlag};
|
|
|
|
use std::io;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::os::unix::io::AsRawFd;
|
|
|
|
|
|
|
|
//---------------------------------------
|
|
|
|
|
|
|
|
fn check_bits(mode: u32, flag: &SFlag) -> bool {
|
|
|
|
(mode & flag.bits()) != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn is_file_or_blk(info: FileStat) -> bool {
|
|
|
|
check_bits(info.st_mode, &stat::SFlag::S_IFBLK) ||
|
|
|
|
check_bits(info.st_mode, &stat::SFlag::S_IFREG)
|
|
|
|
}
|
2020-06-09 19:29:13 +05:30
|
|
|
|
|
|
|
pub fn file_exists(path: &str) -> bool {
|
2020-06-10 19:08:42 +05:30
|
|
|
match stat::stat(path) {
|
|
|
|
Ok(info) => {
|
2020-06-10 21:16:38 +05:30
|
|
|
is_file_or_blk(info)
|
2020-06-10 19:08:42 +05:30
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
// FIXME: assuming all errors indicate the file doesn't
|
|
|
|
// exist.
|
2020-06-10 21:16:38 +05:30
|
|
|
false
|
2020-06-10 19:08:42 +05:30
|
|
|
}
|
2020-06-09 19:29:13 +05:30
|
|
|
}
|
|
|
|
}
|
2020-06-10 19:08:42 +05:30
|
|
|
|
|
|
|
//---------------------------------------
|
|
|
|
|
|
|
|
const BLKGETSIZE64_CODE: u8 = 0x12;
|
|
|
|
const BLKGETSIZE64_SEQ: u8 = 114;
|
|
|
|
ioctl_read!(ioctl_blkgetsize64, BLKGETSIZE64_CODE, BLKGETSIZE64_SEQ, u64);
|
|
|
|
|
|
|
|
pub fn fail<T>(msg: &str) -> io::Result<T> {
|
|
|
|
let e = io::Error::new(io::ErrorKind::Other, msg);
|
|
|
|
Err(e)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_device_size(path: &str) -> io::Result<u64> {
|
2020-06-10 19:37:40 +05:30
|
|
|
let file = File::open(path)?;
|
|
|
|
let fd = file.as_raw_fd();
|
2020-06-10 19:08:42 +05:30
|
|
|
let mut cap = 0u64;
|
|
|
|
unsafe {
|
|
|
|
match ioctl_blkgetsize64(fd, &mut cap) {
|
2020-06-10 21:16:38 +05:30
|
|
|
Ok(_) => {Ok(cap)}
|
|
|
|
_ => {fail("BLKGETSIZE64 ioctl failed")}
|
2020-06-10 19:08:42 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn file_size(path: &str) -> io::Result<u64> {
|
|
|
|
match stat::stat(path) {
|
|
|
|
Ok(info) => {
|
|
|
|
if check_bits(info.st_mode, &SFlag::S_IFREG) {
|
2020-06-10 21:16:38 +05:30
|
|
|
Ok(info.st_size as u64)
|
2020-06-10 19:08:42 +05:30
|
|
|
} else if check_bits(info.st_mode, &SFlag::S_IFBLK) {
|
2020-06-10 21:16:38 +05:30
|
|
|
get_device_size(path)
|
2020-06-10 19:08:42 +05:30
|
|
|
} else {
|
2020-06-10 21:16:38 +05:30
|
|
|
fail("not a regular file or block device")
|
2020-06-10 19:08:42 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {
|
2020-06-10 21:16:38 +05:30
|
|
|
fail("stat failed")
|
2020-06-10 19:08:42 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//---------------------------------------
|