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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
//! Contains an ffi-safe wrapper for `parking_lot::Once`.
use std::{
any::Any,
fmt::{self, Debug},
mem,
panic::{self, AssertUnwindSafe},
};
use parking_lot::{Once as PLOnce, OnceState};
use super::{UnsafeOveralignedField, RAW_LOCK_SIZE};
use crate::{
prefix_type::WithMetadata,
sabi_types::RMut,
std_types::{RErr, ROk, RResult},
};
///////////////////////////////////////////////////////////////////////////////
type OpaqueOnce = UnsafeOveralignedField<PLOnce, [u8; OM_PADDING]>;
const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::<PLOnce>();
#[allow(clippy::declare_interior_mutable_const)]
const OPAQUE_ONCE: OpaqueOnce = OpaqueOnce::new(parking_lot::Once::new(), [0u8; OM_PADDING]);
const _: () = assert!(RAW_LOCK_SIZE == mem::size_of::<OpaqueOnce>());
///////////////////////////////////////////////////////////////////////////////
/// A synchronization primitive for running global initialization once.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::{RMutex, ROnce};
///
/// static MUTEX: RMutex<usize> = RMutex::new(0);
///
/// static ONCE: ROnce = ROnce::new();
///
/// let guards = std::iter::repeat_with(|| {
/// std::thread::spawn(|| {
/// ONCE.call_once(|| {
/// *MUTEX.lock() += 1;
/// })
/// })
/// })
/// .take(20)
/// .collect::<Vec<_>>();
///
/// for guard in guards {
/// guard.join().unwrap();
/// }
///
/// assert_eq!(*MUTEX.lock(), 1);
///
/// ```
///
///
#[repr(C)]
#[derive(StableAbi)]
pub struct ROnce {
opaque_once: OpaqueOnce,
vtable: VTable_Ref,
}
impl ROnce {
/// Constructs an ROnce.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// static ONCE: ROnce = ROnce::new();
///
/// ```
pub const fn new() -> ROnce {
ROnce {
opaque_once: OPAQUE_ONCE,
vtable: VTable::VTABLE,
}
}
}
#[allow(clippy::missing_const_for_fn)]
impl ROnce {
/// Constructs an ROnce.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// static ONCE: ROnce = ROnce::NEW;
///
/// ```
#[allow(clippy::declare_interior_mutable_const)]
pub const NEW: Self = ROnce {
opaque_once: OPAQUE_ONCE,
vtable: VTable::VTABLE,
};
fn vtable(&self) -> VTable_Ref {
self.vtable
}
/// Gets the running state of this ROnce.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::parking_lot::once::{ROnce, ROnceState};
///
/// use std::panic::AssertUnwindSafe;
///
/// let once = ROnce::new();
///
/// assert_eq!(once.state(), ROnceState::New);
///
/// let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
/// once.call_once(|| panic!());
/// }));
///
/// assert!(once.state().poisoned());
///
/// once.call_once_force(|_| ());
///
/// assert!(once.state().done());
///
/// ```
pub fn state(&self) -> ROnceState {
unsafe { self.vtable().state()(&self.opaque_once) }
}
/// Runs an initialization function.
///
/// `f` will be run only if this is the first time this method has been called
/// on this ROnce.
///
/// Once this function returns it is guaranteed that some closure passed
/// to this method has run to completion.
///
/// # Panics
///
/// Panics in the closure will cause this ROnce to become poisoned,
/// and any future calls to this method will panic.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// let once = ROnce::new();
/// let mut counter = 0usize;
///
/// once.call_once(|| counter += 1);
/// once.call_once(|| counter += 1);
/// once.call_once(|| counter += 1);
/// once.call_once(|| counter += 1);
///
/// assert_eq!(counter, 1);
///
/// ```
pub fn call_once<F>(&self, f: F)
where
F: FnOnce(),
{
let mut closure = Closure::without_state(f);
let func = closure.func;
let res = unsafe {
self.vtable().call_once()(
&self.opaque_once,
RMut::new(&mut closure).transmute::<ErasedClosure>(),
func,
)
};
if let Err(e) = closure.panic {
panic::resume_unwind(e);
}
if let RErr(()) = res {
panic!("This ROnce instantce is poisoned.");
}
}
/// Runs an initialization function,even if the ROnce is poisoned.
///
/// This will keep trying to run different closures until one of them doesn't panic.
///
/// The ROnceState parameter describes whether the ROnce is New or Poisoned.
///
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// use std::panic::{self, AssertUnwindSafe};
///
/// let once = ROnce::new();
/// let mut counter = 0usize;
///
/// for i in 0..100 {
/// let _ = panic::catch_unwind(AssertUnwindSafe(|| {
/// once.call_once_force(|_| {
/// if i < 6 {
/// panic!();
/// }
/// counter = i;
/// })
/// }));
/// }
///
/// assert_eq!(counter, 6);
///
/// ```
pub fn call_once_force<F>(&self, f: F)
where
F: FnOnce(ROnceState),
{
let mut closure = Closure::with_state(f);
let func = closure.func;
let res = unsafe {
self.vtable().call_once_force()(
&self.opaque_once,
RMut::new(&mut closure).transmute::<ErasedClosure>(),
func,
)
};
if let Err(e) = closure.panic {
panic::resume_unwind(e);
}
if let RErr(()) = res {
panic!("This ROnce instantce is poisoned.");
}
}
}
impl Debug for ROnce {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Once")
.field("state", &self.state())
.finish()
}
}
impl Default for ROnce {
#[inline]
fn default() -> Self {
Self::new()
}
}
unsafe impl Send for ROnce {}
unsafe impl Sync for ROnce {}
///////////////////////////////////////////////////////////////////////////////
/// Describes the running state of an ROnce.
#[repr(u8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, StableAbi)]
pub enum ROnceState {
/// An ROnce that hasn't started running
New,
/// An ROnce that panicked inside `call_once*`
Poisoned,
/// An ROnce that is the middle of calling `call_once*`
InProgress,
/// An ROnce that has already run.
Done,
}
#[allow(clippy::missing_const_for_fn)]
impl ROnceState {
/// Whether the ROnce is poisoned,requiring call_once_force to run.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// use std::panic::AssertUnwindSafe;
///
/// let once = ROnce::new();
///
/// let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
/// once.call_once(|| panic!());
/// }));
///
/// assert!(once.state().poisoned());
///
/// ```
///
pub fn poisoned(&self) -> bool {
matches!(self, ROnceState::Poisoned)
}
/// Whether the ROnce has already finished running.
///
/// # Example
///
/// ```
/// use abi_stable::external_types::ROnce;
///
/// let once = ROnce::new();
///
/// once.call_once(|| ());
///
/// assert!(once.state().done());
///
/// ```
pub fn done(&self) -> bool {
matches!(self, ROnceState::Done)
}
}
impl_from_rust_repr! {
impl From<OnceState> for ROnceState {
fn(this){
match this {
OnceState::New=>ROnceState::New,
OnceState::Poisoned=>ROnceState::Poisoned,
OnceState::InProgress=>ROnceState::InProgress,
OnceState::Done=>ROnceState::Done,
}
}
}
}
impl_into_rust_repr! {
impl Into<OnceState> for ROnceState {
fn(this){
match this {
ROnceState::New=>OnceState::New,
ROnceState::Poisoned=>OnceState::Poisoned,
ROnceState::InProgress=>OnceState::InProgress,
ROnceState::Done=>OnceState::Done,
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
#[repr(C)]
#[derive(StableAbi)]
struct ErasedClosure;
struct Closure<F> {
closure: Option<F>,
panic: Result<(), Box<dyn Any + Send + 'static>>,
func: RunClosure,
}
#[derive(StableAbi, Copy, Clone)]
#[repr(transparent)]
struct RunClosure {
func: unsafe extern "C" fn(RMut<'_, ErasedClosure>, ROnceState) -> RResult<(), ()>,
}
impl<F> Closure<F> {
#[inline]
pub fn without_state(function: F) -> Self
where
F: FnOnce(),
{
Self {
closure: Some(function),
panic: Ok(()),
func: RunClosure {
func: Self::run_call_once,
},
}
}
#[inline]
pub fn with_state(function: F) -> Self
where
F: FnOnce(ROnceState),
{
Self {
closure: Some(function),
panic: Ok(()),
func: RunClosure {
func: Self::run_call_once_forced,
},
}
}
unsafe extern "C" fn run_call_once(
this: RMut<'_, ErasedClosure>,
state: ROnceState,
) -> RResult<(), ()>
where
F: FnOnce(),
{
unsafe { Self::run_call(this, state, |f, _| f()) }
}
unsafe extern "C" fn run_call_once_forced(
this: RMut<'_, ErasedClosure>,
state: ROnceState,
) -> RResult<(), ()>
where
F: FnOnce(ROnceState),
{
unsafe { Self::run_call(this, state, |f, state| f(state)) }
}
#[inline]
unsafe fn run_call<M>(
this: RMut<'_, ErasedClosure>,
state: ROnceState,
method: M,
) -> RResult<(), ()>
where
M: FnOnce(F, ROnceState),
{
let mut this = unsafe { this.transmute_into_mut::<Self>() };
let res = panic::catch_unwind(AssertUnwindSafe(|| {
let closure = this.closure.take().unwrap();
method(closure, state);
}));
let ret = match res {
Ok { .. } => ROk(()),
Err { .. } => RErr(()),
};
this.panic = res;
ret
}
}
///////////////////////////////////////////////////////////////////////////////
#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix))]
#[sabi(missing_field(panic))]
struct VTable {
state: unsafe extern "C" fn(&OpaqueOnce) -> ROnceState,
call_once:
unsafe extern "C" fn(&OpaqueOnce, RMut<'_, ErasedClosure>, RunClosure) -> RResult<(), ()>,
call_once_force:
unsafe extern "C" fn(&OpaqueOnce, RMut<'_, ErasedClosure>, RunClosure) -> RResult<(), ()>,
}
impl VTable {
// The VTABLE for this type in this executable/library
const VTABLE: VTable_Ref = {
const S: &WithMetadata<VTable> = &WithMetadata::new(VTable {
state,
call_once,
call_once_force,
});
VTable_Ref(S.static_as_prefix())
};
}
///////////////////////////////////////////////////////////////////////////////
unsafe extern "C" fn state(this: &OpaqueOnce) -> ROnceState {
extern_fn_panic_handling! {
this.value.state().into()
}
}
unsafe extern "C" fn call_once(
this: &OpaqueOnce,
erased_closure: RMut<'_, ErasedClosure>,
runner: RunClosure,
) -> RResult<(), ()> {
call_with_closure(|| {
this.value.call_once(|| unsafe {
(runner.func)(erased_closure, ROnceState::New).unwrap();
});
})
}
unsafe extern "C" fn call_once_force(
this: &OpaqueOnce,
erased_closure: RMut<'_, ErasedClosure>,
runner: RunClosure,
) -> RResult<(), ()> {
call_with_closure(|| {
this.value.call_once_force(|state| unsafe {
(runner.func)(erased_closure, state.into()).unwrap();
});
})
}
#[inline]
fn call_with_closure<F>(f: F) -> RResult<(), ()>
where
F: FnOnce(),
{
let res = panic::catch_unwind(AssertUnwindSafe(f));
match res {
Ok { .. } => ROk(()),
Err { .. } => RErr(()),
}
}
///////////////////////////////////////////////////////////////////////////////
#[cfg(all(test, not(feature = "test_miri_track_raw")))]
//#[cfg(test)]
mod tests {
use super::*;
use crossbeam_utils::thread::scope as scoped_thread;
use abi_stable_shared::test_utils::must_panic;
#[test]
#[cfg(not(all(miri, target_os = "windows")))]
fn state() {
{
let once = ROnce::new();
assert_eq!(once.state(), ROnceState::New);
once.call_once(|| {});
assert_eq!(once.state(), ROnceState::Done);
}
{
let once = ROnce::new();
assert_eq!(once.state(), ROnceState::New);
must_panic(|| {
once.call_once(|| panic!());
})
.unwrap();
assert_eq!(once.state(), ROnceState::Poisoned);
}
{
static ONCE: ROnce = ROnce::new();
scoped_thread(|scope| {
let (tx_start, rx_start) = std::sync::mpsc::channel();
let (tx_end, rx_end) = std::sync::mpsc::channel();
scope.spawn(move |_| {
ONCE.call_once(|| {
tx_start.send(()).unwrap();
rx_end.recv().unwrap();
})
});
scope.spawn(move |_| {
rx_start.recv().unwrap();
assert_eq!(ONCE.state(), ROnceState::InProgress);
tx_end.send(()).unwrap();
});
})
.unwrap();
assert_eq!(ONCE.state(), ROnceState::Done);
}
}
#[test]
fn call_once() {
{
let once = ROnce::new();
let mut a = 0;
once.call_once(|| a += 1);
once.call_once(|| a += 2);
once.call_once(|| panic!());
assert_eq!(a, 1);
}
{
let once = ROnce::new();
let mut a = 0;
must_panic(|| {
once.call_once(|| panic!());
})
.unwrap();
must_panic(|| {
once.call_once(|| a += 2);
})
.unwrap();
assert_eq!(a, 0);
}
}
#[test]
fn call_once_force() {
{
let once = ROnce::new();
let mut a = 0;
once.call_once_force(|_| a += 1);
once.call_once_force(|_| a += 2);
assert_eq!(a, 1);
}
{
let once = ROnce::new();
let a = &mut 0;
must_panic(|| {
once.call_once_force(|state| {
assert_eq!(state, ROnceState::New);
panic!()
});
})
.unwrap();
once.call_once_force(|state| {
assert_eq!(state, ROnceState::Poisoned);
*a += 2;
});
once.call_once_force(|_| *a += 4);
once.call_once_force(|_| panic!());
assert_eq!(*a, 2);
}
}
}