use core::cell::Cell;
use alloc::string::String;
#[cfg(feature = "std")]
extern crate std;
#[derive(Debug)]
pub struct Shared {
data: String,
count: Cell<usize>,
}
impl Default for Shared {
fn default() -> Self {
Self::new(String::new())
}
}
impl Shared {
pub const fn new(data: String) -> Self {
Self {
data,
count: Cell::new(1),
}
}
const fn reference_count(&self) -> usize {
self.count.get()
}
pub const unsafe fn as_str(&self) -> &str {
self.data.as_str()
}
pub const fn is_unique(&self) -> bool {
self.reference_count() == 1
}
pub unsafe fn take(self) -> String {
self.data
}
pub unsafe fn increment_count(&self) {
let Some(taken) = self.count.get().checked_add(1) else {
reference_count_overflow()
};
self.count.set(taken);
}
pub unsafe fn decrement_count(&self) {
let count = self.count.get();
let remaining = count.checked_sub(1).expect(
"`Shared` reference count underflow: a count was released twice (double release)",
);
self.count.set(remaining);
}
}
const OVERFLOW_MESSAGE: &str =
"`Shared` reference count overflow: more counts were taken than a `usize` can hold";
#[cold]
#[inline(never)]
fn reference_count_overflow() -> ! {
#[cfg(feature = "std")]
{
use std::io::Write as _;
let _ = writeln!(std::io::stderr(), "{OVERFLOW_MESSAGE}");
std::process::abort()
}
#[cfg(not(feature = "std"))]
{
struct PanicOnUnwind;
impl Drop for PanicOnUnwind {
fn drop(&mut self) {
panic!("{OVERFLOW_MESSAGE}");
}
}
let _abort_on_unwind = PanicOnUnwind;
panic!("{OVERFLOW_MESSAGE}");
}
}
#[cfg(test)]
mod tests {
use super::Shared;
use alloc::string::{String, ToString};
extern crate std;
use std::{env, process::Command, string::String as StdString};
const RUN_GUARD: &str = "SUITEKI_TEST_RUN_REFERENCE_COUNT_OVERFLOW_GUARD";
const GUARD_TEST: &str = "shared::tests::taking_a_count_past_usize_max_ends_the_process";
#[test]
fn a_taken_count_can_be_released() {
let shared = Shared::new("a string long enough to be shared".to_string());
assert!(shared.is_unique());
unsafe {
shared.increment_count();
assert!(!shared.is_unique());
shared.decrement_count();
}
assert!(shared.is_unique());
}
#[test]
#[should_panic(expected = "reference count underflow")]
fn releasing_a_count_twice_panics() {
let shared = Shared::new(String::from("a string long enough to be shared"));
unsafe { shared.decrement_count() };
unsafe { shared.decrement_count() };
}
#[test]
#[cfg_attr(miri, ignore = "Miri cannot spawn the child process this test watches")]
fn taking_a_count_past_usize_max_ends_the_process() {
if env::var_os(RUN_GUARD).is_some() {
let shared = Shared::new("a string long enough to be shared".to_string());
shared.count.set(usize::MAX);
unsafe { shared.increment_count() };
std::process::exit(0);
}
let exe = env::current_exe().expect("the test binary must have a path");
let child = Command::new(exe)
.args([GUARD_TEST, "--exact"])
.env(RUN_GUARD, "1")
.output()
.expect("the test binary must be runnable as a child process");
let mut said = StdString::from_utf8_lossy(&child.stdout).into_owned();
said.push_str(&StdString::from_utf8_lossy(&child.stderr));
assert!(
!child.status.success(),
"taking a count past `usize::MAX` let the count wrap instead of ending the process: {said}"
);
assert!(
said.contains("reference count overflow"),
"the child ended without saying why, so the guard is not what stopped it: {said}"
);
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
assert!(
child.status.signal().is_some(),
"the child ended without being aborted, so the guard is not what stopped it: {said}"
);
}
}
}