1 // Copyright 2024, The Android Open Source Project 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //! This module provides os layer utilities. 16 17 use std::io; 18 19 use nix::unistd::sysconf; 20 use nix::unistd::SysconfVar; 21 22 const MEMINFO_PATH: &str = "/proc/meminfo"; 23 24 /// [MeminfoApi] is a mockable interface for access to "/proc/meminfo". 25 #[cfg_attr(test, mockall::automock)] 26 pub trait MeminfoApi { 27 /// read "/proc/meminfo". read_meminfo() -> io::Result<String>28 fn read_meminfo() -> io::Result<String>; 29 } 30 31 /// The implementation of [MeminfoApi]. 32 pub struct MeminfoApiImpl; 33 34 impl MeminfoApi for MeminfoApiImpl { read_meminfo() -> io::Result<String>35 fn read_meminfo() -> io::Result<String> { 36 std::fs::read_to_string(MEMINFO_PATH) 37 } 38 } 39 40 /// Mutex to synchronize tests using [MeminfoApi]. 41 /// 42 /// mockall for static functions requires synchronization. 43 /// 44 /// https://docs.rs/mockall/latest/mockall/#static-methods 45 #[cfg(test)] 46 pub static MEMINFO_API_MTX: std::sync::Mutex<()> = std::sync::Mutex::new(()); 47 48 /// Returns the page size of the system. get_page_size() -> u6449pub fn get_page_size() -> u64 { 50 // SAFETY: `sysconf` simply returns an integer. 51 unsafe { libc::sysconf(libc::_SC_PAGESIZE) as u64 } 52 } 53 54 /// Returns the page count of the system. get_page_count() -> u6455pub fn get_page_count() -> u64 { 56 sysconf(SysconfVar::_PHYS_PAGES) 57 .expect("PHYS_PAGES should be a valid sysconf variable") 58 .expect("PHYS_PAGES variable should be supported") as u64 59 } 60