1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use crate::zero_ok;
#[cfg(not(any(
    target_os = "android",
    target_os = "linux",
    target_os = "emscripten",
    target_os = "l4re"
)))]
use libc::posix_fadvise as libc_posix_fadvise;
#[cfg(any(
    target_os = "android",
    target_os = "linux",
    target_os = "emscripten",
    target_os = "l4re"
))]
use libc::posix_fadvise64 as libc_posix_fadvise;
use std::{convert::TryInto, io};
use unsafe_io::{os::posish::AsRawFd, AsUnsafeHandle, UnsafeHandle};

/// `POSIX_FADV_*` constants.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(i32)]
pub enum Advice {
    /// `POSIX_FADV_NORMAL`
    Normal = libc::POSIX_FADV_NORMAL,

    /// `POSIX_FADV_SEQUENTIAL`
    Sequential = libc::POSIX_FADV_SEQUENTIAL,

    /// `POSIX_FADV_RANDOM`
    Random = libc::POSIX_FADV_RANDOM,

    /// `POSIX_FADV_NOREUSE`
    NoReuse = libc::POSIX_FADV_NOREUSE,

    /// `POSIX_FADV_WILLNEED`
    WillNeed = libc::POSIX_FADV_WILLNEED,

    /// `POSIX_FADV_DONTNEED`
    DontNeed = libc::POSIX_FADV_DONTNEED,
}

/// `posix_fadvise(fd, offset, len, advice)`
#[inline]
pub fn fadvise<Fd: AsUnsafeHandle>(
    fd: &Fd,
    offset: u64,
    len: u64,
    advice: Advice,
) -> io::Result<()> {
    let fd = fd.as_unsafe_handle();
    unsafe { _fadvise(fd, offset, len, advice) }
}

unsafe fn _fadvise(fd: UnsafeHandle, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
    if let (Ok(offset), Ok(len)) = (offset.try_into(), len.try_into()) {
        zero_ok(libc_posix_fadvise(
            fd.as_raw_fd() as libc::c_int,
            offset,
            len,
            advice as libc::c_int,
        ))?;
    }

    // If the offset or length can't be converted, ignore the advice, as it
    // isn't likely to be useful in that case.
    Ok(())
}