use std::fs::File;
use std::io::Result;
pub trait FileSync {
fn fsync(&mut self) -> Result<()>;
}
impl FileSync for File {
fn fsync(&mut self) -> Result<()> {
self.sync_all()
}
}
pub trait FileSetLen {
fn set_len(&self, len: u64) -> Result<()>;
}
impl FileSetLen for File {
fn set_len(&self, len: u64) -> Result<()> {
File::set_len(self, len)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::OpenOptions;
use std::io::{Seek, SeekFrom, Write};
use std::path::PathBuf;
use crate::tempdir::TempDir;
#[test]
fn test_fsync() {
let tempdir = TempDir::new_with_prefix("/tmp/fsync_test").unwrap();
let mut path = PathBuf::from(tempdir.as_path());
path.push("file");
let mut f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
f.write_all(b"Hello, world!").unwrap();
f.fsync().unwrap();
assert_eq!(f.metadata().unwrap().len(), 13);
}
#[test]
fn test_set_len() {
let tempdir = TempDir::new_with_prefix("/tmp/set_len_test").unwrap();
let mut path = PathBuf::from(tempdir.as_path());
path.push("file");
let mut f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
f.set_len(10).unwrap();
assert_eq!(f.seek(SeekFrom::End(0)).unwrap(), 10);
}
}