rust-analyzer/crates/ra_prof/src/memory_usage.rs

68 lines
1.5 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
use std::fmt;
use cfg_if::cfg_if;
pub struct MemoryUsage {
pub allocated: Bytes,
}
impl MemoryUsage {
pub fn current() -> MemoryUsage {
cfg_if! {
if #[cfg(target_os = "linux")] {
// Note: This is incredibly slow.
let alloc = unsafe { libc::mallinfo() }.uordblks as u32 as usize;
2020-07-30 07:45:20 +00:00
MemoryUsage { allocated: Bytes(alloc) }
} else {
2020-07-30 07:45:20 +00:00
MemoryUsage { allocated: Bytes(0) }
}
}
}
}
impl fmt::Display for MemoryUsage {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2020-07-30 07:45:20 +00:00
write!(fmt, "{}", self.allocated)
}
}
2019-06-30 11:40:01 +00:00
#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct Bytes(usize);
2020-07-25 08:35:45 +00:00
impl Bytes {
pub fn megabytes(self) -> usize {
self.0 / 1024 / 1024
}
}
impl fmt::Display for Bytes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let bytes = self.0;
2019-06-30 11:40:01 +00:00
let mut value = bytes;
let mut suffix = "b";
if value > 4096 {
value /= 1024;
suffix = "kb";
if value > 4096 {
value /= 1024;
suffix = "mb";
}
}
2019-06-30 11:40:01 +00:00
f.pad(&format!("{}{}", value, suffix))
}
}
impl std::ops::AddAssign<usize> for Bytes {
fn add_assign(&mut self, x: usize) {
self.0 += x;
}
}
2019-06-30 11:40:01 +00:00
impl std::ops::Sub for Bytes {
type Output = Bytes;
fn sub(self, rhs: Bytes) -> Bytes {
Bytes(self.0 - rhs.0)
}
}