wiwi/rc/inner.rs
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 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
use crate::prelude_std::*;
use self::alloc_mod::Layout;
use self::atomic::Ordering::*;
#[repr(transparent)]
pub struct RcInner<C, V, S> {
ptr: ptr::NonNull<RcLayout<C, V, S>>
}
// if fields in this struct need to change,
// make sure to change `calc_layout` accordingly
#[repr(C)]
struct RcLayout<C, V, S> {
/// The reference counter (handles counting both strong and weak references)
counter: C,
/// The length of the slice stored in the unsized portion
slice_len: usize,
/// The value (the sized portion)
value: V,
/// A "header" of the unsized slice portion I guess?
///
/// This forces this struct to have an alignment of (at least) S's alignment,
/// while also not requiring that there be at least 1 S element in this struct
/// itself, and the slice will follow right after this field.
slice: [S; 0]
}
#[inline]
pub fn new_from_value<C, V>(value: V) -> RcInner<C, V, ()>
where
C: Counter
{
new_from_value_and_slice_copy(value, &[])
}
#[inline]
pub fn new_from_array_into_slice<C, S, const N: usize>(array: [S; N]) -> RcInner<C, (), S>
where
C: Counter
{
new_from_value_and_array_into_slice((), array)
}
#[inline]
pub fn new_from_slice_clone<C, S>(slice: &[S]) -> RcInner<C, (), S>
where
C: Counter,
S: Clone
{
new_from_value_and_slice_clone((), slice)
}
#[inline]
pub fn new_from_slice_copy<C, S>(slice: &[S]) -> RcInner<C, (), S>
where
C: Counter,
S: Copy
{
new_from_value_and_slice_copy((), slice)
}
#[inline]
pub fn new_from_value_and_array_into_slice<C, V, S, const N: usize>(value: V, array: [S; N]) -> RcInner<C, V, S>
where
C: Counter
{
let array = ManuallyDrop::new(array);
// SAFETY: we put the array into `ManuallyDrop`
unsafe { new_from_value_and_slice_copy_unchecked(value, &*array) }
}
#[inline]
pub fn new_from_value_and_slice_clone<C, V, S>(value: V, slice: &[S]) -> RcInner<C, V, S>
where
C: Counter,
S: Clone
{
let instance = alloc_instance::<_, _, S>(slice.len());
// SAFETY:
// - instance just allocated in statement above
// - because just allocated, we must have exclusive reference to `instance`
// - reference is used just for this single `write` statement and
// dropped immediately after
unsafe { value_uninit(instance).write(value); }
// SAFETY: instance just allocated in statement above
let ptr = unsafe { slice_thin_ptr(instance).as_ptr() };
slice.iter().enumerate().for_each(|(i, s)| {
// SAFETY: `ptr` is writeable for `slice.len()` elements
let ptr = unsafe { ptr.add(i) };
// SAFETY: see above
unsafe { ptr.write(s.clone()) }
});
instance
}
#[inline]
pub fn new_from_value_and_slice_copy<C, V, S>(value: V, slice: &[S]) -> RcInner<C, V, S>
where
C: Counter,
S: Copy
{
// SAFETY: `S: Copy` enforced by trait bound
unsafe { new_from_value_and_slice_copy_unchecked(value, slice) }
}
/// # Safety
///
/// The provided slice should either contain elements that implement [`Copy`],
/// or the input slice should be prevented from dropping to avoid double
/// dropping elements.
#[inline]
unsafe fn new_from_value_and_slice_copy_unchecked<C, V, S>(value: V, slice: &[S]) -> RcInner<C, V, S>
where
C: Counter
{
let instance = alloc_instance(slice.len());
// SAFETY:
// - instance just allocated in statement above
// - because just allocated, we must have exclusive reference to `instance`
// - reference is used just for this single `write` statement and
// dropped immediately after
unsafe { value_uninit(instance).write(value); }
// SAFETY: instance just allocated in statement above
let ptr = unsafe { slice_thin_ptr(instance).as_ptr() };
// SAFETY: `ptr` is writeable for `slice.len()` elements
unsafe {
ptr::copy_nonoverlapping(
slice.as_ptr(),
ptr,
slice.len()
)
}
instance
}
/// Initialise a new instance with the provided length
///
/// The instance returned will have fields `counter` and `slice_length` fields
/// initialised. Counter is set to 1 strong and 1 weak according to contract of
/// [`Counter`]. Caller is responsible for initialising the `value` and `slice`
/// fields.
#[inline]
fn alloc_instance<C, V, S>(slice_len: usize) -> RcInner<C, V, S>
where
C: Counter
{
let layout = calc_layout::<C, V, S>(slice_len);
// SAFETY: `calc_layout` never returns layout with 0 size
let ptr = unsafe { alloc(layout) };
let Some(ptr) = ptr::NonNull::new(ptr.cast()) else {
alloc_mod::handle_alloc_error(layout)
};
let instance = RcInner { ptr };
// we can fill in counter since we know the type of counter already
// SAFETY:
// - instance just allocated in statements above
// - because just allocated, we must have exclusive reference to `instance`
// - reference is used just for this single `write` statement and
// dropped immediately after
unsafe { counter_uninit(instance).write(C::new()); }
// we can fill in length since that will never change
// SAFETY: same as above
unsafe { slice_len_uninit(instance).write(slice_len); }
instance
}
/// Drop the value and slice contents of the provided instance
///
/// # Safety
///
/// This instance must be fully initialised, and this must be the first time
/// this function is called on this particular `instance`.
#[inline]
pub unsafe fn drop_instance<C, V, S>(instance: RcInner<C, V, S>)
where
C: Counter
{
// SAFETY: caller promises `instance` is fully initialised
let slice_ref = unsafe { slice_ref(instance) };
#[expect(
clippy::as_conversions,
reason = "slice ptr cast without casting methods available (yet?)"
)]
let slice_ptr = slice_ref as *const [S] as *mut [S];
// SAFETY: see above
unsafe { ptr::drop_in_place(slice_ptr) }
// SAFETY: caller promises `instance` is fully initialised
let value_ptr = unsafe { value_ptr(instance).as_ptr() };
// SAFETY: see above
unsafe { ptr::drop_in_place(value_ptr) }
}
/// Drop the counter and deallocate the backing allocation of the provided instance
///
/// # Safety
///
/// This instance must be in the partially initialised state following a call to
/// [`drop_instance`], and this must be the first time this function is called on
/// this particular `instance`. This may be called on an instance that is still
/// fully initialised (ie. [`drop_instance`] has not been called on it), but
/// that is equivalent to leaking the value and slice fields, and is almost
/// certainly incorrect.
#[inline]
pub unsafe fn dealloc_instance<C, V, S>(instance: RcInner<C, V, S>)
where
C: Counter
{
// SAFETY: caller promises `counter` is initialised
let counter_ptr = unsafe { counter_ptr(instance).as_ptr() };
// SAFETY: see above
unsafe { ptr::drop_in_place(counter_ptr) }
// SAFETY: caller promises `slice_len` is initialised
let slice_len = unsafe { slice_len(instance) };
let layout = calc_layout::<C, V, S>(slice_len);
// SAFETY: see above
unsafe { dealloc(instance.ptr.as_ptr().cast(), layout) }
}
/// Calculate the layout to allocate a new instance with the specified counter,
/// value type, slice type, and slice length
// TODO: make this fn `const` when `feature(const_alloc_layout)` is stable
#[inline]
fn calc_layout<C, V, S>(slice_len: usize) -> Layout {
fn inner<C, V, S>(slice_len: usize) -> Option<Layout> {
// if the size of `V` is not an even multiple of the align of the rest of the
// struct (max of `usize` and `C`), and align of `S` is less than or equal to
// align of `V`, the `slice` field will be at the end of `V` and there will be
// some padding after it. I don't think this causes UB, but it will allocate
// and use more memory than is necessary in these edge cases. So, we calculate
// it manually (we can do this because `repr(C)`), to attach the real layout
// of the slice where `slice` would have been, and place some additional checks
// in debug to assert it would have been the same as just using `Layout::new`.
let mut layout = Layout::new::<()>();
macro_rules! extend_layout {
($field_name:ident, $layout:expr) => {
let new = layout
.extend($layout)
.ok()?;
debug_assert_eq!(
mem::offset_of!(RcLayout<C, V, S>, $field_name),
new.1
);
layout = new.0;
}
}
extend_layout!(counter, Layout::new::<C>());
extend_layout!(slice_len, Layout::new::<usize>());
extend_layout!(value, Layout::new::<V>());
extend_layout!(slice, Layout::array::<S>(slice_len).ok()?);
Some(layout.pad_to_align())
}
inner::<C, V, S>(slice_len).expect("rc layout calculation failed")
}
/// # Safety
///
/// - The provided `instance` must not have been deallocated
#[inline]
unsafe fn counter_ptr<C, V, S>(instance: RcInner<C, V, S>) -> ptr::NonNull<C>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { &raw const (*instance.ptr.as_ptr()).counter };
// SAFETY: ptr is guaranteed to be nonnull
unsafe { ptr::NonNull::new_unchecked(ptr.cast_mut()) }
}
/// # Safety
///
/// - The provided `instance` must not have been deallocated
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
/// - The returned reference must be the only mut reference into `counter` (exclusive borrow)
#[inline]
unsafe fn counter_uninit<'h, C, V, S>(instance: RcInner<C, V, S>) -> &'h mut MaybeUninit<C>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { counter_ptr(instance).as_ptr() };
// SAFETY: ptr is valid, and `MaybeUninit` has same ABI as inner type
unsafe { &mut *ptr.cast() }
}
/// # Safety
///
/// - The provided `instance` must not have been deallocated
/// - The provided `instance` must have field `counter` already initialised
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
#[inline]
pub unsafe fn counter_ref<'h, C, V, S>(instance: RcInner<C, V, S>) -> &'h C
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { counter_ptr(instance).as_ptr() };
// SAFETY: ptr is valid
unsafe { &*ptr }
}
/// # Safety
///
/// - The provided `instance` must not have been deallocated
#[inline]
unsafe fn slice_len_ptr<C, V, S>(instance: RcInner<C, V, S>) -> ptr::NonNull<usize>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { &raw const (*instance.ptr.as_ptr()).slice_len };
// SAFETY: ptr is guaranteed to be nonnull
unsafe { ptr::NonNull::new_unchecked(ptr.cast_mut()) }
}
/// # Safety
///
/// - The provided `instance` must not have been deallocated
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
/// - The returned reference must be the only mut reference into `slice_len` (exclusive borrow)
#[inline]
unsafe fn slice_len_uninit<'h, C, V, S>(instance: RcInner<C, V, S>) -> &'h mut MaybeUninit<usize>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { slice_len_ptr(instance).as_ptr() };
// SAFETY: ptr is valid, and `MaybeUninit` has same ABI as inner type
unsafe { &mut *ptr.cast() }
}
/// # Safety
///
/// - The provided `instance` must not have been deallocated
/// - The provided `instance` must have field `slice_len` already initialised
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
#[inline]
unsafe fn slice_len<C, V, S>(instance: RcInner<C, V, S>) -> usize
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { slice_len_ptr(instance).as_ptr() };
// SAFETY: ptr is valid
unsafe { *ptr }
}
/// # Safety
///
/// - The provided `instance` must not have been dropped or deallocated
#[inline]
unsafe fn value_ptr<C, V, S>(instance: RcInner<C, V, S>) -> ptr::NonNull<V>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { &raw const (*instance.ptr.as_ptr()).value };
// SAFETY: ptr is guaranteed to be nonnull
unsafe { ptr::NonNull::new_unchecked(ptr.cast_mut()) }
}
/// # Safety
///
/// - The provided `instance` must not have been dropped or deallocated
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
/// - The returned reference must be the only mut reference into `value` (exclusive borrow)
#[inline]
unsafe fn value_uninit<'h, C, V, S>(instance: RcInner<C, V, S>) -> &'h mut MaybeUninit<V>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { value_ptr(instance).as_ptr() };
// SAFETY: ptr is valid, and `MaybeUninit` has same ABI as inner type
unsafe { &mut *ptr.cast() }
}
/// # Safety
///
/// - The provided `instance` must not have been dropped or deallocated
/// - The provided `instance` must have field `value` already initialised
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
#[inline]
pub unsafe fn value_ref<'h, C, V, S>(instance: RcInner<C, V, S>) -> &'h V
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { value_ptr(instance).as_ptr() };
// SAFETY: ptr is valid
unsafe { &*ptr }
}
/// # Safety
///
/// - The provided `instance` must not have been dropped or deallocated
#[inline]
unsafe fn slice_thin_ptr<C, V, S>(instance: RcInner<C, V, S>) -> ptr::NonNull<S>
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { &raw const (*instance.ptr.as_ptr()).slice };
let ptr = ptr.cast::<S>();
// SAFETY: ptr is guaranteed to be nonnull
unsafe { ptr::NonNull::new_unchecked(ptr.cast_mut()) }
}
/// # Safety
///
/// - The provided `instance` must not have been dropped or deallocated
/// - The provided `instance` must have field `slice_len` already initialised
/// - The provided `instance` must have `slice_len` elements in `slice` already initialised
/// - `instance` must outlive `'h` (the lifetime of the returned reference)
#[inline]
pub unsafe fn slice_ref<'h, C, V, S>(instance: RcInner<C, V, S>) -> &'h [S]
where
C: Counter
{
// SAFETY: caller promises to uphold the requirements
let ptr = unsafe { slice_thin_ptr(instance).as_ptr() };
// SAFETY: caller promises to uphold the requirements
let slice_len = unsafe { slice_len(instance) };
// SAFETY: caller promises ptr is valid for at least `len` elements
unsafe { slice::from_raw_parts(ptr, slice_len) }
}
impl<C, V, S> Clone for RcInner<C, V, S>
where
C: Counter
{
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl<C, V, S> Copy for RcInner<C, V, S>
where
C: Counter
{}
/// Trait for structs that can count references
///
/// `wiwi` includes two implementations: one for single threaded access (akin
/// to `std`'s [`Rc`]), and the other for atomic multithreaded access (akin to
/// `std`'s [`Arc`]).
///
/// # Safety
///
/// You must implement this trait correctly (ie. functions must return correct
/// values), as values returned from functions are directly used to control the
/// allocation/deallocation of memory and dropping of values.
pub unsafe trait Counter: Sized {
/// Create a new couter with strong and weak count both set to 1
fn new() -> Self;
/// Get the strong reference count
fn strong_count(&self) -> usize;
/// Get the weak reference count
///
/// Don't subtract the "fake" weak reference that
/// is held by all the strong references.
fn weak_count(&self) -> usize;
/// Increment the strong count for creation of a new strong reference
fn inc_strong_for_new_ref(&self);
/// Decrements the strong count for dropping a reference, returning `true`
/// if there are no more strong pointers left (and the value and items in
/// the slice should be dropped)
fn dec_strong_for_drop(&self) -> bool;
/// Increments the weak count for creation of a new weak reference
fn inc_weak_for_new_ref(&self);
/// Decrements the weak count for dropping a reference, returning `true`
/// if there are no more weak pointers left (and the allocation should be
/// deallocated)
fn dec_weak_for_drop(&self) -> bool;
/// Increment the strong count if it is possible to upgrade a weak pointer
/// to strong, and return `true`, otherwise return `false` and do nothing
fn try_inc_strong_for_upgrade(&self) -> bool;
}
pub struct ThreadCounter {
strong: cell::Cell<usize>,
weak: cell::Cell<usize>,
_not_thread_safe: PhantomData<*const ()>
}
// SAFETY: we implement everything correctly
unsafe impl Counter for ThreadCounter {
#[inline]
fn new() -> Self {
Self {
strong: cell::Cell::new(1),
weak: cell::Cell::new(1),
_not_thread_safe: PhantomData
}
}
#[inline]
fn strong_count(&self) -> usize {
self.strong.get()
}
#[inline]
fn weak_count(&self) -> usize {
self.weak.get()
}
#[inline]
fn inc_strong_for_new_ref(&self) {
let old = self.strong.get();
self.strong.set(old + 1);
}
#[inline]
fn dec_strong_for_drop(&self) -> bool {
let old = self.strong.get();
self.strong.set(old - 1);
old == 1
}
#[inline]
fn inc_weak_for_new_ref(&self) {
let old = self.weak.get();
self.weak.set(old + 1);
}
#[inline]
fn dec_weak_for_drop(&self) -> bool {
let old = self.weak.get();
self.weak.set(old - 1);
old == 1
}
#[inline]
fn try_inc_strong_for_upgrade(&self) -> bool {
let old = self.strong.get();
let should_upgrade = old > 0;
if should_upgrade {
self.strong.set(old + 1)
}
should_upgrade
}
}
pub struct AtomicCounter {
strong: AtomicUsize,
weak: AtomicUsize
}
// SAFETY: we implement everything correctly
unsafe impl Counter for AtomicCounter {
#[inline]
fn new() -> Self {
Self {
strong: AtomicUsize::new(1),
weak: AtomicUsize::new(1)
}
}
#[inline]
fn strong_count(&self) -> usize {
self.strong.load(Relaxed)
}
#[inline]
fn weak_count(&self) -> usize {
self.weak.load(Relaxed)
}
#[inline]
fn inc_strong_for_new_ref(&self) {
self.strong.fetch_add(1, Relaxed);
}
#[inline]
fn dec_strong_for_drop(&self) -> bool {
let old = self.strong.fetch_sub(1, Release);
if old != 1 { return false }
atomic::fence(Acquire);
true
}
#[inline]
fn inc_weak_for_new_ref(&self) {
self.weak.fetch_add(1, Relaxed);
}
#[inline]
fn dec_weak_for_drop(&self) -> bool {
let old = self.weak.fetch_sub(1, Release);
if old != 1 { return false }
atomic::fence(Acquire);
true
}
#[inline]
fn try_inc_strong_for_upgrade(&self) -> bool {
self.strong
.fetch_update(
Acquire,
Relaxed,
|old| (old > 0).then(move || old + 1)
)
.is_ok()
}
}