1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! What the crate takes from std on a hosted build and from elsewhere
//! without it (#1615).
//!
//! The objects build without std on a target with a global allocator and
//! atomic compare-and-swap. Most of what they used from std lives in `core`
//! or `alloc` under the same name; the rest comes from here, so the object
//! code is the same in both builds:
//!
//! - [`prelude`]: the `alloc` names std's prelude adds (`String`, `Vec`,
//! `Box`, `ToString`, `ToOwned`). Only modules that need them import it.
//! - [`collections`]: std's hash maps on a hosted build, hashbrown's
//! without std. Neither's iteration order is fixed, so no output depends
//! on it in either build.
//! - [`sync`]: a mutex (std's on a hosted build, a spin lock without std),
//! and an `AtomicU64` that falls back to that mutex on a target without
//! 64-bit atomics.
//! - [`float`]: the `f64` rounding core lacks.
//! - [`catch_panic`]: std's `catch_unwind`, for calls into application
//! code. Without std a panic isn't caught.
//! - `log_warn!` and `log_debug!`: tracing's `warn!` and `debug!` on a
//! hosted build. Without std they log nothing, since tracing needs atomics
//! that the no_std crates don't assume; they only borrow the variables the
//! line names, so none goes unused.
/// The `alloc` names std's prelude brings into scope.
pub(crate) mod prelude {
pub(crate) use alloc::borrow::ToOwned;
pub(crate) use alloc::boxed::Box;
pub(crate) use alloc::string::{String, ToString};
pub(crate) use alloc::vec::Vec;
}
/// Hash maps and sets: std's with std, hashbrown's without.
pub(crate) mod collections {
#[cfg(not(feature = "std"))]
pub(crate) use hashbrown::{HashMap, HashSet};
#[cfg(feature = "std")]
pub(crate) use std::collections::{HashMap, HashSet};
}
/// A mutex whose [`lock`](sync::Mutex::lock) hands back the guard.
pub(crate) mod sync {
/// A mutual-exclusion lock: std's with std, a spin lock without.
///
/// A poisoned std mutex still hands back its guard. Every value these
/// locks guard is whole between statements, so a panic elsewhere leaves
/// nothing half written.
#[derive(Debug, Default)]
pub(crate) struct Mutex<T>(Inner<T>);
#[cfg(feature = "std")]
type Inner<T> = std::sync::Mutex<T>;
#[cfg(not(feature = "std"))]
type Inner<T> = spinning_top::Spinlock<T>;
/// The guard [`Mutex::lock`] returns.
#[cfg(feature = "std")]
pub(crate) type MutexGuard<'a, T> = std::sync::MutexGuard<'a, T>;
/// The guard [`Mutex::lock`] returns.
#[cfg(not(feature = "std"))]
pub(crate) type MutexGuard<'a, T> = spinning_top::SpinlockGuard<'a, T>;
impl<T> Mutex<T> {
/// A mutex holding `value`.
pub(crate) const fn new(value: T) -> Self {
Self(Inner::new(value))
}
/// Wait for the lock and take it.
pub(crate) fn lock(&self) -> MutexGuard<'_, T> {
#[cfg(feature = "std")]
{
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(not(feature = "std"))]
{
self.0.lock()
}
}
}
#[cfg(not(target_has_atomic = "64"))]
pub(crate) use LockedU64 as AtomicU64;
#[cfg(target_has_atomic = "64")]
pub(crate) use core::sync::atomic::AtomicU64;
/// The calls the crate makes on an `AtomicU64`, behind a [`Mutex`], for a
/// target without 64-bit atomics, such as 32-bit Arm and RISC-V. The
/// lock orders every call, so the orderings go unused. Tests build it on
/// every target.
#[cfg(any(test, not(target_has_atomic = "64")))]
#[derive(Debug, Default)]
pub(crate) struct LockedU64(Mutex<u64>);
#[cfg(any(test, not(target_has_atomic = "64")))]
impl LockedU64 {
/// A counter holding `value`.
pub(crate) const fn new(value: u64) -> Self {
Self(Mutex::new(value))
}
/// The value.
pub(crate) fn load(&self, _: core::sync::atomic::Ordering) -> u64 {
*self.0.lock()
}
/// Replace the value.
pub(crate) fn store(&self, value: u64, _: core::sync::atomic::Ordering) {
*self.0.lock() = value;
}
/// Add `delta`, wrapping, and return the value before.
pub(crate) fn fetch_add(&self, delta: u64, _: core::sync::atomic::Ordering) -> u64 {
let mut value = self.0.lock();
let before = *value;
*value = before.wrapping_add(delta);
before
}
/// Replace the value with what `f` makes of it, unless `f` returns
/// `None`: the value before in `Ok`, or in `Err` when unchanged.
pub(crate) fn try_update(
&self,
_: core::sync::atomic::Ordering,
_: core::sync::atomic::Ordering,
f: impl FnMut(u64) -> Option<u64>,
) -> Result<u64, u64> {
let mut f = f;
let mut value = self.0.lock();
let before = *value;
match f(before) {
Some(next) => {
*value = next;
Ok(before)
}
None => Err(before),
}
}
}
#[cfg(test)]
mod tests {
use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
use super::LockedU64;
/// The fallback answers each call as core's `AtomicU64` does.
#[test]
fn locked_u64_matches_atomic_u64() {
let (locked, atomic) = (LockedU64::new(u64::MAX - 1), AtomicU64::new(u64::MAX - 1));
assert_eq!(locked.fetch_add(3, Relaxed), atomic.fetch_add(3, Relaxed));
assert_eq!(locked.load(Relaxed), atomic.load(Relaxed));
assert_eq!(locked.load(Relaxed), 1);
let bump = |n: u64| n.checked_add(1);
assert_eq!(
locked.try_update(Relaxed, Relaxed, bump),
atomic.try_update(Relaxed, Relaxed, bump)
);
locked.store(u64::MAX, Relaxed);
atomic.store(u64::MAX, Relaxed);
assert_eq!(
locked.try_update(Relaxed, Relaxed, bump),
atomic.try_update(Relaxed, Relaxed, bump)
);
assert_eq!(locked.try_update(Relaxed, Relaxed, bump), Err(u64::MAX));
assert_eq!(locked.load(Relaxed), atomic.load(Relaxed));
}
}
}
/// The `f64` rounding std has and core lacks: std's with std, libm's
/// without. Each is exact in both, but for `hypot`, which may differ in the
/// last place.
pub(crate) mod float {
/// `x` rounded toward zero.
pub(crate) fn trunc(x: f64) -> f64 {
#[cfg(feature = "std")]
{
x.trunc()
}
#[cfg(not(feature = "std"))]
{
libm::trunc(x)
}
}
/// The smallest integer at or above `x`.
pub(crate) fn ceil(x: f64) -> f64 {
#[cfg(feature = "std")]
{
x.ceil()
}
#[cfg(not(feature = "std"))]
{
libm::ceil(x)
}
}
/// `x` rounded to the nearest integer, halves away from zero.
pub(crate) fn round(x: f64) -> f64 {
#[cfg(feature = "std")]
{
x.round()
}
#[cfg(not(feature = "std"))]
{
libm::round(x)
}
}
/// The length of the hypotenuse of a right triangle with legs `x` and
/// `y`.
pub(crate) fn hypot(x: f64, y: f64) -> f64 {
#[cfg(feature = "std")]
{
x.hypot(y)
}
#[cfg(not(feature = "std"))]
{
libm::hypot(x, y)
}
}
}
/// Run `f`, which calls application code: `None` if it panics. Only std
/// can catch a panic, so without it a panic goes on up.
pub(crate) fn catch_panic<R>(f: impl FnOnce() -> R) -> Option<R> {
#[cfg(feature = "std")]
{
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok()
}
#[cfg(not(feature = "std"))]
{
Some(f())
}
}
/// tracing's `warn!` with std; nothing without it.
#[cfg(feature = "std")]
macro_rules! log_warn {
($($arg:tt)*) => { ::tracing::warn!($($arg)*) };
}
/// tracing's `warn!` with std; nothing without it.
#[cfg(not(feature = "std"))]
macro_rules! log_warn {
($($arg:tt)*) => {{
log_fields_used!($($arg)*);
}};
}
/// Without std, borrows each variable a log line's fields name (`%error`,
/// `key = value`), so a binding only the log line reads still counts as
/// used. Every other token is passed over.
#[cfg(not(feature = "std"))]
macro_rules! log_fields_used {
() => {};
($key:ident = % $value:ident $($rest:tt)*) => {
let _ = &$value;
log_fields_used!($($rest)*);
};
($key:ident = ? $value:ident $($rest:tt)*) => {
let _ = &$value;
log_fields_used!($($rest)*);
};
($key:ident = $value:ident $($rest:tt)*) => {
let _ = &$value;
log_fields_used!($($rest)*);
};
(% $value:ident $($rest:tt)*) => {
let _ = &$value;
log_fields_used!($($rest)*);
};
(? $value:ident $($rest:tt)*) => {
let _ = &$value;
log_fields_used!($($rest)*);
};
($other:tt $($rest:tt)*) => {
log_fields_used!($($rest)*);
};
}
/// tracing's `debug!` with std; nothing without it.
#[cfg(feature = "std")]
macro_rules! log_debug {
($($arg:tt)*) => { ::tracing::debug!($($arg)*) };
}
/// tracing's `debug!` with std; nothing without it.
#[cfg(not(feature = "std"))]
macro_rules! log_debug {
($($arg:tt)*) => {{
log_fields_used!($($arg)*);
}};
}