Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: Add File::truncate for async file truncation #317

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ keywords = ["async", "fs", "io-uring"]
[dependencies]
tokio = { version = "1.2", features = ["net", "rt", "sync"] }
slab = "0.4.2"
libc = "0.2.80"
io-uring = "0.6.0"
libc = "0.2.167"
io-uring = "0.7.3"
socket2 = { version = "0.4.4", features = ["all"] }
bytes = { version = "1.0", optional = true }
futures-util = { version = "0.3.26", default-features = false, features = ["std"] }
Expand Down
28 changes: 28 additions & 0 deletions src/fs/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,34 @@ impl File {
Op::fallocate(&self.fd, offset, len, flags)?.await
}

/// Truncates the file to the specified length.
///
/// If the file was larger than `len` bytes, then the extra data is removed.
///
/// If the file was smaller than `len` bytes, then the file is extended and filled with zeros.
///
/// # Examples
///
/// ```no_run
/// use tokio_uring::fs::File;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// tokio_uring::start(async {
/// const PATH: &str = "foo.txt";
/// std::fs::write(PATH, b"hello world").unwrap();
///
/// // Truncate to be shorter.
/// let file = OpenOptions::new().write(true).open(PATH).await.unwrap();
/// file.ftruncate(5).await.unwrap();
///
/// let res = std::fs::read_to_string(PATH).unwrap();
/// assert_eq!(res, "hello");
/// })
/// }
pub async fn ftruncate(&self, len: u64) -> io::Result<()> {
Op::ftruncate(&self.fd, len)?.await
}

/// Closes the file using the uring asynchronous close operation and returns the possible error
/// as described in the close(2) man page.
///
Expand Down
35 changes: 35 additions & 0 deletions src/io/ftruncate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::io;

use io_uring::{opcode, types};

use crate::{
io::SharedFd,
runtime::{
driver::op::{Completable, CqeResult, Op},
CONTEXT,
},
};

pub(crate) struct Ftruncate {
fd: SharedFd,
}

impl Op<Ftruncate> {
pub(crate) fn ftruncate(fd: &SharedFd, len: u64) -> io::Result<Op<Ftruncate>> {
CONTEXT.with(|x| {
x.handle()
.expect("not in a runtime context")
.submit_op(Ftruncate { fd: fd.clone() }, |ftruncate| {
opcode::Ftruncate::new(types::Fd(ftruncate.fd.raw_fd()), len).build()
})
})
}
}

impl Completable for Ftruncate {
type Output = io::Result<()>;

fn complete(self, cqe: CqeResult) -> Self::Output {
cqe.result.map(|_| ())
}
}
2 changes: 2 additions & 0 deletions src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,5 @@ mod writev;

mod writev_all;
pub(crate) use writev_all::writev_at_all;

mod ftruncate;
31 changes: 28 additions & 3 deletions tests/fs_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ use std::{

use tempfile::NamedTempFile;

use tokio_uring::buf::fixed::FixedBufRegistry;
use tokio_uring::buf::{BoundedBuf, BoundedBufMut};
use tokio_uring::fs::File;
use tokio_uring::{
buf::{fixed::FixedBufRegistry, BoundedBuf, BoundedBufMut},
fs::{File, OpenOptions},
};

#[path = "../src/future.rs"]
#[allow(warnings)]
Expand Down Expand Up @@ -313,6 +314,30 @@ fn basic_fallocate() {
});
}

#[test]
fn basic_ftruncate() {
tokio_uring::start(async {
let tempfile = tempfile();
std::fs::write(&tempfile, b"hello world").unwrap();

// Truncate to be shorter.
let file = OpenOptions::new()
.write(true)
.open(&tempfile)
.await
.unwrap();
file.ftruncate(5).await.unwrap();

let res = std::fs::read_to_string(&tempfile).unwrap();
assert_eq!(res, "hello");

// Truncate to be longer; filled with zero.
file.ftruncate(10).await.unwrap();
let res = std::fs::read_to_string(&tempfile).unwrap();
assert_eq!(res, "hello\0\0\0\0\0");
})
}

fn tempfile() -> NamedTempFile {
NamedTempFile::new().unwrap()
}
Expand Down