Skip to content

Commit b7f8f93

Browse files
feat: I/O safety ftruncate
1 parent 67f8770 commit b7f8f93

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

src/unistd.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ use std::ffi::{CString, OsStr};
3535
use std::os::unix::ffi::OsStrExt;
3636
use std::os::unix::ffi::OsStringExt;
3737
use std::os::unix::io::RawFd;
38+
use std::os::unix::io::{AsFd, AsRawFd};
3839
use std::path::PathBuf;
3940
use std::{fmt, mem, ptr};
4041

@@ -1255,8 +1256,8 @@ pub fn truncate<P: ?Sized + NixPath>(path: &P, len: off_t) -> Result<()> {
12551256
///
12561257
/// See also
12571258
/// [ftruncate(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html)
1258-
pub fn ftruncate(fd: RawFd, len: off_t) -> Result<()> {
1259-
Errno::result(unsafe { libc::ftruncate(fd, len) }).map(drop)
1259+
pub fn ftruncate<Fd: AsFd>(fd: Fd, len: off_t) -> Result<()> {
1260+
Errno::result(unsafe { libc::ftruncate(fd.as_fd().as_raw_fd(), len) }).map(drop)
12601261
}
12611262

12621263
pub fn isatty(fd: RawFd) -> Result<bool> {

test/test_unistd.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -772,15 +772,12 @@ fn test_ftruncate() {
772772
let tempdir = tempdir().unwrap();
773773
let path = tempdir.path().join("file");
774774

775-
let tmpfd = {
776-
let mut tmp = File::create(&path).unwrap();
777-
const CONTENTS: &[u8] = b"12345678";
778-
tmp.write_all(CONTENTS).unwrap();
779-
tmp.into_raw_fd()
780-
};
775+
let mut file = File::create(&path).unwrap();
776+
const CONTENTS: &[u8] = b"12345678";
777+
file.write_all(CONTENTS).unwrap();
781778

782-
ftruncate(tmpfd, 2).unwrap();
783-
close(tmpfd).unwrap();
779+
ftruncate(&file, 2).unwrap();
780+
drop(file);
784781

785782
let metadata = fs::metadata(&path).unwrap();
786783
assert_eq!(2, metadata.len());

0 commit comments

Comments
 (0)