use std::mem::size_of;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructureSize {
pub name: &'static str,
pub entries: u64,
pub bytes: Option<u64>,
}
const MAP_ENTRY_OVERHEAD: usize = 16;
pub fn json_heap_bytes(value: &serde_json::Value) -> usize {
use serde_json::Value;
match value {
Value::Null | Value::Bool(_) | Value::Number(_) => 0,
Value::String(text) => text.len(),
Value::Array(items) => {
items.len() * size_of::<Value>() + items.iter().map(json_heap_bytes).sum::<usize>()
}
Value::Object(map) => map
.iter()
.map(|(key, item)| {
MAP_ENTRY_OVERHEAD
+ size_of::<String>()
+ key.len()
+ size_of::<Value>()
+ json_heap_bytes(item)
})
.sum(),
}
}
pub const fn hash_entry_bytes<K, V>() -> usize {
size_of::<(K, V)>() * 8 / 7 + 1
}
#[cfg(all(feature = "heap-profile", target_os = "linux"))]
pub fn jemalloc_live_bytes() -> u64 {
tikv_jemalloc_ctl::epoch::advance().expect("jemalloc epoch");
tikv_jemalloc_ctl::stats::allocated::read().expect("jemalloc allocated") as u64
}
#[cfg(all(feature = "heap-profile", target_os = "linux"))]
pub async fn heap_profile_pprof() -> anyhow::Result<Vec<u8>> {
let ctl = jemalloc_pprof::PROF_CTL
.as_ref()
.ok_or_else(|| anyhow::anyhow!("jemalloc profiling is not compiled in"))?;
let mut ctl = ctl.lock().await;
ctl.dump_pprof()
}