1use std::ffi::{c_char, CString};
13use std::fmt;
14use std::ptr;
15
16use crate::error::{check, Result};
17use crate::event::Event;
18use crate::host::Host;
19use crate::sys::{
20 AnvilBenchmarkField, AnvilBenchmarkService, AnvilPlugin, ANVIL_BENCHMARK_ENUM,
21 ANVIL_BENCHMARK_FLAG, ANVIL_BENCHMARK_INT, ANVIL_BENCHMARK_NUMBER,
22 ANVIL_BENCHMARK_SERVICE_VERSION, ANVIL_BENCHMARK_UNIT_BYTES, ANVIL_BENCHMARK_UNIT_COUNT,
23 ANVIL_BENCHMARK_UNIT_MB, ANVIL_BENCHMARK_UNIT_MS, ANVIL_BENCHMARK_UNIT_NONE,
24 ANVIL_BENCHMARK_UNIT_PERCENT,
25};
26use crate::table::Table;
27use crate::text::c_string;
28
29pub const SERVICE: &std::ffi::CStr = c"anvil.benchmark";
31pub const VERSION: u32 = ANVIL_BENCHMARK_SERVICE_VERSION;
33
34pub const QUIT: Event<()> = unsafe { Event::new(c"anvil.benchmark_quit") };
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub enum Unit {
42 None,
44 Ms,
46 Count,
48 Bytes,
50 Mb,
52 Percent,
54}
55
56impl Unit {
57 const fn raw(self) -> u32 {
58 (match self {
59 Self::None => ANVIL_BENCHMARK_UNIT_NONE,
60 Self::Ms => ANVIL_BENCHMARK_UNIT_MS,
61 Self::Count => ANVIL_BENCHMARK_UNIT_COUNT,
62 Self::Bytes => ANVIL_BENCHMARK_UNIT_BYTES,
63 Self::Mb => ANVIL_BENCHMARK_UNIT_MB,
64 Self::Percent => ANVIL_BENCHMARK_UNIT_PERCENT,
65 }) as u32
66 }
67}
68
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum FieldKind<'a> {
72 Int(Unit),
74 Number(Unit),
76 Enum(&'a [&'a str]),
78 Flag,
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct Field<'a> {
85 pub name: &'a str,
87 pub kind: FieldKind<'a>,
89 pub label: Option<&'a str>,
91}
92
93#[derive(Clone, Copy)]
95pub struct Benchmark {
96 table: Table<AnvilBenchmarkService>,
97 plugin: *mut AnvilPlugin,
98}
99
100unsafe impl Send for Benchmark {}
102unsafe impl Sync for Benchmark {}
104
105impl fmt::Debug for Benchmark {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.debug_struct("Benchmark")
108 .field("active", &self.is_active())
109 .finish()
110 }
111}
112
113impl Benchmark {
114 pub fn get(host: &Host) -> Option<Self> {
116 let table = unsafe { host.service::<AnvilBenchmarkService>(SERVICE, VERSION) }?;
118 Some(Self {
119 table,
120 plugin: host.raw_plugin(),
121 })
122 }
123
124 pub fn c_api(&self) -> Table<AnvilBenchmarkService> {
126 self.table
127 }
128
129 pub fn is_active(&self) -> bool {
131 function!(self.table, AnvilBenchmarkService, active).is_ok_and(|f| unsafe { f() } != 0)
133 }
134
135 pub fn declare(&self, fields: &[Field<'_>]) -> Result<()> {
138 let f = function!(self.table, AnvilBenchmarkService, declare)?;
139 let mut texts: Vec<CString> = Vec::new();
141 let mut option_lists: Vec<Vec<*const c_char>> = Vec::new();
142 let mut raw: Vec<AnvilBenchmarkField> = Vec::with_capacity(fields.len());
143 for field in fields {
144 let name = c_string(field.name);
145 let label = field.label.map(c_string);
146 let (kind, unit, options, option_count) = match field.kind {
147 FieldKind::Int(unit) => (ANVIL_BENCHMARK_INT, unit.raw(), ptr::null(), 0),
148 FieldKind::Number(unit) => (ANVIL_BENCHMARK_NUMBER, unit.raw(), ptr::null(), 0),
149 FieldKind::Flag => (ANVIL_BENCHMARK_FLAG, Unit::None.raw(), ptr::null(), 0),
150 FieldKind::Enum(names) => {
151 let list: Vec<*const c_char> = names
152 .iter()
153 .map(|option| {
154 let c = c_string(option);
155 let pointer = c.as_ptr();
156 texts.push(c);
157 pointer
158 })
159 .collect();
160 let pointer = list.as_ptr();
161 option_lists.push(list);
162 (
163 ANVIL_BENCHMARK_ENUM,
164 Unit::None.raw(),
165 pointer,
166 u32::try_from(names.len()).unwrap_or(u32::MAX),
167 )
168 }
169 };
170 raw.push(AnvilBenchmarkField {
171 name: name.as_ptr(),
172 kind: kind as u32,
173 unit,
174 label: label.as_ref().map_or(ptr::null(), |l| l.as_ptr()),
175 options,
176 option_count,
177 });
178 texts.push(name);
179 texts.extend(label);
180 }
181 let count = u32::try_from(raw.len()).unwrap_or(u32::MAX);
182 let result = unsafe { f(self.plugin, raw.as_ptr(), count) };
184 drop((texts, option_lists));
185 check(result, || "benchmark declare")
186 }
187
188 pub fn set_int(&self, field: &str, value: i64) -> Result<()> {
190 let f = function!(self.table, AnvilBenchmarkService, set_int)?;
191 let name = c_string(field);
192 check(unsafe { f(self.plugin, name.as_ptr(), value) }, || {
194 format!("benchmark set_int {field}")
195 })
196 }
197
198 pub fn set_number(&self, field: &str, value: f64) -> Result<()> {
200 let f = function!(self.table, AnvilBenchmarkService, set_number)?;
201 let name = c_string(field);
202 check(unsafe { f(self.plugin, name.as_ptr(), value) }, || {
204 format!("benchmark set_number {field}")
205 })
206 }
207
208 pub fn set_enum(&self, field: &str, option: &str) -> Result<()> {
210 let f = function!(self.table, AnvilBenchmarkService, set_enum)?;
211 let (name, option_c) = (c_string(field), c_string(option));
212 check(
214 unsafe { f(self.plugin, name.as_ptr(), option_c.as_ptr()) },
215 || format!("benchmark set_enum {field}"),
216 )
217 }
218
219 pub fn set_flag(&self, field: &str, value: bool) -> Result<()> {
221 let f = function!(self.table, AnvilBenchmarkService, set_flag)?;
222 let name = c_string(field);
223 check(
225 unsafe { f(self.plugin, name.as_ptr(), i32::from(value)) },
226 || format!("benchmark set_flag {field}"),
227 )
228 }
229
230 pub fn done(&self) -> Result<()> {
233 let f = function!(self.table, AnvilBenchmarkService, done)?;
234 check(unsafe { f(self.plugin) }, || "benchmark done")
236 }
237
238 pub fn learning(&self, reason: &str) -> Result<()> {
242 let f = function!(self.table, AnvilBenchmarkService, learning)?;
243 let reason_c = c_string(reason);
244 check(unsafe { f(self.plugin, reason_c.as_ptr()) }, || {
246 format!("benchmark learning {reason}")
247 })
248 }
249
250 pub fn open_cost(&self, files: u64, ms: f64) -> Result<()> {
253 let f = function!(self.table, AnvilBenchmarkService, open_cost)?;
254 check(unsafe { f(self.plugin, files, ms) }, || {
256 "benchmark open_cost"
257 })
258 }
259}