swmr_cell/
lib.rs

1//! # SWMR Version-Based Single Object
2//!
3//! This crate provides a single-writer, multi-reader (SWMR) cell that supports
4//! concurrent wait-free reads and lock-free writes using version-based garbage collection.
5//!
6//! ## Core Concepts
7//!
8//! - **Single Object**: The `swmr_cell` library manages a single versioned object per `SwmrCell`.
9//! - **Version**: The version counter represents the state of the object. Each write increments the version.
10//! - **Pinning**: Readers pin the current version when they start reading, preventing the writer from reclaiming that version (and any older versions still visible to other readers) until they are done.
11//!
12//! ## Typical Usage
13//!
14//! ```rust
15//! use swmr_cell::SwmrCell;
16//!
17//! // 1. Create a new SWMR cell with an initial value
18//! let mut cell = SwmrCell::new(42i32);
19//!
20//! // 2. Create a local reader for this thread (or pass to another thread)
21//! let local = cell.local();
22//!
23//! // 3. Pin and read the value by dereferencing the guard
24//! let guard = local.pin();
25//! assert_eq!(*guard, 42);
26//! drop(guard);
27//!
28//! // 4. Writer updates the value
29//! cell.store(100i32);
30//!
31//! // 5. Read the new value
32//! let guard = local.pin();
33//! assert_eq!(*guard, 100);
34//! drop(guard);
35//!
36//! // 6. Manually collect garbage (optional, happens automatically too)
37//! cell.collect();
38//! ```
39#![cfg_attr(not(feature = "std"), no_std)]
40
41#[cfg(not(feature = "std"))]
42extern crate alloc;
43
44#[cfg(all(not(feature = "std"), test))]
45extern crate std;
46
47mod shim;
48
49#[cfg(test)]
50mod tests;
51use crate::shim::{
52    Arc, AtomicPtr, AtomicUsize, Box, Cell, Mutex, Ordering, Vec, VecDeque, heavy_barrier,
53    light_barrier,
54};
55use core::{fmt, marker::PhantomData, ops::Deref};
56
57/// Default threshold for automatic garbage reclamation (count of retired nodes).
58/// 自动垃圾回收的默认阈值(已退休节点的数量)。
59pub(crate) const AUTO_RECLAIM_THRESHOLD: usize = 16;
60
61/// Represents a reader that is not currently pinned to any version.
62/// 表示当前未被钉住到任何版本的读者。
63pub(crate) const INACTIVE_VERSION: usize = usize::MAX;
64
65/// A single-writer, multi-reader cell with version-based garbage collection.
66///
67/// `SwmrCell` provides safe concurrent access where one writer can update the value
68/// and multiple readers can read it concurrently. Readers access the value by
69/// creating a `LocalReader` and pinning it.
70///
71/// 单写多读单元,带有基于版本的垃圾回收。
72///
73/// `SwmrCell` 提供安全的并发访问,其中一个写入者可以更新值,
74/// 多个读者可以并发读取它。读者通过创建 `LocalReader` 并 pin 来访问值。
75pub struct SwmrCell<T: 'static> {
76    shared: Arc<SharedState<T>>,
77    garbage: GarbageSet<T>,
78    auto_reclaim_threshold: Option<usize>,
79}
80
81impl<T: 'static> SwmrCell<T> {
82    /// Create a new SWMR cell with default settings and the given initial value.
83    ///
84    /// 使用默认设置和给定的初始值创建一个新的 SWMR 单元。
85    #[inline]
86    pub fn new(data: T) -> Self {
87        Self::builder().build(data)
88    }
89
90    /// Returns a builder for configuring the SWMR cell.
91    ///
92    /// 返回用于配置 SWMR 单元的构建器。
93    #[inline]
94    pub fn builder() -> SwmrCellBuilder<T> {
95        SwmrCellBuilder {
96            auto_reclaim_threshold: Some(AUTO_RECLAIM_THRESHOLD),
97            marker: PhantomData::default(),
98        }
99    }
100
101    /// Create a new `LocalReader` for reading.
102    ///
103    /// Each thread should create its own `LocalReader` and reuse it.
104    /// `LocalReader` is `!Sync` and should not be shared between threads.
105    ///
106    /// 创建一个新的 `LocalReader` 用于读取。
107    /// 每个线程应该创建自己的 `LocalReader` 并重复使用。
108    /// `LocalReader` 是 `!Sync` 的,不应在线程之间共享。
109    #[inline]
110    pub fn local(&self) -> LocalReader<T> {
111        LocalReader::new(self.shared.clone())
112    }
113
114    /// Create a new `SwmrReader` that can be shared across threads.
115    ///
116    /// `SwmrReader` is `Sync` + `Clone` and acts as a factory for `LocalReader`s.
117    /// This is useful for distributing reader creation capability to other threads.
118    ///
119    /// 创建一个新的 `SwmrReader`,可以在线程之间共享。
120    /// `SwmrReader` 是 `Sync` + `Clone` 的,充当 `LocalReader` 的工厂。
121    /// 这对于将读者创建能力分发给其他线程很有用。
122    #[inline]
123    pub fn reader(&self) -> SwmrReader<T> {
124        SwmrReader {
125            shared: self.shared.clone(),
126        }
127    }
128
129    /// Store a new value, making it visible to readers.
130    /// The old value is retired and will be garbage collected.
131    ///
132    /// This operation increments the global version.
133    ///
134    /// 存储新值,使其对读者可见。
135    /// 旧值已退休,将被垃圾回收。
136    /// 此操作会增加全局版本。
137    pub fn store(&mut self, data: T) {
138        let new_ptr = Box::into_raw(Box::new(data));
139        let old_ptr = self.shared.ptr.swap(new_ptr, Ordering::Release);
140
141        // Increment global version.
142        // The old value belongs to the previous version (the one before this increment).
143        // 增加全局版本。
144        // 旧值属于前一个版本(此次增加之前的那个)。
145        let old_version = self.shared.global_version.fetch_add(1, Ordering::AcqRel);
146
147        if !old_ptr.is_null() {
148            // Safe because we just swapped it out and we own the writer
149            unsafe {
150                self.garbage.add(Box::from_raw(old_ptr), old_version);
151            }
152        }
153
154        // Auto-reclaim
155        if let Some(threshold) = self.auto_reclaim_threshold {
156            if self.garbage.len() > threshold {
157                self.collect();
158            }
159        }
160    }
161
162    /// Get a reference to the previously stored value, if any.
163    ///
164    /// Returns `None` if no previous value exists (i.e., only the initial value has been stored).
165    ///
166    /// **Note**: The previous value is guaranteed not to be garbage collected because
167    /// `collect()` uses `safety_limit = current_version - 2`, which always preserves
168    /// the most recently retired value (version = current_version - 1).
169    ///
170    /// This is useful for comparing the current value with the previous one,
171    /// or for implementing undo/rollback logic.
172    ///
173    /// 获取上一个存储值的引用(如果存在)。
174    ///
175    /// 如果不存在上一个值(即只存储了初始值),则返回 `None`。
176    ///
177    /// **注意**:上一个值保证不会被垃圾回收,因为 `collect()` 使用 `safety_limit = current_version - 2`,
178    /// 这始终保留最近退休的值(版本 = current_version - 1)。
179    ///
180    /// 这对于将当前值与上一个值进行比较,或实现撤销/回滚逻辑很有用。
181    ///
182    /// # Example
183    ///
184    /// ```rust
185    /// use swmr_cell::SwmrCell;
186    ///
187    /// let mut cell = SwmrCell::new(1);
188    /// assert!(cell.previous().is_none()); // No previous value yet
189    ///
190    /// cell.store(2);
191    /// assert_eq!(cell.previous(), Some(&1)); // Previous value is 1
192    ///
193    /// cell.store(3);
194    /// assert_eq!(cell.previous(), Some(&2)); // Previous value is 2
195    /// ```
196    #[inline]
197    pub fn previous(&self) -> Option<&T> {
198        self.garbage.back()
199    }
200
201    /// Get a reference to the current value (writer-only, no pinning required).
202    ///
203    /// This is only accessible from the writer thread since `SwmrCell` is `!Sync`.
204    ///
205    /// 获取当前值的引用(仅写者可用,无需 pin)。
206    /// 这只能从写者线程访问,因为 `SwmrCell` 是 `!Sync` 的。
207    #[inline]
208    pub fn get(&self) -> &T {
209        // Safety: We own the writer, and the current pointer is always valid.
210        // 安全性:我们拥有写者,当前指针始终有效。
211        unsafe { &*self.shared.ptr.load(Ordering::Acquire) }
212    }
213
214    /// Update the value using a closure.
215    ///
216    /// The closure receives the current value and should return the new value.
217    /// This is equivalent to `cell.store(f(cell.get().clone()))` but more ergonomic.
218    ///
219    /// 使用闭包更新值。
220    /// 闭包接收当前值并应返回新值。
221    /// 这相当于 `cell.store(f(cell.get().clone()))` 但更符合人体工程学。
222    #[inline]
223    pub fn update<F>(&mut self, f: F)
224    where
225        F: FnOnce(&T) -> T,
226    {
227        let new_value = f(self.get());
228        self.store(new_value);
229    }
230
231    /// Get the current global version.
232    ///
233    /// The version is incremented each time `store()` or `replace()` is called.
234    ///
235    /// 获取当前全局版本。
236    /// 每次调用 `store()` 或 `replace()` 时版本会增加。
237    #[inline]
238    pub fn version(&self) -> usize {
239        self.shared.global_version.load(Ordering::Acquire)
240    }
241
242    /// Get the number of retired objects waiting for garbage collection.
243    ///
244    /// 获取等待垃圾回收的已退休对象数量。
245    #[inline]
246    pub fn garbage_count(&self) -> usize {
247        self.garbage.len()
248    }
249
250    /// Manually trigger garbage collection.
251    /// 手动触发垃圾回收。
252    pub fn collect(&mut self) {
253        // In this design, we don't necessarily advance the version just for collection.
254        // But we need to find min_active_version.
255
256        let current_version = self.shared.global_version.load(Ordering::Acquire);
257
258        // Safety limit ensures we never reclaim the most recent retired value (previous).
259        // The most recent retired value has version = current_version - 1.
260        // With safety_limit = current_version - 2, we only reclaim versions < current_version - 2,
261        // so the previous value (version = current_version - 1) is always preserved.
262        // 安全限制确保我们永远不会回收最近退休的值(previous)。
263        // 最近退休的值的版本 = current_version - 1。
264        // 使用 safety_limit = current_version - 2,我们只回收版本 < current_version - 2 的,
265        // 因此上一个值(版本 = current_version - 1)始终被保留。
266        let safety_limit = current_version.saturating_sub(2);
267
268        let mut min_active = current_version;
269
270        // Force memory visibility of any preceding stores and serialize reader streams.
271        // This ensures we see any active readers that have completed their light_barrier.
272        heavy_barrier();
273
274        let mut shared_readers = self.shared.readers.lock();
275
276        for arc_slot in shared_readers.iter() {
277            let version = arc_slot.active_version.load(Ordering::Acquire);
278            if version != INACTIVE_VERSION {
279                min_active = min_active.min(version);
280            }
281        }
282
283        // Clean up dead reader slots (strong_count == 1 means only SharedState holds it)
284        // 清理死读者槽(strong_count == 1 表示只有 SharedState 持有它)
285        shared_readers.retain(|arc_slot| Arc::strong_count(arc_slot) > 1);
286
287        drop(shared_readers);
288
289        let reclaim_threshold = min_active.min(safety_limit);
290
291        self.shared
292            .min_active_version
293            .store(reclaim_threshold, Ordering::Release);
294
295        self.garbage.collect(reclaim_threshold, current_version);
296    }
297}
298
299/// A handle for creating `LocalReader`s that can be shared across threads.
300///
301/// Unlike `LocalReader`, which is `!Sync` and bound to a single thread,
302/// `SwmrReader` is `Sync` and `Clone`. It holds a reference to the shared state
303/// but does not register a reader slot until `local()` is called.
304///
305/// 可以跨线程共享的用于创建 `LocalReader` 的句柄。
306///
307/// 与 `!Sync` 且绑定到单个线程的 `LocalReader` 不同,
308/// `SwmrReader` 是 `Sync` 和 `Clone` 的。它持有对共享状态的引用,
309/// 但直到调用 `local()` 时才注册读者槽。
310pub struct SwmrReader<T: 'static> {
311    shared: Arc<SharedState<T>>,
312}
313
314impl<T: 'static> SwmrReader<T> {
315    /// Create a new `LocalReader` for the current thread.
316    ///
317    /// 为当前线程创建一个新的 `LocalReader`。
318    #[inline]
319    pub fn local(&self) -> LocalReader<T> {
320        LocalReader::new(self.shared.clone())
321    }
322}
323
324impl<T: 'static> Clone for SwmrReader<T> {
325    #[inline]
326    fn clone(&self) -> Self {
327        Self {
328            shared: self.shared.clone(),
329        }
330    }
331}
332
333impl<T: 'static> fmt::Debug for SwmrReader<T> {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        f.debug_struct("SwmrReader").finish()
336    }
337}
338
339/// A builder for configuring and creating a SWMR cell.
340///
341/// 用于配置和创建 SWMR 单元的构建器。
342pub struct SwmrCellBuilder<T> {
343    auto_reclaim_threshold: Option<usize>,
344    marker: PhantomData<T>,
345}
346
347impl<T: 'static> SwmrCellBuilder<T> {
348    /// Sets the threshold for automatic garbage reclamation.
349    ///
350    /// When the number of retired objects exceeds this threshold,
351    /// garbage collection is triggered automatically during `store`.
352    ///
353    /// Set to `None` to disable automatic reclamation.
354    /// Default is `Some(64)`.
355    ///
356    /// 设置自动垃圾回收的阈值。
357    /// 当已退休对象的数量超过此阈值时,将在 `store` 期间自动触发垃圾回收。
358    /// 设置为 `None` 以禁用自动回收。
359    /// 默认为 `Some(64)`。
360    #[inline]
361    pub fn auto_reclaim_threshold(mut self, threshold: Option<usize>) -> Self {
362        self.auto_reclaim_threshold = threshold;
363        self
364    }
365
366    /// Creates a new SWMR cell with the configured settings and initial value.
367    ///
368    /// 使用配置的设置和初始值创建一个新的 SWMR 单元。
369    pub fn build(self, data: T) -> SwmrCell<T> {
370        let shared = Arc::new(SharedState {
371            global_version: AtomicUsize::new(0),
372            min_active_version: AtomicUsize::new(0),
373            ptr: AtomicPtr::new(Box::into_raw(Box::new(data))),
374            readers: Mutex::new(Vec::new()),
375        });
376
377        SwmrCell {
378            shared,
379            garbage: GarbageSet::new(),
380            auto_reclaim_threshold: self.auto_reclaim_threshold,
381        }
382    }
383}
384
385/// Manages retired objects and their reclamation.
386///
387/// This struct encapsulates the logic for:
388/// - Storing retired objects in version-ordered queue.
389/// - Reclaiming objects when they are safe to delete.
390///
391/// 管理已退休对象及其回收。
392///
393/// 此结构体封装了以下逻辑:
394/// - 将已退休对象存储在按版本排序的队列中。
395/// - 当对象可以安全删除时进行回收。
396struct GarbageSet<T> {
397    /// Queue of garbage items, ordered by version.
398    /// Each element is (version, node).
399    queue: VecDeque<(usize, Box<T>)>,
400}
401
402impl<T> GarbageSet<T> {
403    /// Create a new empty garbage set.
404    /// 创建一个新的空垃圾集合。
405    fn new() -> Self {
406        Self {
407            queue: VecDeque::new(),
408        }
409    }
410
411    /// Get the total number of retired objects.
412    /// 获取已退休对象的总数。
413    #[inline]
414    fn len(&self) -> usize {
415        self.queue.len()
416    }
417
418    /// Get a reference to the most recently retired object (the previous value).
419    /// 获取最近退休对象(上一个值)的引用。
420    #[inline]
421    fn back(&self) -> Option<&T> {
422        self.queue.back().map(|(_, boxed)| boxed.as_ref())
423    }
424
425    /// Add a retired node to the set for the current version.
426    ///
427    /// 将已退休节点添加到当前版本的集合中。
428    #[inline]
429    fn add(&mut self, node: Box<T>, current_version: usize) {
430        self.queue.push_back((current_version, node));
431    }
432
433    /// Reclaim garbage that is safe to delete.
434    ///
435    /// Garbage from versions older than `min_active_version` is dropped.
436    ///
437    /// 回收可以安全删除的垃圾。
438    ///
439    /// 来自比 `min_active_version` 更旧的版本的垃圾将被 drop。
440    #[inline]
441    fn collect(&mut self, min_active_version: usize, _current_version: usize) {
442        // We reclaim everything that is strictly older than min_active_version.
443        // If min_active_version == current_version, then everything (all < current_version) is reclaimed.
444        while let Some((version, _)) = self.queue.front() {
445            if *version >= min_active_version {
446                break;
447            }
448            self.queue.pop_front(); // Box<T> is dropped here
449        }
450    }
451}
452
453/// A slot allocated for a reader thread to record its active version.
454///
455/// Cache-aligned to prevent false sharing between readers.
456///
457/// 为读者线程分配的槽,用于记录其活跃版本。
458/// 缓存对齐以防止读者之间的伪共享。
459#[derive(Debug)]
460#[repr(align(64))]
461pub(crate) struct ReaderSlot {
462    /// The version currently being accessed by the reader, or INACTIVE_VERSION.
463    /// 读者当前访问的版本,或 INACTIVE_VERSION。
464    pub(crate) active_version: AtomicUsize,
465}
466
467/// Global shared state for the version GC domain.
468///
469/// Contains the global version, the minimum active version, the data pointer, and the list of reader slots.
470///
471/// version GC 域的全局共享状态。
472/// 包含全局版本、最小活跃版本、数据指针和读者槽列表。
473#[repr(align(64))]
474pub(crate) struct SharedState<T: 'static> {
475    /// The global monotonic version counter.
476    /// 全局单调版本计数器。
477    pub(crate) global_version: AtomicUsize,
478    /// The minimum version among all active readers (cached for performance).
479    /// 所有活跃读者中的最小版本(为性能而缓存)。
480    pub(crate) min_active_version: AtomicUsize,
481    /// The current data pointer.
482    /// 当前数据指针。
483    pub(crate) ptr: AtomicPtr<T>,
484    /// List of all registered reader slots. Protected by a Mutex.
485    /// 所有注册读者槽的列表。由 Mutex 保护。
486    pub(crate) readers: Mutex<Vec<Arc<ReaderSlot>>>,
487}
488
489impl<T: 'static> Drop for SharedState<T> {
490    fn drop(&mut self) {
491        // Drop the current value held by ptr to avoid leaking it.
492        // Drop ptr 持有的当前值,以避免泄漏。
493        let ptr = self.ptr.load(Ordering::Acquire);
494        if !ptr.is_null() {
495            unsafe {
496                drop(Box::from_raw(ptr));
497            }
498        }
499    }
500}
501
502/// A reader thread's local version state.
503///
504/// Each reader thread should create exactly one `LocalReader` via `SwmrCell::local()`.
505/// It is `!Sync` (due to `Cell`) and must be stored per-thread.
506///
507/// The `LocalReader` is used to:
508/// - Pin the thread to the current version via `pin()`.
509/// - Obtain a `PinGuard` that protects access to values and can be dereferenced.
510///
511/// **Thread Safety**: `LocalReader` is not `Sync` and must be used by only one thread.
512///
513/// 读者线程的本地版本状态。
514/// 每个读者线程应该通过 `SwmrCell::local()` 创建恰好一个 `LocalReader`。
515/// 它是 `!Sync` 的(因为 `Cell`),必须在每个线程中存储。
516/// `LocalReader` 用于:
517/// - 通过 `pin()` 将线程钉住到当前版本。
518/// - 获取保护对值访问的 `PinGuard`,可以解引用来读取值。
519/// **线程安全性**:`LocalReader` 不是 `Sync` 的,必须仅由一个线程使用。
520pub struct LocalReader<T: 'static> {
521    slot: Arc<ReaderSlot>,
522    shared: Arc<SharedState<T>>,
523    pin_count: Cell<usize>,
524}
525
526impl<T: 'static> LocalReader<T> {
527    fn new(shared: Arc<SharedState<T>>) -> Self {
528        let slot = Arc::new(ReaderSlot {
529            active_version: AtomicUsize::new(INACTIVE_VERSION),
530        });
531
532        // Register the reader immediately in the shared readers list
533        shared.readers.lock().push(Arc::clone(&slot));
534
535        LocalReader {
536            slot,
537            shared,
538            pin_count: Cell::new(0),
539        }
540    }
541
542    /// Pin this thread to the current version.
543    ///
544    /// Returns a `PinGuard` that keeps the thread pinned for its lifetime.
545    /// The guard can be dereferenced to access the current value.
546    ///
547    /// **Reentrancy**: This method is reentrant. Multiple calls can be nested, and the thread
548    /// remains pinned until all returned guards are dropped. You can also clone a guard to create
549    /// additional references: `let guard2 = guard1.clone();`
550    ///
551    /// **Example**:
552    /// ```ignore
553    /// let local = cell.local();
554    /// let guard1 = local.pin();
555    /// let value = *guard1;  // Dereference to read
556    /// let guard2 = local.pin();  // Reentrant call
557    /// let guard3 = guard1.clone();     // Clone for nested scope
558    /// // Thread remains pinned until all three guards are dropped
559    /// ```
560    ///
561    /// While pinned, the thread is considered "active" at a particular version,
562    /// and the garbage collector will not reclaim data from that version.
563    ///
564    /// 将此线程钉住到当前版本。
565    ///
566    /// 返回一个 `PinGuard`,在其生命周期内保持线程被钉住。
567    /// 可以解引用该守卫来访问当前值。
568    ///
569    /// **可重入性**:此方法是可重入的。多个调用可以嵌套,线程在所有返回的守卫被 drop 之前保持被钉住。
570    /// 你也可以克隆一个守卫来创建额外的引用:`let guard2 = guard1.clone();`
571    ///
572    /// **示例**:
573    /// ```ignore
574    /// let local = cell.local();
575    /// let guard1 = local.pin();
576    /// let value = *guard1;  // 解引用来读取
577    /// let guard2 = local.pin();  // 可重入调用
578    /// let guard3 = guard1.clone();     // 克隆用于嵌套作用域
579    /// // 线程保持被钉住直到所有三个守卫被 drop
580    /// ```
581    ///
582    /// 当被钉住时,线程被认为在特定版本"活跃",垃圾回收器不会回收该版本的数据。
583    /// Check if this reader is currently pinned.
584    ///
585    /// 检查此读者当前是否被 pin。
586    #[inline]
587    pub fn is_pinned(&self) -> bool {
588        self.pin_count.get() > 0
589    }
590
591    /// Get the current global version.
592    ///
593    /// Note: This returns the global version, not the pinned version.
594    /// To get the pinned version, use `PinGuard::version()`.
595    ///
596    /// 获取当前全局版本。
597    /// 注意:这返回全局版本,而不是 pin 的版本。
598    /// 要获取 pin 的版本,请使用 `PinGuard::version()`。
599    #[inline]
600    pub fn version(&self) -> usize {
601        self.shared.global_version.load(Ordering::Acquire)
602    }
603
604    #[inline]
605    pub fn pin(&self) -> PinGuard<'_, T> {
606        let pin_count = self.pin_count.get();
607
608        // Reentrant pin: the version is already protected by the outer pin.
609        // Just increment count and reuse the existing pinned pointer.
610        // 可重入 pin:版本已经被外层 pin 保护。
611        // 只需增加计数并复用现有的 pinned 指针。
612        if pin_count > 0 {
613            self.pin_count.set(pin_count + 1);
614
615            // Load the pointer that corresponds to our already-pinned version.
616            // Since we're reentrant, we should see the same or newer pointer.
617            // 加载与我们已 pin 版本对应的指针。
618            // 由于是可重入的,我们应该看到相同或更新的指针。
619            let ptr = self.shared.ptr.load(Ordering::Acquire);
620            let version = self.slot.active_version.load(Ordering::Acquire);
621
622            return PinGuard {
623                local: self,
624                ptr,
625                version,
626            };
627        }
628
629        // First pin: need to acquire a version and validate it.
630        // 首次 pin:需要获取版本并验证。
631        loop {
632            let current_version = self.shared.global_version.load(Ordering::Acquire);
633
634            self.slot
635                .active_version
636                .store(current_version, Ordering::Release);
637
638            // Light barrier coupled with Writer's Heavy barrier prevents Store-Load reordering.
639            light_barrier();
640
641            // Check if our version is still valid (not yet reclaimed).
642            // 检查我们的版本是否仍然有效(尚未被回收)。
643            let min_active = self.shared.min_active_version.load(Ordering::Acquire);
644
645            if current_version >= min_active {
646                break;
647            }
648
649            // Version was reclaimed between our read and store.
650            // Retry with a fresh version.
651            // 版本在我们读取和存储之间被回收了。
652            // 用新版本重试。
653            core::hint::spin_loop();
654        }
655
656        self.pin_count.set(1);
657
658        // Capture the pointer and version at pin time for snapshot semantics.
659        // 在 pin 时捕获指针和版本以实现快照语义。
660        let ptr = self.shared.ptr.load(Ordering::Acquire);
661        let version = self.slot.active_version.load(Ordering::Acquire);
662
663        PinGuard {
664            local: self,
665            ptr,
666            version,
667        }
668    }
669
670    /// Create a new `SwmrReader` from this `LocalReader`.
671    ///
672    /// `SwmrReader` is `Sync` + `Clone` and acts as a factory for `LocalReader`s.
673    /// This is equivalent to calling `swmr_cell.reader()`, but using the `LocalReader`'s reference to the shared state.
674    ///
675    /// 从此 `LocalReader` 创建一个新的 `SwmrReader`。
676    /// `SwmrReader` 是 `Sync` + `Clone` 的,充当 `LocalReader` 的工厂。
677    /// 这相当于调用 `swmr_cell.reader()`,但使用 `LocalReader` 对共享状态的引用。
678    #[inline]
679    pub fn share(&self) -> SwmrReader<T> {
680        SwmrReader {
681            shared: self.shared.clone(),
682        }
683    }
684
685    /// Convert this `LocalReader` into a `SwmrReader`.
686    ///
687    /// This consumes the `LocalReader` and returns a `SwmrReader`
688    /// that can be sent to another thread to create new `LocalReader`s.
689    ///
690    /// 将此 `LocalReader` 转换为 `SwmrReader`。
691    /// 这会消耗 `LocalReader` 并返回一个 `SwmrReader`,
692    /// 该 `SwmrReader` 可以发送到另一个线程以创建新 `LocalReader`。
693    #[inline]
694    pub fn into_swmr(self) -> SwmrReader<T> {
695        SwmrReader {
696            shared: self.shared.clone(),
697        }
698    }
699}
700
701impl<T: 'static> Clone for LocalReader<T> {
702    #[inline]
703    fn clone(&self) -> Self {
704        Self::new(self.shared.clone())
705    }
706}
707
708/// A guard that keeps the current thread pinned to a version.
709///
710/// `PinGuard` is obtained by calling `LocalReader::pin()`.
711/// It implements `Deref<Target = T>` to allow reading the current value.
712/// It is `!Send` and `!Sync` because it references a `!Sync` `LocalReader`.
713/// Its lifetime is bound to the `LocalReader` it came from.
714///
715/// While a `PinGuard` is held, the thread is considered "active" at a particular version,
716/// and the garbage collector will not reclaim data from that version.
717///
718/// `PinGuard` supports internal cloning via reference counting (increments the pin count),
719/// allowing nested pinning. The thread remains pinned until all cloned guards are dropped.
720///
721/// **Safety**: The `PinGuard` is the mechanism that ensures safe concurrent access to
722/// shared values. Readers must always hold a valid `PinGuard` when accessing
723/// shared data.
724///
725/// 一个保持当前线程被钉住到一个版本的守卫。
726/// `PinGuard` 通过调用 `LocalReader::pin()` 获得。
727/// 它实现了 `Deref<Target = T>`,允许读取当前值。
728/// 它是 `!Send` 和 `!Sync` 的,因为它引用了一个 `!Sync` 的 `LocalReader`。
729/// 它的生命周期被绑定到它来自的 `LocalReader`。
730/// 当 `PinGuard` 被持有时,线程被认为在特定版本"活跃",
731/// 垃圾回收器不会回收该版本的数据。
732/// `PinGuard` 支持通过引用计数的内部克隆(增加 pin 计数),允许嵌套 pinning。
733/// 线程保持被钉住直到所有克隆的守卫被 drop。
734/// **安全性**:`PinGuard` 是确保对值安全并发访问的机制。
735/// 读者在访问共享数据时必须始终持有有效的 `PinGuard`。
736#[must_use]
737pub struct PinGuard<'a, T: 'static> {
738    local: &'a LocalReader<T>,
739    /// The pointer captured at pin time for snapshot semantics.
740    /// 在 pin 时捕获的指针,用于快照语义。
741    ptr: *const T,
742    /// The version at pin time.
743    /// pin 时的版本。
744    version: usize,
745}
746
747impl<T: 'static> PinGuard<'_, T> {
748    /// Get the version that this guard is pinned to.
749    ///
750    /// 获取此守卫被 pin 到的版本。
751    #[inline]
752    pub fn version(&self) -> usize {
753        self.version
754    }
755}
756
757impl<'a, T> Deref for PinGuard<'a, T> {
758    type Target = T;
759
760    /// Dereference to access the pinned value.
761    ///
762    /// Returns a reference to the value that was current when this guard was created.
763    /// This provides snapshot semantics - the value won't change during the guard's lifetime.
764    ///
765    /// 解引用以访问被 pin 的值。
766    ///
767    /// 返回对创建此守卫时当前值的引用。
768    /// 这提供了快照语义 - 在守卫的生命周期内值不会改变。
769    #[inline]
770    fn deref(&self) -> &T {
771        // Safety: pin() guarantees pinned_version >= min_active,
772        // and the pointer was captured at pin time.
773        // The value is valid as long as guard is held.
774        // 安全性:pin() 保证 pinned_version >= min_active,
775        // 并且指针在 pin 时被捕获。
776        // 只要 guard 被持有,值就是有效的。
777        unsafe { &*self.ptr }
778    }
779}
780
781impl<'a, T> Clone for PinGuard<'a, T> {
782    /// Clone this guard to create a nested pin.
783    ///
784    /// Cloning increments the pin count, and the thread remains pinned until all cloned guards
785    /// are dropped. This allows multiple scopes to hold pins simultaneously.
786    ///
787    /// 克隆此守卫以创建嵌套 pin。
788    ///
789    /// 克隆会增加 pin 计数,线程保持被钉住直到所有克隆的守卫被 drop。
790    /// 这允许多个作用域同时持有 pin。
791    #[inline]
792    fn clone(&self) -> Self {
793        let pin_count = self.local.pin_count.get();
794
795        assert!(
796            pin_count > 0,
797            "BUG: Cloning a PinGuard in an unpinned state (pin_count = 0). \
798             This indicates incorrect API usage or a library bug."
799        );
800
801        self.local.pin_count.set(pin_count + 1);
802
803        PinGuard {
804            local: self.local,
805            ptr: self.ptr,
806            version: self.version,
807        }
808    }
809}
810
811impl<'a, T> Drop for PinGuard<'a, T> {
812    #[inline]
813    fn drop(&mut self) {
814        let pin_count = self.local.pin_count.get();
815
816        assert!(
817            pin_count > 0,
818            "BUG: Dropping a PinGuard in an unpinned state (pin_count = 0). \
819             This indicates incorrect API usage or a library bug."
820        );
821
822        if pin_count == 1 {
823            self.local
824                .slot
825                .active_version
826                .store(INACTIVE_VERSION, Ordering::Release);
827        }
828
829        self.local.pin_count.set(pin_count - 1);
830    }
831}
832
833impl<T: 'static> AsRef<T> for PinGuard<'_, T> {
834    #[inline]
835    fn as_ref(&self) -> &T {
836        self.deref()
837    }
838}
839
840// ============================================================================
841// Standard Trait Implementations
842// 标准 trait 实现
843// ============================================================================
844
845impl<T: Default + 'static> Default for SwmrCell<T> {
846    /// Create a new SWMR cell with the default value.
847    ///
848    /// 使用默认值创建一个新的 SWMR 单元。
849    #[inline]
850    fn default() -> Self {
851        Self::new(T::default())
852    }
853}
854
855impl<T: 'static> From<T> for SwmrCell<T> {
856    /// Create a new SWMR cell from a value.
857    ///
858    /// 从一个值创建一个新的 SWMR 单元。
859    #[inline]
860    fn from(value: T) -> Self {
861        Self::new(value)
862    }
863}
864
865impl<T: fmt::Debug + 'static> fmt::Debug for SwmrCell<T> {
866    #[inline]
867    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
868        f.debug_struct("SwmrCell")
869            .field("value", self.get())
870            .field("version", &self.version())
871            .field("garbage_count", &self.garbage_count())
872            .finish()
873    }
874}
875
876impl<T: 'static> fmt::Debug for LocalReader<T> {
877    #[inline]
878    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879        f.debug_struct("LocalReader")
880            .field("is_pinned", &self.is_pinned())
881            .field("version", &self.version())
882            .finish()
883    }
884}
885
886impl<T: fmt::Debug + 'static> fmt::Debug for PinGuard<'_, T> {
887    #[inline]
888    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
889        f.debug_struct("PinGuard")
890            .field("value", &self.deref())
891            .field("version", &self.version)
892            .finish()
893    }
894}