From 114d0ae3d47bd358101ca6250605554e953c4e8a Mon Sep 17 00:00:00 2001 From: Connor Horman Date: Wed, 21 Aug 2024 21:37:37 -0400 Subject: [PATCH] Add spec identifier syntax to interior-mutability.md --- src/interior-mutability.md | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/interior-mutability.md b/src/interior-mutability.md index dc79aac38..7f7178473 100644 --- a/src/interior-mutability.md +++ b/src/interior-mutability.md @@ -1,22 +1,38 @@ # Interior Mutability +r[interior-mut] + +r[interior-mut.intro] Sometimes a type needs to be mutated while having multiple aliases. In Rust this -is achieved using a pattern called _interior mutability_. A type has interior -mutability if its internal state can be changed through a [shared reference] to -it. This goes against the usual [requirement][ub] that the value pointed to by a +is achieved using a pattern called _interior mutability_. + +r[interior-mut.shared-ref] +A type has interior mutability if its internal state can be changed through a [shared reference] to +it. + +r[interior-mut.no-constraint] +This goes against the usual [requirement][ub] that the value pointed to by a shared reference is not mutated. +r[interior-mut.unsafe-cell] [`std::cell::UnsafeCell`] type is the only allowed way to disable this requirement. When `UnsafeCell` is immutably aliased, it is still safe to -mutate, or obtain a mutable reference to, the `T` it contains. As with all -other types, it is undefined behavior to have multiple `&mut UnsafeCell` +mutate, or obtain a mutable reference to, the `T` it contains. + +r[interior-mut.mut-unsafe-cell] +As with all other types, it is undefined behavior to have multiple `&mut UnsafeCell` aliases. +r[interior-mut.abstraction] Other types with interior mutability can be created by using `UnsafeCell` as a field. The standard library provides a variety of types that provide safe -interior mutability APIs. For example, [`std::cell::RefCell`] uses run-time -borrow checks to ensure the usual rules around multiple references. The -[`std::sync::atomic`] module contains types that wrap a value that is only +interior mutability APIs. + +r[interior-mut.ref-cell] +For example, [`std::cell::RefCell`] uses run-time borrow checks to ensure the usual rules around multiple references. + +r[interior-mut.atomic] +The [`std::sync::atomic`] module contains types that wrap a value that is only accessed with atomic operations, allowing the value to be shared and mutated across threads.