1 // Copyright 2018 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 use std::cmp::min;
6 use std::fs::File;
7 use std::io;
8 use std::os::unix::fs::FileExt;
9
10 use super::discard_block;
11 use super::fallocate;
12 use super::is_block_file;
13 use super::FallocateMode;
14
file_punch_hole(file: &File, offset: u64, length: u64) -> io::Result<()>15 pub(crate) fn file_punch_hole(file: &File, offset: u64, length: u64) -> io::Result<()> {
16 if is_block_file(file)? {
17 Ok(discard_block(file, offset, length)?)
18 } else {
19 fallocate(file, FallocateMode::PunchHole, offset, length)
20 .map_err(|e| io::Error::from_raw_os_error(e.errno()))
21 }
22 }
23
file_write_zeroes_at(file: &File, offset: u64, length: usize) -> io::Result<usize>24 pub(crate) fn file_write_zeroes_at(file: &File, offset: u64, length: usize) -> io::Result<usize> {
25 // Try to use fallocate() first.
26 if fallocate(file, FallocateMode::ZeroRange, offset, length as u64).is_ok() {
27 return Ok(length);
28 }
29
30 // fall back to write()
31 // fallocate() failed; fall back to writing a buffer of zeroes
32 // until we have written up to length.
33 let buf_size = min(length, 0x10000);
34 let buf = vec![0u8; buf_size];
35 let mut nwritten: usize = 0;
36 while nwritten < length {
37 let remaining = length - nwritten;
38 let write_size = min(remaining, buf_size);
39 nwritten += file.write_at(&buf[0..write_size], offset + nwritten as u64)?;
40 }
41 Ok(length)
42 }
43