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
use core::cell::RefCell;
use core::ffi::CStr;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
};
use core::panic::AssertUnwindSafe;
use core::sync::atomic::{
AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32,
AtomicU64, AtomicU8, AtomicUsize,
};
use alloc::boxed::Box;
use alloc::vec::Vec;
use alloc::ffi::CString;
use alloc::string::String;
#[cfg(feature = "std")]
use std::{
path::{Path, PathBuf},
ffi::{OsStr, OsString}
};
use crate::List;
/// Trait to finalize objects before freeing them.
///
/// Must be always implemented for every cycle-collectable object, even when `finalization` is disabled, to avoid cross-crate incompatibilities.
/// When `finalization` is disabled, the [`finalize`] method will *never* be called.
///
/// # Derive macro
///
/// The [`Finalize`][`macro@crate::Finalize`] derive macro can be used to implement an empty finalizer:
#[cfg_attr(
feature = "derive",
doc = r"```rust"
)]
#[cfg_attr(
not(feature = "derive"),
doc = r"```rust,ignore"
)]
#[doc = r"# use rust_cc::*;
# use rust_cc_derive::*;
#[derive(Finalize)]
struct Foo {
// ...
}
```"]
///
/// [`finalize`]: Finalize::finalize
pub trait Finalize {
/// The finalizer, which is called after an object becomes garbage and before [`drop`]ing it.
///
/// By default, objects are finalized only once. Use the method [`Cc::finalize_again`] to make finalization happen again for a certain object.
/// Also, objects created during the execution of a finalizer are not automatically finalized.
///
/// # Default implementation
///
/// The default implementation is empty.
///
/// [`drop`]: core::ops::Drop::drop
/// [`Cc::finalize_again`]: crate::Cc::finalize_again
#[inline(always)]
fn finalize(&self) {}
}
/// Trait to trace cycle-collectable objects.
///
/// This trait is unsafe to implement, but can be safely derived using the [`Trace`][`macro@crate::Trace`] derive macro, which calls the [`trace`] method on every field:
#[cfg_attr(
feature = "derive",
doc = r"```rust"
)]
#[cfg_attr(
not(feature = "derive"),
doc = r"```rust,ignore"
)]
#[doc = r"# use rust_cc::*;
# use rust_cc_derive::*;
# #[derive(Finalize)]
#[derive(Trace)]
struct Foo<A: Trace + 'static, B: Trace + 'static> {
a_field: Cc<A>,
another_field: Cc<B>,
}
```"]
///
/// This trait is already implemented for common types from the standard library.
///
/// # Safety
/// The implementations of this trait must uphold the following invariants:
/// * The [`trace`] implementation can trace (maximum once) every [`Cc`] instance *exclusively* owned by `self`.
/// No other [`Cc`] instance can be traced.
/// * It's always safe to panic.
/// * During the same tracing phase (see below), two different [`trace`] calls on the same value must *behave the same*, i.e. they must trace the same
/// [`Cc`] instances.
/// If a panic happens during the second of such [`trace`] calls but not in the first one, then the [`Cc`] instances traced during the second call
/// must be a subset of the [`Cc`] instances traced in the first one.
/// Tracing can be detected using the [`state::is_tracing`] function. If it never returned `false` between two [`trace`] calls
/// on the same value, then they are part of the same tracing phase.
/// * The [`trace`] implementation must not create, clone, dereference or drop any [`Cc`].
/// * If the implementing type implements [`Drop`], then the [`Drop::drop`] implementation must not create, clone, move, dereference, drop or call
/// any method on any [`Cc`] instance.
///
/// # Implementation tips
/// It is almost always preferable to use the derive macro `#[derive(Trace)]`, but in case a manual implementation is needed the following suggestions usually apply:
/// * If a field's type implements [`Trace`], then call its [`trace`] method.
/// * Try to avoid panicking if not strictly necessary, since it may lead to memory leaks.
/// * Avoid mixing [`Cc`]s with other shared-ownership smart pointers like [`Rc`] (a [`Cc`] contained inside an [`Rc`] cannot be traced,
/// since it's not owned *exclusively*).
/// * Never tracing a field is always safe.
/// * If you need to perform any clean up actions, you should do them in the [`Finalize::finalize`] implementation (instead of inside [`Drop::drop`])
/// or using a [cleaner](crate::cleaners).
///
/// # Derive macro compatibility
/// In order to improve the `Trace` derive macro usability and error messages, it is suggested to avoid implementing this trait for references or raw pointers
/// (also considering that no pointed [`Cc`] may be traced, since a reference doesn't own what it refers to).
///
/// [`trace`]: crate::Trace::trace
/// [`state::is_tracing`]: crate::state::is_tracing
/// [`Finalize::finalize`]: crate::Finalize::finalize
/// [`Cc`]: crate::Cc
/// [`Drop`]: core::ops::Drop
/// [`Rc`]: alloc::rc::Rc
/// [`Drop::drop`]: core::ops::Drop::drop
pub unsafe trait Trace: Finalize {
/// Traces the contained [`Cc`]s. See [`Trace`] for more information.
///
/// [`Cc`]: crate::Cc
fn trace(&self, ctx: &mut Context<'_>);
}
/// The tracing context provided to every invocation of [`Trace::trace`].
pub struct Context<'a> {
inner: ContextInner<'a>,
_phantom: PhantomData<*mut ()>, // Make Context !Send and !Sync
}
pub(crate) enum ContextInner<'a> {
Counting {
root_list: &'a mut List,
non_root_list: &'a mut List,
},
RootTracing {
root_list: &'a mut List,
non_root_list: &'a mut List,
},
}
impl<'b> Context<'b> {
#[inline]
#[must_use]
pub(crate) const fn new(ctxi: ContextInner) -> Context {
Context {
inner: ctxi,
_phantom: PhantomData,
}
}
#[inline]
pub(crate) fn inner<'a>(&'a mut self) -> &'a mut ContextInner<'b>
where
'b: 'a,
{
&mut self.inner
}
}
// #################################
// # Trace impls #
// #################################
macro_rules! empty_trace {
($($this:ty),*,) => {
$(
unsafe impl $crate::trace::Trace for $this {
#[inline(always)]
fn trace(&self, _: &mut $crate::trace::Context<'_>) {}
}
impl $crate::trace::Finalize for $this {
}
)*
};
}
empty_trace! {
(),
bool,
isize,
usize,
i8,
u8,
i16,
u16,
i32,
u32,
i64,
u64,
i128,
u128,
f32,
f64,
char,
str,
CStr,
String,
CString,
NonZeroIsize,
NonZeroUsize,
NonZeroI8,
NonZeroU8,
NonZeroI16,
NonZeroU16,
NonZeroI32,
NonZeroU32,
NonZeroI64,
NonZeroU64,
NonZeroI128,
NonZeroU128,
AtomicBool,
AtomicIsize,
AtomicUsize,
AtomicI8,
AtomicU8,
AtomicI16,
AtomicU16,
AtomicI32,
AtomicU32,
AtomicI64,
AtomicU64,
}
#[cfg(feature = "std")]
empty_trace! {
Path,
OsStr,
PathBuf,
OsString,
}
// Removed since these impls are error-prone. Making a Cc<MaybeUninit<T>> and then casting it to Cc<T>
// doesn't make T traced during tracing, since the impls for MaybeUninit are empty and the vtable is saved when calling Cc::new
/*unsafe impl<T> Trace for MaybeUninit<T> {
/// This does nothing, since memory may be uninit.
#[inline(always)]
fn trace(&self, _: &mut Context<'_>) {}
}
impl<T> Finalize for MaybeUninit<T> {
/// This does nothing, since memory may be uninit.
#[inline(always)]
fn finalize(&self) {}
}*/
unsafe impl<T> Trace for PhantomData<T> {
#[inline(always)]
fn trace(&self, _: &mut Context<'_>) {}
}
impl<T> Finalize for PhantomData<T> {}
macro_rules! deref_trace {
($generic:ident; $this:ty; $($bound:tt)*) => {
unsafe impl<$generic: $($bound)* $crate::trace::Trace + 'static> $crate::trace::Trace for $this
{
#[inline]
fn trace(&self, ctx: &mut $crate::trace::Context<'_>) {
let deref: &$generic = <$this as ::core::ops::Deref>::deref(self);
<$generic as $crate::trace::Trace>::trace(deref, ctx);
}
}
impl<$generic: $($bound)* $crate::trace::Finalize + 'static> $crate::trace::Finalize for $this
{
#[inline]
fn finalize(&self) {
let deref: &$generic = <$this as ::core::ops::Deref>::deref(self);
<$generic as $crate::trace::Finalize>::finalize(deref);
}
}
}
}
macro_rules! deref_traces {
($($this:tt),*,) => {
$(
deref_trace!{T; $this<T>; ?::core::marker::Sized +}
)*
}
}
macro_rules! deref_traces_sized {
($($this:tt),*,) => {
$(
deref_trace!{T; $this<T>; }
)*
}
}
deref_traces! {
Box,
ManuallyDrop,
}
deref_traces_sized! {
AssertUnwindSafe,
}
unsafe impl<T: ?Sized + Trace + 'static> Trace for RefCell<T> {
#[inline]
fn trace(&self, ctx: &mut Context<'_>) {
if let Ok(borrow) = self.try_borrow() {
borrow.trace(ctx);
}
}
}
impl<T: ?Sized + Finalize + 'static> Finalize for RefCell<T> {
#[inline]
fn finalize(&self) {
if let Ok(borrow) = self.try_borrow() {
borrow.finalize();
}
}
}
unsafe impl<T: Trace + 'static> Trace for Option<T> {
#[inline]
fn trace(&self, ctx: &mut Context<'_>) {
if let Some(inner) = self {
inner.trace(ctx);
}
}
}
impl<T: Finalize + 'static> Finalize for Option<T> {
#[inline]
fn finalize(&self) {
if let Some(value) = self {
value.finalize();
}
}
}
unsafe impl<R: Trace + 'static, E: Trace + 'static> Trace for Result<R, E> {
#[inline]
fn trace(&self, ctx: &mut Context<'_>) {
match self {
Ok(ok) => ok.trace(ctx),
Err(err) => err.trace(ctx),
}
}
}
impl<R: Finalize + 'static, E: Finalize + 'static> Finalize for Result<R, E> {
#[inline]
fn finalize(&self) {
match self {
Ok(value) => value.finalize(),
Err(err) => err.finalize(),
}
}
}
unsafe impl<T: Trace + 'static, const N: usize> Trace for [T; N] {
#[inline]
fn trace(&self, ctx: &mut Context<'_>) {
for elem in self {
elem.trace(ctx);
}
}
}
impl<T: Finalize + 'static, const N: usize> Finalize for [T; N] {
#[inline]
fn finalize(&self) {
for elem in self {
elem.finalize();
}
}
}
unsafe impl<T: Trace + 'static> Trace for [T] {
#[inline]
fn trace(&self, ctx: &mut Context<'_>) {
for elem in self {
elem.trace(ctx);
}
}
}
impl<T: Finalize + 'static> Finalize for [T] {
#[inline]
fn finalize(&self) {
for elem in self {
elem.finalize();
}
}
}
unsafe impl<T: Trace + 'static> Trace for Vec<T> {
#[inline]
fn trace(&self, ctx: &mut Context<'_>) {
for elem in self {
elem.trace(ctx);
}
}
}
impl<T: Finalize + 'static> Finalize for Vec<T> {
#[inline]
fn finalize(&self) {
for elem in self {
elem.finalize();
}
}
}
macro_rules! tuple_finalize_trace {
($($args:ident),+) => {
#[allow(non_snake_case)]
unsafe impl<$($args),*> $crate::trace::Trace for ($($args,)*)
where $($args: $crate::trace::Trace + 'static),*
{
#[inline]
fn trace(&self, ctx: &mut $crate::trace::Context<'_>) {
match self {
($($args,)*) => {
$(
<$args as $crate::trace::Trace>::trace($args, ctx);
)*
}
}
}
}
#[allow(non_snake_case)]
impl<$($args),*> $crate::trace::Finalize for ($($args,)*)
where $($args: $crate::trace::Finalize + 'static),*
{
#[inline]
fn finalize(&self) {
match self {
($($args,)*) => {
$(
<$args as $crate::trace::Finalize>::finalize($args);
)*
}
}
}
}
}
}
macro_rules! tuple_finalize_traces {
($(($($args:ident),+);)*) => {
$(
tuple_finalize_trace!($($args),*);
)*
}
}
tuple_finalize_traces! {
(A);
(A, B);
(A, B, C);
(A, B, C, D);
(A, B, C, D, E);
(A, B, C, D, E, F);
(A, B, C, D, E, F, G);
(A, B, C, D, E, F, G, H);
(A, B, C, D, E, F, G, H, I);
(A, B, C, D, E, F, G, H, I, J);
(A, B, C, D, E, F, G, H, I, J, K);
(A, B, C, D, E, F, G, H, I, J, K, L);
}