Skip to content

Commit

Permalink
feat: I/O safety ftruncate
Browse files Browse the repository at this point in the history
  • Loading branch information
JonathanWoollett-Light committed Jan 8, 2023
1 parent 67f8770 commit b7f8f93
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
5 changes: 3 additions & 2 deletions src/unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ use std::ffi::{CString, OsStr};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::io::RawFd;
use std::os::unix::io::{AsFd, AsRawFd};
use std::path::PathBuf;
use std::{fmt, mem, ptr};

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

pub fn isatty(fd: RawFd) -> Result<bool> {
Expand Down
13 changes: 5 additions & 8 deletions test/test_unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -772,15 +772,12 @@ fn test_ftruncate() {
let tempdir = tempdir().unwrap();
let path = tempdir.path().join("file");

let tmpfd = {
let mut tmp = File::create(&path).unwrap();
const CONTENTS: &[u8] = b"12345678";
tmp.write_all(CONTENTS).unwrap();
tmp.into_raw_fd()
};
let mut file = File::create(&path).unwrap();
const CONTENTS: &[u8] = b"12345678";
file.write_all(CONTENTS).unwrap();

ftruncate(tmpfd, 2).unwrap();
close(tmpfd).unwrap();
ftruncate(&file, 2).unwrap();
drop(file);

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

0 comments on commit b7f8f93

Please sign in to comment.