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
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);
}
#[test]
fn test_set_len_fails_when_file_not_opened_for_writing() {
let tempdir = TempDir::new_with_prefix("/tmp/set_len_test").unwrap();
let mut path = PathBuf::from(tempdir.as_path());
path.push("file");
File::create(path.clone()).unwrap();
let f = OpenOptions::new().read(true).open(&path).unwrap();
let result = f.set_len(10);
assert!(result.is_err());
}
}