use std::collections::TryReserveError;
#[inline]
pub(crate) fn try_reserve_exact<T>(
vec: &mut Vec<T>,
additional: usize,
) -> Result<(), TryReserveError> {
#[cfg(any(test, feature = "test-components"))]
{
if let Some(err) = testing::take_pending_fault() {
return Err(err);
}
}
vec.try_reserve_exact(additional)
}
#[cfg(any(test, feature = "test-components"))]
pub mod testing {
use std::cell::Cell;
use std::collections::TryReserveError;
thread_local! {
static PENDING_FAULT: Cell<Option<TryReserveError>> = const { Cell::new(None) };
}
pub fn arm_fault(err: TryReserveError) {
PENDING_FAULT.with(|cell| cell.set(Some(err)));
}
pub(super) fn take_pending_fault() -> Option<TryReserveError> {
PENDING_FAULT.with(|cell| cell.take())
}
pub fn synthetic_err() -> TryReserveError {
let mut v: Vec<[u8; 32]> = Vec::new();
v.try_reserve_exact(usize::MAX)
.expect_err("usize::MAX reserve overflows TryReserveError")
}
pub struct FailOnce {
_private: (),
}
impl FailOnce {
pub fn install() -> Self {
arm_fault(synthetic_err());
Self { _private: () }
}
}
impl Drop for FailOnce {
fn drop(&mut self) {
PENDING_FAULT.with(|cell| cell.set(None));
}
}
}