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
// Copyright (C) 2025-2026 Takayuki Sato. All Rights Reserved.
// This program is free software under MIT License.
// See the file LICENSE in this distribution for more details.
//! A library for managing data through distinct lifecycle phases.
//!
//! This crate provides "phased cells", a collection of smart pointer types that enforce
//! a specific lifecycle for the data they manage: `Setup` -> `Read` -> `Cleanup`.
//! This is useful for data that is initialized once, read by multiple threads or tasks
//! for a period, and then explicitly destroyed.
//!
//! # Core Concepts
//!
//! The lifecycle is divided into three phases:
//! - **`Setup`**: The initial phase. The data can be mutably accessed for initialization.
//! - **`Read`**: The operational phase. The data can only be accessed immutably. This phase
//! is optimized for concurrent, lock-free reads.
//! - **`Cleanup`**: The final phase. The data can be mutably accessed again for deconstruction
//! or resource cleanup.
//!
//! ## Cell Variants
//!
//! This crate offers several cell variants to suit different concurrency needs:
//!
//! - [`PhasedCell`]: The basic cell. It is `Sync` if the contained data `T` is `Send + Sync`,
//! allowing it to be shared across threads for reading. However, mutable access via
//! [`get_mut_unlocked`](PhasedCell::get_mut_unlocked) is not thread-safe and requires the
//! caller to ensure exclusive access.
//!
//! - [`PhasedCellSync`]: A thread-safe version that uses a `std::sync::Mutex` to allow for
//! safe concurrent mutable access during the `Setup` and `Cleanup` phases.
//!
//! - [`PhasedCellAsync`]: (Requires the `tokio` feature) An `async` version
//! of `PhasedCellSync` that uses a `tokio::sync::Mutex`.
//!
//! ## Graceful Cleanup
//!
//! (Requires the `graceful` feature)
//!
//! The `graceful` module provides wrappers that add graceful cleanup capabilities. When
//! transitioning to the `Cleanup` phase, these cells will wait for a specified duration
//! for all active read operations to complete.
//!
//! - [`GracefulPhasedCell`](graceful::GracefulPhasedCell)
//! - [`GracefulPhasedCellSync`](graceful::GracefulPhasedCellSync)
//! - [`GracefulPhasedCellAsync`](graceful::GracefulPhasedCellAsync) (Requires both features)
//!
//! # Examples
//!
//! Using a `static PhasedCellSync` to initialize data, read it from multiple threads, and then
//! clean it up.
//!
//! ```
//! use setup_read_cleanup::{PhasedCellSync, Phase};
//! use std::thread;
//!
//! struct MyData {
//! items: Vec<i32>,
//! }
//!
//! // Declare a static PhasedCellSync instance
//! static CELL: PhasedCellSync<MyData> = PhasedCellSync::new(MyData { items: Vec::new() });
//!
//! fn main() {
//! // --- Setup Phase ---
//! assert_eq!(CELL.phase(), Phase::Setup);
//! {
//! let mut data = CELL.lock().unwrap();
//! data.items.push(10);
//! data.items.push(20);
//! } // Lock is released here
//!
//! // --- Transition to Read Phase ---
//! CELL.transition_to_read(|data| {
//! data.items.push(30);
//! Ok::<(), std::io::Error>(())
//! }).unwrap();
//! assert_eq!(CELL.phase(), Phase::Read);
//!
//! // --- Read Phase ---
//! // Now, multiple threads can read the data concurrently.
//! let mut handles = Vec::new();
//! for i in 0..3 {
//! handles.push(thread::spawn(move || {
//! let data = CELL.read().unwrap(); // Access the static CELL
//! println!("Thread {} reads: {:?}", i, data.items);
//! assert_eq!(data.items, &[10, 20, 30]);
//! }));
//! }
//!
//! for handle in handles {
//! handle.join().unwrap();
//! }
//!
//! // --- Transition to Cleanup Phase ---
//! CELL.transition_to_cleanup(|data| {
//! println!("Cleaning up. Final item: {:?}", data.items.pop());
//! Ok::<(), std::io::Error>(())
//! }).unwrap();
//! assert_eq!(CELL.phase(), Phase::Cleanup);
//! }
//! ```
//!
//! # Features
//!
//! - `tokio`: Enables the `async` cell variants (`PhasedCellAsync`, `GracefulPhasedCellAsync`)
//! which use `tokio::sync`.
//! - `graceful`: Enables the `graceful` module, which provides cells with
//! graceful cleanup capabilities.
/// A module for graceful cleanup of phased cells.
///
/// This module provides extensions and wrappers for `PhasedCell` and its variants
/// to support graceful cleanup, allowing ongoing operations to complete before
/// transitioning to the `Cleanup` phase.
use ;
/// Represents the current operational phase of a phased cell.
///
/// The lifecycle of a phased cell progresses through these three distinct phases:
/// 1. `Setup`: The initial phase where the data is constructed and initialized.
/// 2. `Read`: The main operational phase where the data is accessed for read-only operations.
/// 3. `Cleanup`: The final phase where the data is deconstructed and resources are released.
/// An enumeration of possible error kinds that can occur in a phased cell.
///
/// This enum categorizes the various errors that can arise during phase transitions
/// or data access, providing specific information about the nature of the failure.
/// A structure representing an error that occurred within a phased cell.
///
/// It contains the phase in which the error occurred, the kind of error, and an
/// optional source error for more context.
/// A cell that manages data through distinct `Setup`, `Read`, and `Cleanup` phases.
///
/// `PhasedCell` enforces a specific data lifecycle: initialization in the `Setup`
/// phase, a read-only operational period in the `Read` phase, and deconstruction
/// in the `Cleanup` phase.
///
/// This cell is `Sync` if the contained data `T` is `Send + Sync`, which allows
/// the cell to be shared across threads. During the `Read` phase, the `read` and
/// `read_relaxed` methods can be safely called from multiple threads simultaneously
/// if the cell is `Sync`. Access during phase transitions and mutable access in
/// other phases are not thread-safe.
/// A thread-safe cell that manages data through `Setup`, `Read`, and `Cleanup` phases
/// with support for concurrent mutable access.
///
/// `PhasedCellSync` is similar to `PhasedCell` but uses a `std::sync::Mutex` to
/// synchronize access to the internal data. This is particularly useful when
/// multiple threads need to mutate the data during the `Setup` or `Cleanup`
/// phases, which is not safely supported by `PhasedCell`.
/// A RAII implementation of a scoped lock for a `PhasedCellSync`.
///
/// When this structure is dropped (falls out of scope), the lock will be released.
/// An asynchronous, thread-safe cell for managing data through `Setup`, `Read`, and `Cleanup` phases.
///
/// `PhasedCellAsync` is similar to `PhasedCellSync` but is designed for asynchronous
/// contexts using `tokio`. It leverages a `tokio::sync::Mutex` to provide asynchronous,
/// non-blocking locking, making it suitable for use in async applications.
/// A RAII implementation of a scoped lock for a `PhasedCellAsync`.
///
/// When this structure is dropped (falls out of scope), the lock will be released.