Debian Codegraph @

debian/rust-vendor/codspeed-divan-compat/src/compat/bench/args.rs

raw
1 use crate::compat_divan::compat::util::ty::TypeCast;
2
3 use core::slice;
4 use std::{
5 any::{Any, TypeId},
6 borrow::Cow,
7 mem,
8 sync::OnceLock,
9 };
10
11 use super::Bencher;
12
13 /// Holds lazily-initialized runtime arguments to be passed into a benchmark.
14 ///
15 /// `#[divan::bench]` stores this as a `__DIVAN_ARGS` global for each entry, and
16 /// then at runtime it is initialized once by a closure that creates the usable
17 /// `BenchArgsRunner`.
18 pub struct BenchArgs {
19 args: OnceLock<ErasedArgsSlice>,
20 }
21
22 /// Type-erased `&'static [T]` that also stores names of the arguments.
23 struct ErasedArgsSlice {
24 /// The start of `&[T]`.
25 args: *const (),
26
27 /// The start of `&[&'static str]`.
28 names: *const &'static str,
29
30 /// The number of arguments.
31 len: usize,
32
33 /// The ID of `T` to ensure correctness.
34 arg_type: TypeId,
35 }
36
37 // SAFETY: Raw pointers in `ErasedArgsSlice` are used in a thread-safe way, and
38 // the argument type is required to be `Send + Sync` when initialized from the
39 // iterator in `BenchArgs::runner`.
40 unsafe impl Send for ErasedArgsSlice {}
41 unsafe impl Sync for ErasedArgsSlice {}
42
43 /// The result of making `BenchArgs` runnable from instantiating the arguments
44 /// list and providing a typed benchmarking implementation.
45 #[derive(Clone, Copy)]
46 pub struct BenchArgsRunner {
47 args: &'static ErasedArgsSlice,
48 bench: fn(Bencher, &ErasedArgsSlice, arg_index: usize),
49 }
50
51 impl BenchArgs {
52 pub const fn new() -> Self {
53 Self {
54 args: OnceLock::new(),
55 }
56 }
57
58 pub fn runner<I, B>(
59 &'static self,
60 make_args: impl FnOnce() -> I,
61 arg_to_string: impl Fn(&I::Item) -> String,
62 _bench_impl: B,
63 ) -> BenchArgsRunner
64 where
65 I: IntoIterator,
66 I::Item: Any + Send + Sync,
67 B: FnOnce(Bencher, &I::Item) + Copy,
68 {
69 let args = self.args.get_or_init(|| {
70 let args_iter = make_args().into_iter();
71
72 // Reuse arguments for names if already a slice of strings.
73 //
74 // NOTE: We do this over `I::IntoIter` instead of `I` since it works
75 // for both slices and `slice::Iter`.
76 let args_strings: Option<&'static [&str]> = args_iter
77 .cast_ref::<slice::Iter<&str>>()
78 .map(|iter| iter.as_slice());
79
80 // Collect arguments into leaked slice.
81 //
82 // Leaking the collected `args` simplifies memory management, such
83 // as when reusing for `names`. We're leaking anyways since this is
84 // accessed via a global `OnceLock`.
85 //
86 // PERF: We could optimize this to reuse arguments when users
87 // provide slices. However, for slices its `Item` is a reference, so
88 // `slice::Iter<I::Item>` would never match here. To make this
89 // optimization, we would need to be able to get the referee type.
90 let args: &'static [I::Item] = Box::leak(args_iter.collect());
91
92 // Collect printable representations of arguments.
93 //
94 // PERF: We take multiple opportunities to reuse the provided
95 // arguments buffer or individual strings' buffers:
96 // - `&[&str]`
97 // - `IntoIterator<Item = &str>`
98 // - `IntoIterator<Item = String>`
99 // - `IntoIterator<Item = Box<str>>`
100 // - `IntoIterator<Item = Cow<str>>`
101 let names: &'static [&str] = 'names: {
102 // PERF: Reuse arguments strings slice.
103 if let Some(args) = args_strings {
104 break 'names args;
105 }
106
107 // PERF: Reuse our args slice allocation.
108 if let Some(args) = args.cast_ref::<&[&str]>() {
109 break 'names args;
110 }
111
112 Box::leak(
113 args.iter()
114 .map(|arg| -> &str {
115 // PERF: Reuse strings as-is.
116 if let Some(arg) = arg.cast_ref::<String>() {
117 return arg;
118 }
119 if let Some(arg) = arg.cast_ref::<Box<str>>() {
120 return arg;
121 }
122 if let Some(arg) = arg.cast_ref::<Cow<str>>() {
123 return arg;
124 }
125
126 // Default to `arg_to_string`, which will format via
127 // either `ToString` or `Debug`.
128 Box::leak(arg_to_string(arg).into_boxed_str())
129 })
130 .collect(),
131 )
132 };
133
134 ErasedArgsSlice {
135 // We `black_box` arguments to prevent the compiler from
136 // optimizing the benchmark for the provided values.
137 args: crate::black_box(args.as_ptr().cast()),
138 names: names.as_ptr(),
139 len: args.len(),
140 arg_type: TypeId::of::<I::Item>(),
141 }
142 });
143
144 BenchArgsRunner {
145 args,
146 bench: bench::<I::Item, B>,
147 }
148 }
149 }
150
151 impl Default for BenchArgs {
152 fn default() -> Self {
153 Self::new()
154 }
155 }
156
157 impl BenchArgsRunner {
158 #[inline]
159 pub(crate) fn bench(&self, bencher: Bencher, index: usize) {
160 (self.bench)(bencher, self.args, index)
161 }
162
163 #[inline]
164 pub(crate) fn arg_names(&self) -> &'static [&'static str] {
165 self.args.names()
166 }
167 }
168
169 impl ErasedArgsSlice {
170 /// Retrieves a slice of arguments if the type is `T`.
171 #[inline]
172 fn typed_args<T: Any>(&self) -> Option<&[T]> {
173 if self.arg_type == TypeId::of::<T>() {
174 // SAFETY: `BenchArgs::runner` guarantees storing `len` instances.
175 Some(unsafe { slice::from_raw_parts(self.args.cast(), self.len) })
176 } else {
177 None
178 }
179 }
180
181 /// Returns the arguments' names.
182 ///
183 /// Names are in the same order as args and thus their indices can be used
184 /// to reference arguments.
185 #[inline]
186 fn names(&self) -> &'static [&str] {
187 // SAFETY: `BenchArgs::runner` guarantees storing `len` names.
188 unsafe { slice::from_raw_parts(self.names, self.len) }
189 }
190 }
191
192 /// The `BenchArgsRunner.bench` implementation.
193 fn bench<T, B>(bencher: Bencher, erased_args: &ErasedArgsSlice, arg_index: usize)
194 where
195 T: Any,
196 B: FnOnce(Bencher, &T) + Copy,
197 {
198 // We defer type checking until the benchmark is run to make safety of this
199 // function easier to audit. Checking here instead of in `BenchArgs::runner`
200 // is late but fine since this check will only fail due to a bug in Divan's
201 // macro code generation.
202
203 let Some(typed_args) = erased_args.typed_args::<T>() else {
204 type_mismatch::<T>();
205
206 // Reduce code size by using a separate function for each `T` instead of
207 // each benchmark closure.
208 #[cold]
209 #[inline(never)]
210 fn type_mismatch<T>() -> ! {
211 unreachable!("incorrect type '{}'", std::any::type_name::<T>())
212 }
213 };
214
215 // SAFETY: The closure is a ZST, so we can construct one out of thin air.
216 // This can be done multiple times without invoking a `Drop` destructor
217 // because it implements `Copy`.
218 let bench_impl: B = unsafe {
219 assert_eq!(
220 size_of::<B>(),
221 0,
222 "benchmark closure expected to be zero-sized"
223 );
224 mem::zeroed()
225 };
226
227 bench_impl(bencher, &typed_args[arg_index]);
228 }