Skip to main content

ma_ippatsu_r/
lib.rs

1//! Thread-safe, one-shot initialization with explicit winner status.
2//!
3//! The first successfully completed initializer publishes one immutable value.
4//! Every later caller receives that value without evaluating its initializer.
5//!
6//! ```
7//! use ma_ippatsu_r::{Ippatsu, ShotStatus};
8//!
9//! let answer = Ippatsu::new();
10//! assert_eq!(answer.fire(|| 42).status(), ShotStatus::FiredNow);
11//! assert_eq!(answer.fire(|| 99).status(), ShotStatus::AlreadyFired);
12//! assert_eq!(answer.get(), Some(&42));
13//! ```
14
15use std::fmt::{self, Debug, Formatter};
16use std::sync::OnceLock;
17
18/// Whether a call published the value or observed an existing value.
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20pub enum ShotStatus {
21    /// This call successfully published the one-shot value.
22    FiredNow,
23    /// A previous call had already published the value.
24    AlreadyFired,
25}
26
27/// Borrowed result of lazy one-shot initialization.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct Shot<'a, T> {
30    status: ShotStatus,
31    value: &'a T,
32}
33
34impl<'a, T> Shot<'a, T> {
35    /// Whether this call fired or observed an earlier shot.
36    pub const fn status(self) -> ShotStatus {
37        self.status
38    }
39
40    /// Canonical immutable value.
41    pub const fn value(self) -> &'a T {
42        self.value
43    }
44
45    /// Returns true only for the call that published the value.
46    pub const fn fired_now(self) -> bool {
47        matches!(self.status, ShotStatus::FiredNow)
48    }
49}
50
51/// Result of offering an already-created value.
52pub struct Offer<'a, T> {
53    status: ShotStatus,
54    value: &'a T,
55    rejected: Option<T>,
56}
57
58impl<T: Debug> Debug for Offer<'_, T> {
59    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
60        f.debug_struct("Offer")
61            .field("status", &self.status)
62            .field("value", self.value)
63            .field("rejected", &self.rejected)
64            .finish()
65    }
66}
67
68impl<'a, T> Offer<'a, T> {
69    /// Whether this offer published or lost to an earlier value.
70    pub const fn status(&self) -> ShotStatus {
71        self.status
72    }
73
74    /// Canonical immutable value.
75    pub const fn value(&self) -> &'a T {
76        self.value
77    }
78
79    /// Value that lost the race, when this offer was not accepted.
80    pub const fn rejected(&self) -> Option<&T> {
81        self.rejected.as_ref()
82    }
83
84    /// Consumes the outcome and returns the losing value.
85    pub fn into_rejected(self) -> Option<T> {
86        self.rejected
87    }
88}
89
90/// One immutable value initialized at most once successfully.
91#[derive(Debug, Default)]
92pub struct Ippatsu<T> {
93    cell: OnceLock<T>,
94}
95
96impl<T> Ippatsu<T> {
97    /// Creates an unfired one-shot cell.
98    pub const fn new() -> Self {
99        Self {
100            cell: OnceLock::new(),
101        }
102    }
103
104    /// Lazily fires the cell.
105    ///
106    /// Across concurrent callers, only the winning initializer is evaluated.
107    /// If it panics, no value is published and a later caller may retry.
108    ///
109    /// Initializers must not reentrantly initialize the same cell.
110    pub fn fire(&self, initializer: impl FnOnce() -> T) -> Shot<'_, T> {
111        let mut fired_now = false;
112        let value = self.cell.get_or_init(|| {
113            fired_now = true;
114            initializer()
115        });
116        Shot {
117            status: if fired_now {
118                ShotStatus::FiredNow
119            } else {
120                ShotStatus::AlreadyFired
121            },
122            value,
123        }
124    }
125
126    /// Offers an already-created value to the one-shot cell.
127    ///
128    /// A losing value is returned through [`Offer::rejected`] or
129    /// [`Offer::into_rejected`] instead of being silently dropped.
130    pub fn offer(&self, candidate: T) -> Offer<'_, T> {
131        let (status, rejected) = match self.cell.set(candidate) {
132            Ok(()) => (ShotStatus::FiredNow, None),
133            Err(candidate) => (ShotStatus::AlreadyFired, Some(candidate)),
134        };
135        let value = self
136            .cell
137            .get()
138            .expect("OnceLock contains a value after set succeeds or loses");
139        Offer {
140            status,
141            value,
142            rejected,
143        }
144    }
145
146    /// Returns the published value without firing.
147    pub fn get(&self) -> Option<&T> {
148        self.cell.get()
149    }
150
151    /// Returns whether a value has been published.
152    pub fn is_fired(&self) -> bool {
153        self.cell.get().is_some()
154    }
155
156    /// Consumes the cell and returns its published value.
157    pub fn into_inner(self) -> Option<T> {
158        self.cell.into_inner()
159    }
160}
161
162impl<T> From<T> for Ippatsu<T> {
163    fn from(value: T) -> Self {
164        let cell = OnceLock::new();
165        let result = cell.set(value);
166        debug_assert!(result.is_ok());
167        Self { cell }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use std::panic::{AssertUnwindSafe, catch_unwind};
175    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
176    use std::sync::{Arc, Barrier};
177    use std::thread;
178
179    #[test]
180    fn new_cell_is_unfired() {
181        let cell = Ippatsu::<u8>::new();
182        assert!(!cell.is_fired());
183        assert_eq!(cell.get(), None);
184    }
185
186    #[test]
187    fn first_fire_wins_and_later_initializer_is_not_run() {
188        let cell = Ippatsu::new();
189        let later_ran = AtomicBool::new(false);
190
191        let first = cell.fire(|| 42);
192        let later = cell.fire(|| {
193            later_ran.store(true, Ordering::SeqCst);
194            99
195        });
196
197        assert_eq!(first.status(), ShotStatus::FiredNow);
198        assert_eq!(later.status(), ShotStatus::AlreadyFired);
199        assert_eq!(later.value(), &42);
200        assert!(!later_ran.load(Ordering::SeqCst));
201    }
202
203    #[test]
204    fn losing_offer_returns_its_candidate() {
205        let cell = Ippatsu::new();
206        assert_eq!(cell.offer(10).status(), ShotStatus::FiredNow);
207        let later = cell.offer(20);
208        assert_eq!(later.status(), ShotStatus::AlreadyFired);
209        assert_eq!(later.value(), &10);
210        assert_eq!(later.into_rejected(), Some(20));
211    }
212
213    #[test]
214    fn concurrent_fire_executes_exactly_one_initializer() {
215        const WORKERS: usize = 8;
216        let cell = Arc::new(Ippatsu::new());
217        let starts = Arc::new(Barrier::new(WORKERS));
218        let executions = Arc::new(AtomicUsize::new(0));
219        let handles: Vec<_> = (0..WORKERS)
220            .map(|index| {
221                let cell = cell.clone();
222                let starts = starts.clone();
223                let executions = executions.clone();
224                thread::spawn(move || {
225                    starts.wait();
226                    *cell
227                        .fire(|| {
228                            executions.fetch_add(1, Ordering::SeqCst);
229                            index
230                        })
231                        .value()
232                })
233            })
234            .collect();
235
236        let values: Vec<_> = handles
237            .into_iter()
238            .map(|handle| handle.join().unwrap())
239            .collect();
240        assert_eq!(executions.load(Ordering::SeqCst), 1);
241        assert!(values.iter().all(|value| value == &values[0]));
242    }
243
244    #[test]
245    fn panic_publishes_no_partial_value_and_allows_retry() {
246        let cell = Ippatsu::new();
247        let result = catch_unwind(AssertUnwindSafe(|| {
248            cell.fire(|| -> String { panic!("failed shot") });
249        }));
250        assert!(result.is_err());
251        assert!(!cell.is_fired());
252        assert_eq!(cell.fire(|| "retry".to_string()).value(), "retry");
253    }
254
255    #[test]
256    fn preloaded_cell_is_already_fired() {
257        let cell = Ippatsu::from("ready");
258        assert!(cell.is_fired());
259        assert_eq!(cell.fire(|| "later").status(), ShotStatus::AlreadyFired);
260        assert_eq!(cell.get(), Some(&"ready"));
261    }
262
263    #[test]
264    fn into_inner_preserves_state() {
265        assert_eq!(Ippatsu::from(7).into_inner(), Some(7));
266        assert_eq!(Ippatsu::<u8>::new().into_inner(), None);
267    }
268}