diff options
Diffstat (limited to 'sys_util/src')
-rw-r--r-- | sys_util/src/file_traits.rs | 16 | ||||
-rw-r--r-- | sys_util/src/lib.rs | 5 |
2 files changed, 20 insertions, 1 deletions
diff --git a/sys_util/src/file_traits.rs b/sys_util/src/file_traits.rs index 7e615d6..54e710f 100644 --- a/sys_util/src/file_traits.rs +++ b/sys_util/src/file_traits.rs @@ -8,6 +8,8 @@ use std::os::unix::io::{AsRawFd, RawFd}; use data_model::VolatileSlice; +use crate::{fallocate, FallocateMode}; + /// A trait for flushing the contents of a file to disk. /// This is equivalent to File's `sync_all` method, but /// wrapped in a trait so that it can be implemented for @@ -54,6 +56,20 @@ impl FileGetLen for File { } } +/// A trait for allocating disk space in a sparse file. +/// This is equivalent to fallocate() with no special flags. +pub trait FileAllocate { + /// Allocate storage for the region of the file starting at `offset` and extending `len` bytes. + fn allocate(&mut self, offset: u64, len: u64) -> Result<()>; +} + +impl FileAllocate for File { + fn allocate(&mut self, offset: u64, len: u64) -> Result<()> { + fallocate(self, FallocateMode::Allocate, true, offset, len) + .map_err(|e| Error::from_raw_os_error(e.errno())) + } +} + /// A trait similar to `Read` and `Write`, but uses volatile memory as buffers. pub trait FileReadWriteVolatile { /// Read bytes from this file into the given slice, returning the number of bytes read on diff --git a/sys_util/src/lib.rs b/sys_util/src/lib.rs index bde5eb2..357e6b4 100644 --- a/sys_util/src/lib.rs +++ b/sys_util/src/lib.rs @@ -64,7 +64,8 @@ pub use crate::timerfd::*; pub use poll_token_derive::*; pub use crate::file_traits::{ - AsRawFds, FileGetLen, FileReadWriteAtVolatile, FileReadWriteVolatile, FileSetLen, FileSync, + AsRawFds, FileAllocate, FileGetLen, FileReadWriteAtVolatile, FileReadWriteVolatile, FileSetLen, + FileSync, }; pub use crate::guest_memory::Error as GuestMemoryError; pub use crate::mmap::Error as MmapError; @@ -175,6 +176,7 @@ pub fn flock(file: &dyn AsRawFd, op: FlockOperation, nonblocking: bool) -> Resul pub enum FallocateMode { PunchHole, ZeroRange, + Allocate, } /// Safe wrapper for `fallocate()`. @@ -200,6 +202,7 @@ pub fn fallocate( let mut mode = match mode { FallocateMode::PunchHole => libc::FALLOC_FL_PUNCH_HOLE, FallocateMode::ZeroRange => libc::FALLOC_FL_ZERO_RANGE, + FallocateMode::Allocate => 0, }; if keep_size { |