1//! Cached field values: `#[r_data(cache)]` (#2271).
2//!
3//! The R getter of a struct field converts a clone of the Rust value on every
4//! read, so a large field costs a copy and a conversion per `$`. The getter of
5//! a field marked `#[r_data(cache)]` keeps the R object its first read makes,
6//! and later reads return that same object, until the value is borrowed
7//! exclusively.
8//!
9//! # Storage
10//!
11//! The cached objects live in the pool that roots owning `ExternalPtr`
12//! handles ([`root_owned`]), and their keys in a table keyed by the address of
13//! the value's `RefCell<T>`: one entry per object, one slot per cached field,
14//! empty until the field's first read. Not in the pointer's `prot` list, which
15//! `saveRDS()` writes: a save never carries a cache, and an object
16//! `readRDS()` brings back starts with none. A clone has a `RefCell` of its
17//! own, so it starts with none too.
18//!
19//! # Invalidation
20//!
21//! Every exclusive borrow of the value drops its entry
22//! ([`borrow_value_mut`](super::borrow_value_mut)): a `&mut self` method, a
23//! `&mut T` or [`ExternalPtrMut`](super::ExternalPtrMut) argument,
24//! [`ExternalPtr::borrow_mut`](super::ExternalPtr::borrow_mut), an R setter,
25//! a consuming `self` method, `into_inner`. The check is a constant
26//! ([`TypedExternal::CACHED_FIELD_COUNT`](super::TypedExternal::CACHED_FIELD_COUNT)),
27//! so a type without cached fields pays one constant branch. While the borrow
28//! lasts, a read can't fill the entry again: the getter's shared borrow
29//! raises `miniextendr_borrow_conflict`. The finalizer of such a type drops
30//! the entry before it frees the value ([`super::finalizer`]), so a later
31//! value at the same address never finds it.
32//!
33//! A change no exclusive borrow covers is not seen, and the field reads its
34//! old value: interior mutability behind `&self` (a `Cell`, `RefCell`,
35//! `Mutex` or atomic in the field, or anything it reaches), and the ALTREP
36//! `data1` paths that read and write without a borrow
37//! ([`as_mut_unchecked`](super::ExternalPtr::as_mut_unchecked)). The value
38//! is stale, not unsound: the cached object is a complete R value, rooted
39//! until its entry drops.
40//!
41//! # Sharing
42//!
43//! A read returns the cached object itself, so two reads give the same R
44//! object. It is marked not mutable (`MARK_NOT_MUTABLE`): R code that
45//! modifies it (`v[1] <- 0`, `attr(v, "a") <- 1`) copies it first. C code that
46//! writes its argument in place (`data.table::set()`) changes it for every
47//! later read, as it would any shared R object.
4849use std::any::Any;
50use std::cell::RefCell;
51use std::collections::HashMap;
5253use super::{pooled, root_owned, unroot_owned};
54use crate::SEXP;
55use crate::protect_pool::ProtectKey;
56use crate::sys::MARK_NOT_MUTABLE;
5758#[doc =
r" The cached field values of each object that has any, by the address"]
#[doc =
r" of its value's `RefCell`: the pool key of each cached field's value,"]
#[doc = r" in cache-index order, `None` until the field's first read."]
const FIELD_CACHES:
::std::thread::LocalKey<RefCell<HashMap<usize,
Box<[Option<ProtectKey>]>>>> =
{
#[allow(mismatched_lifetime_syntaxes)]
#[inline]
fn __rust_std_internal_init_fn(_lifetime_elision:
::std::marker::PhantomData<&'static ()>)
-> RefCell<HashMap<usize, Box<[Option<ProtectKey>]>>> {
RefCell::new(HashMap::new())
}
unsafe {
::std::thread::LocalKey::new(const {
if ::std::mem::needs_drop::<RefCell<HashMap<usize,
Box<[Option<ProtectKey>]>>>>() {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<RefCell<HashMap<usize,
Box<[Option<ProtectKey>]>>>, ()> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
|| __rust_std_internal_init_fn(::std::marker::PhantomData))
}
} else {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<RefCell<HashMap<usize,
Box<[Option<ProtectKey>]>>>, !> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
|| __rust_std_internal_init_fn(::std::marker::PhantomData))
}
}
})
}
};thread_local! {
59/// The cached field values of each object that has any, by the address
60 /// of its value's `RefCell`: the pool key of each cached field's value,
61 /// in cache-index order, `None` until the field's first read.
62static FIELD_CACHES: RefCell<HashMap<usize, Box<[Option<ProtectKey>]>>> =
63 RefCell::new(HashMap::new());
64}6566/// The table key of a stored value: the address of its `RefCell`.
67#[inline]
68pub(super) fn cell_key<T>(cell: &RefCell<T>) -> usize {
69 std::ptr::from_ref(cell).addr()
70}
7172/// The table key of the value an `ExternalPtr`'s address holds: the
73/// `RefCell<T>` its `Box<dyn Any>` points to, so the same as [`cell_key`] of
74/// that cell.
75#[inline]
76pub(super) fn stored_key(stored: &dyn Any) -> usize {
77 std::ptr::from_ref(stored).cast::<()>().addr()
78}
7980/// The cached value of the field at `index` of the value at `key`, if a read
81/// stored one since the value's last exclusive borrow.
82#[inline]
83pub(super) fn cached(key: usize, index: usize) -> Option<SEXP> {
84let pool_key =
85 FIELD_CACHES.with_borrow(|caches| caches.get(&key)?.get(index).copied().flatten())?;
86pooled(pool_key)
87}
8889/// Keeps `value`, the converted value of the field at `index` of the value
90/// at `key`, whose type has `count` cached fields. Marks it not mutable and
91/// roots it in the pool, which `value` may need no protection for (the pool
92/// keeps it reachable while it grows). On R's main thread.
93pub(super) fn store(key: usize, count: usize, index: usize, value: SEXP) {
94if true {
if !(index < count) {
{
::core::panicking::panic_fmt(format_args!("cache index {0} out of {1}",
index, count));
}
};
};debug_assert!(index < count, "cache index {index} out of {count}");
95// SAFETY: on R's main thread (the getter's); `value` is a live object.
96unsafe { MARK_NOT_MUTABLE(value) };
97let pool_key = root_owned(value);
98// No R call runs while the table is borrowed, so no finalizer can reach
99 // it meanwhile.
100let replaced = FIELD_CACHES.with_borrow_mut(|caches| {
101let slots = caches102 .entry(key)
103 .or_insert_with(|| ::alloc::vec::from_elem_global(None, count)vec![None; count].into_boxed_slice());
104slots[index].replace(pool_key)
105 });
106if let Some(old) = replaced {
107unroot_owned(old);
108 }
109}
110111/// Drops the cached field values of the value at `key`, if it has any.
112/// Allocates nothing and calls no R code, so a finalizer can call it.
113pub(super) fn forget(key: usize) {
114let Some(slots) = FIELD_CACHES.with_borrow_mut(|caches| caches.remove(&key)) else {
115return;
116 };
117for &pool_key in slots.iter().flatten() {
118 unroot_owned(pool_key);
119 }
120}