Skip to main content

anvil/
benchmark.rs

1//! `anvil.benchmark`: the core's service through which a plugin joins the
2//! start-up benchmark and reports its own fields (`anvil_benchmark.h`).
3//!
4//! Declaring fields inside `load`, even zero of them, makes the plugin a
5//! participant, which promises one [`done`](Benchmark::done) call: in a
6//! benchmark start the game quits once it is ready and every participant is
7//! done, or 30 s after ready ([`QUIT`]). Outside a benchmark start
8//! ([`is_active`](Benchmark::is_active) is false) every call checks its
9//! arguments the same way and records nothing, so a plugin may call it always.
10//! A refused call also writes one warning to the plugin's log.
11
12use 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
29/// The service's name.
30pub const SERVICE: &std::ffi::CStr = c"anvil.benchmark";
31/// The service's major version.
32pub const VERSION: u32 = ANVIL_BENCHMARK_SERVICE_VERSION;
33
34/// Published once in a benchmark start, on a thread of its own, when the game
35/// is ready and every participant is done, or 30 s after ready. Payload none.
36// SAFETY: the core publishes it with a NULL payload.
37pub const QUIT: Event<()> = unsafe { Event::new(c"anvil.benchmark_quit") };
38
39/// The unit of a number field.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub enum Unit {
42    /// No unit.
43    None,
44    /// Milliseconds.
45    Ms,
46    /// A count.
47    Count,
48    /// Bytes.
49    Bytes,
50    /// Megabytes.
51    Mb,
52    /// Percent.
53    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/// The kind of a field. There is no string kind: a report carries no paths or text.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum FieldKind<'a> {
72    /// An `i64`.
73    Int(Unit),
74    /// An `f64`; NaN and infinity are refused.
75    Number(Unit),
76    /// One of the options (1 to 32), by name.
77    Enum(&'a [&'a str]),
78    /// False or true.
79    Flag,
80}
81
82/// One field of the plugin's benchmark record.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct Field<'a> {
85    /// `group.field` or `field`, from `[a-z0-9_]`.
86    pub name: &'a str,
87    /// Its kind.
88    pub kind: FieldKind<'a>,
89    /// Short English text for the player's preview only.
90    pub label: Option<&'a str>,
91}
92
93/// The `anvil.benchmark` service.
94#[derive(Clone, Copy)]
95pub struct Benchmark {
96    table: Table<AnvilBenchmarkService>,
97    plugin: *mut AnvilPlugin,
98}
99
100// SAFETY: every function may be called from any thread; the plugin handle is an id.
101unsafe impl Send for Benchmark {}
102// SAFETY: as above.
103unsafe 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    /// The service; `None` with an Anvil older than 1.4.
115    pub fn get(host: &Host) -> Option<Self> {
116        // SAFETY: the table type of anvil.benchmark version 1.
117        let table = unsafe { host.service::<AnvilBenchmarkService>(SERVICE, VERSION) }?;
118        Some(Self {
119            table,
120            plugin: host.raw_plugin(),
121        })
122    }
123
124    /// The C table, for what this crate does not wrap.
125    pub fn c_api(&self) -> Table<AnvilBenchmarkService> {
126        self.table
127    }
128
129    /// Whether this is a benchmark start.
130    pub fn is_active(&self) -> bool {
131        // SAFETY: the service's function.
132        function!(self.table, AnvilBenchmarkService, active).is_ok_and(|f| unsafe { f() } != 0)
133    }
134
135    /// Declares fields, all or none of them; inside `load` only. Any call,
136    /// a refused one included, makes the plugin a participant.
137    pub fn declare(&self, fields: &[Field<'_>]) -> Result<()> {
138        let f = function!(self.table, AnvilBenchmarkService, declare)?;
139        // Everything the raw fields point to lives until the call returns; Anvil copies it.
140        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        // SAFETY: `count` fields whose texts and option lists live until the call returns.
183        let result = unsafe { f(self.plugin, raw.as_ptr(), count) };
184        drop((texts, option_lists));
185        check(result, || "benchmark declare")
186    }
187
188    /// Sets an int field; the last value wins.
189    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        // SAFETY: a NUL-terminated name.
193        check(unsafe { f(self.plugin, name.as_ptr(), value) }, || {
194            format!("benchmark set_int {field}")
195        })
196    }
197
198    /// Sets a number field (finite).
199    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        // SAFETY: a NUL-terminated name.
203        check(unsafe { f(self.plugin, name.as_ptr(), value) }, || {
204            format!("benchmark set_number {field}")
205        })
206    }
207
208    /// Sets an enum field to one of its options.
209    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        // SAFETY: NUL-terminated names.
213        check(
214            unsafe { f(self.plugin, name.as_ptr(), option_c.as_ptr()) },
215            || format!("benchmark set_enum {field}"),
216        )
217    }
218
219    /// Sets a flag field.
220    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        // SAFETY: a NUL-terminated name.
224        check(
225            unsafe { f(self.plugin, name.as_ptr(), i32::from(value)) },
226            || format!("benchmark set_flag {field}"),
227        )
228    }
229
230    /// The participant's work after ready is finished; later values are
231    /// refused. Calling it again does nothing.
232    pub fn done(&self) -> Result<()> {
233        let f = function!(self.table, AnvilBenchmarkService, done)?;
234        // SAFETY: the service's function with this plugin.
235        check(unsafe { f(self.plugin) }, || "benchmark done")
236    }
237
238    /// This start is not representative for the plugin (e.g. a cache still
239    /// being built): it is discarded and replaced. `reason` is a name like a
240    /// field's, e.g. `new_mod_set`. Before `done` only.
241    pub fn learning(&self, reason: &str) -> Result<()> {
242        let f = function!(self.table, AnvilBenchmarkService, learning)?;
243        let reason_c = c_string(reason);
244        // SAFETY: a NUL-terminated reason.
245        check(unsafe { f(self.plugin, reason_c.as_ptr()) }, || {
246            format!("benchmark learning {reason}")
247        })
248    }
249
250    /// The participant opened `files` of the game's files ahead of the game,
251    /// which took `ms` in total. Before `done` only; the last call wins.
252    pub fn open_cost(&self, files: u64, ms: f64) -> Result<()> {
253        let f = function!(self.table, AnvilBenchmarkService, open_cost)?;
254        // SAFETY: the service's function with this plugin.
255        check(unsafe { f(self.plugin, files, ms) }, || {
256            "benchmark open_cost"
257        })
258    }
259}