use std::fmt;
use std::str;
use crate::{read_value, write_value, ProcResult};
pub fn admin_reserve_kbytes() -> ProcResult<usize> {
read_value("/proc/sys/vm/admin_reserve_kbytes")
}
pub fn set_admin_reserve_kbytes(kbytes: usize) -> ProcResult<()> {
write_value("/proc/sys/vm/admin_reserve_kbytes", kbytes)
}
pub fn compact_memory() -> ProcResult<()> {
write_value("/proc/sys/vm/compact_memory", 1)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DropCache {
Default = 0,
PageCache = 1,
Inodes = 2,
All = 3,
Disable = 4,
}
impl fmt::Display for DropCache {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
DropCache::Default => 0,
DropCache::PageCache => 1,
DropCache::Inodes => 2,
DropCache::All => 3,
DropCache::Disable => 4,
}
)
}
}
impl str::FromStr for DropCache {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse().map_err(|_| "Fail to parse drop cache").and_then(|n| match n {
0 => Ok(DropCache::Default),
1 => Ok(DropCache::PageCache),
2 => Ok(DropCache::Inodes),
3 => Ok(DropCache::All),
4 => Ok(DropCache::Disable),
_ => Err("Unknown drop cache value"),
})
}
}
pub fn drop_caches(drop: DropCache) -> ProcResult<()> {
write_value("/proc/sys/vm/drop_caches", drop)
}
pub fn max_map_count() -> ProcResult<u64> {
read_value("/proc/sys/vm/max_map_count")
}
pub fn set_max_map_count(count: u64) -> ProcResult<()> {
write_value("/proc/sys/vm/max_map_count", count)
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn test() {
use std::path::Path;
if Path::new("/proc/sys/vm/admin_reserve_kbytes").exists() {
admin_reserve_kbytes().unwrap();
}
if Path::new("/proc/sys/vm/max_map_count").exists() {
max_map_count().unwrap();
}
for v in 0..5 {
let s = format!("{}", v);
let dc = DropCache::from_str(&s).unwrap();
assert_eq!(format!("{}", dc), s);
}
}
}