use std::ffi::{c_char, CString};
use std::fmt;
use std::ptr;
use crate::error::{check, Result};
use crate::event::Event;
use crate::host::Host;
use crate::sys::{
AnvilBenchmarkField, AnvilBenchmarkService, AnvilPlugin, ANVIL_BENCHMARK_ENUM,
ANVIL_BENCHMARK_FLAG, ANVIL_BENCHMARK_INT, ANVIL_BENCHMARK_NUMBER,
ANVIL_BENCHMARK_SERVICE_VERSION, ANVIL_BENCHMARK_UNIT_BYTES, ANVIL_BENCHMARK_UNIT_COUNT,
ANVIL_BENCHMARK_UNIT_MB, ANVIL_BENCHMARK_UNIT_MS, ANVIL_BENCHMARK_UNIT_NONE,
ANVIL_BENCHMARK_UNIT_PERCENT,
};
use crate::table::Table;
use crate::text::c_string;
pub const SERVICE: &std::ffi::CStr = c"anvil.benchmark";
pub const VERSION: u32 = ANVIL_BENCHMARK_SERVICE_VERSION;
pub const QUIT: Event<()> = unsafe { Event::new(c"anvil.benchmark_quit") };
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Unit {
None,
Ms,
Count,
Bytes,
Mb,
Percent,
}
impl Unit {
const fn raw(self) -> u32 {
(match self {
Self::None => ANVIL_BENCHMARK_UNIT_NONE,
Self::Ms => ANVIL_BENCHMARK_UNIT_MS,
Self::Count => ANVIL_BENCHMARK_UNIT_COUNT,
Self::Bytes => ANVIL_BENCHMARK_UNIT_BYTES,
Self::Mb => ANVIL_BENCHMARK_UNIT_MB,
Self::Percent => ANVIL_BENCHMARK_UNIT_PERCENT,
}) as u32
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FieldKind<'a> {
Int(Unit),
Number(Unit),
Enum(&'a [&'a str]),
Flag,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Field<'a> {
pub name: &'a str,
pub kind: FieldKind<'a>,
pub label: Option<&'a str>,
}
#[derive(Clone, Copy)]
pub struct Benchmark {
table: Table<AnvilBenchmarkService>,
plugin: *mut AnvilPlugin,
}
unsafe impl Send for Benchmark {}
unsafe impl Sync for Benchmark {}
impl fmt::Debug for Benchmark {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Benchmark")
.field("active", &self.is_active())
.finish()
}
}
impl Benchmark {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilBenchmarkService>(SERVICE, VERSION) }?;
Some(Self {
table,
plugin: host.raw_plugin(),
})
}
pub fn c_api(&self) -> Table<AnvilBenchmarkService> {
self.table
}
pub fn is_active(&self) -> bool {
function!(self.table, AnvilBenchmarkService, active).is_ok_and(|f| unsafe { f() } != 0)
}
pub fn declare(&self, fields: &[Field<'_>]) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, declare)?;
let mut texts: Vec<CString> = Vec::new();
let mut option_lists: Vec<Vec<*const c_char>> = Vec::new();
let mut raw: Vec<AnvilBenchmarkField> = Vec::with_capacity(fields.len());
for field in fields {
let name = c_string(field.name);
let label = field.label.map(c_string);
let (kind, unit, options, option_count) = match field.kind {
FieldKind::Int(unit) => (ANVIL_BENCHMARK_INT, unit.raw(), ptr::null(), 0),
FieldKind::Number(unit) => (ANVIL_BENCHMARK_NUMBER, unit.raw(), ptr::null(), 0),
FieldKind::Flag => (ANVIL_BENCHMARK_FLAG, Unit::None.raw(), ptr::null(), 0),
FieldKind::Enum(names) => {
let list: Vec<*const c_char> = names
.iter()
.map(|option| {
let c = c_string(option);
let pointer = c.as_ptr();
texts.push(c);
pointer
})
.collect();
let pointer = list.as_ptr();
option_lists.push(list);
(
ANVIL_BENCHMARK_ENUM,
Unit::None.raw(),
pointer,
u32::try_from(names.len()).unwrap_or(u32::MAX),
)
}
};
raw.push(AnvilBenchmarkField {
name: name.as_ptr(),
kind: kind as u32,
unit,
label: label.as_ref().map_or(ptr::null(), |l| l.as_ptr()),
options,
option_count,
});
texts.push(name);
texts.extend(label);
}
let count = u32::try_from(raw.len()).unwrap_or(u32::MAX);
let result = unsafe { f(self.plugin, raw.as_ptr(), count) };
drop((texts, option_lists));
check(result, || "benchmark declare")
}
pub fn set_int(&self, field: &str, value: i64) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, set_int)?;
let name = c_string(field);
check(unsafe { f(self.plugin, name.as_ptr(), value) }, || {
format!("benchmark set_int {field}")
})
}
pub fn set_number(&self, field: &str, value: f64) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, set_number)?;
let name = c_string(field);
check(unsafe { f(self.plugin, name.as_ptr(), value) }, || {
format!("benchmark set_number {field}")
})
}
pub fn set_enum(&self, field: &str, option: &str) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, set_enum)?;
let (name, option_c) = (c_string(field), c_string(option));
check(
unsafe { f(self.plugin, name.as_ptr(), option_c.as_ptr()) },
|| format!("benchmark set_enum {field}"),
)
}
pub fn set_flag(&self, field: &str, value: bool) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, set_flag)?;
let name = c_string(field);
check(
unsafe { f(self.plugin, name.as_ptr(), i32::from(value)) },
|| format!("benchmark set_flag {field}"),
)
}
pub fn done(&self) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, done)?;
check(unsafe { f(self.plugin) }, || "benchmark done")
}
pub fn learning(&self, reason: &str) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, learning)?;
let reason_c = c_string(reason);
check(unsafe { f(self.plugin, reason_c.as_ptr()) }, || {
format!("benchmark learning {reason}")
})
}
pub fn open_cost(&self, files: u64, ms: f64) -> Result<()> {
let f = function!(self.table, AnvilBenchmarkService, open_cost)?;
check(unsafe { f(self.plugin, files, ms) }, || {
"benchmark open_cost"
})
}
}