use std::marker::PhantomData;
use std::ptr::NonNull;
use libc::{c_void, devstat};
use crate::sys::ffi::{
geom_stats_snapshot_free, geom_stats_snapshot_get, geom_stats_snapshot_next,
geom_stats_snapshot_reset,
};
pub(super) struct GeomSnapshot(NonNull<c_void>);
impl GeomSnapshot {
pub(super) unsafe fn new() -> Option<Self> {
match NonNull::new(unsafe { geom_stats_snapshot_get() }) {
Some(n) => Some(Self(n)),
None => {
sinf_debug!("geom_stats_snapshot_get failed");
None
}
}
}
pub(super) fn iter(&mut self) -> GeomSnapshotIter<'_> {
GeomSnapshotIter(self)
}
fn reset(&mut self) {
unsafe { geom_stats_snapshot_reset(self.0.as_mut()) }
}
}
impl Drop for GeomSnapshot {
fn drop(&mut self) {
unsafe { geom_stats_snapshot_free(self.0.as_mut()) };
}
}
#[repr(transparent)]
pub(super) struct Devstat<'a> {
pub(super) devstat: NonNull<devstat>,
phantom: PhantomData<&'a devstat>,
}
pub(super) struct GeomSnapshotIter<'a>(&'a mut GeomSnapshot);
impl<'a> Iterator for GeomSnapshotIter<'a> {
type Item = Devstat<'a>;
fn next(&mut self) -> Option<Self::Item> {
let raw = unsafe { geom_stats_snapshot_next(self.0.0.as_mut()) };
NonNull::new(raw).map(|devstat| Devstat {
devstat,
phantom: PhantomData,
})
}
}
impl Drop for GeomSnapshotIter<'_> {
fn drop(&mut self) {
self.0.reset();
}
}