|
| 1 | +use crate::executor::Wait; |
| 2 | +use std::{ |
| 3 | + fmt, |
| 4 | + sync::{Arc, OnceLock}, |
| 5 | +}; |
| 6 | + |
| 7 | +#[derive(Debug)] |
| 8 | +enum FutureStatus<T> { |
| 9 | + Completed(T), |
| 10 | + Poisoned, |
| 11 | +} |
| 12 | + |
| 13 | +use FutureStatus::*; |
| 14 | + |
| 15 | +/// A placeholder for a value that will be computed at a later time. |
| 16 | +/// |
| 17 | +/// `Future`s are the result of running functions in separate threads using |
| 18 | +/// [`Executor::spawn`](crate::executor::Executor::spawn): calling `spawn()` in fact returns |
| 19 | +/// immediately, even though the function will complete at a later time. The `Future` returned by |
| 20 | +/// `spawn()` allows retrieving the result of the function once it completes. |
| 21 | +/// |
| 22 | +/// # Poisoning |
| 23 | +/// |
| 24 | +/// A `Future` may be in a "poisoned" status if the execution of the function that produced it |
| 25 | +/// failed with a panic. |
| 26 | +pub struct Future<T> { |
| 27 | + cell: Arc<OnceLock<FutureStatus<T>>>, |
| 28 | +} |
| 29 | + |
| 30 | +impl<T> Future<T> { |
| 31 | + #[inline] |
| 32 | + #[must_use] |
| 33 | + pub(super) fn pending() -> Self { |
| 34 | + Self { cell: Arc::new(OnceLock::new()) } |
| 35 | + } |
| 36 | + |
| 37 | + /// Creates a new `Future` that is already completed with the given value. |
| 38 | + #[inline] |
| 39 | + #[must_use] |
| 40 | + pub fn ready(value: T) -> Self { |
| 41 | + let this = Self::pending(); |
| 42 | + this.complete(value); |
| 43 | + this |
| 44 | + } |
| 45 | + |
| 46 | + #[inline] |
| 47 | + pub(super) fn complete(&self, value: T) { |
| 48 | + self.try_complete(value).unwrap_or_else(|err| panic!("{err}")) |
| 49 | + } |
| 50 | + |
| 51 | + #[inline] |
| 52 | + pub(super) fn try_complete(&self, value: T) -> Result<(), ReadyError> { |
| 53 | + self.cell.set(Completed(value)).map_err(|_| ReadyError) |
| 54 | + } |
| 55 | + |
| 56 | + // There's no `poison()` method simply because it's not used internally. |
| 57 | + |
| 58 | + #[inline] |
| 59 | + pub(super) fn try_poison(&self) -> Result<(), ReadyError> { |
| 60 | + self.cell.set(Poisoned).map_err(|_| ReadyError) |
| 61 | + } |
| 62 | + |
| 63 | + /// Returns the value of the `Future`, or `None` if this `Future` was not completed yet. |
| 64 | + /// |
| 65 | + /// # Panics |
| 66 | + /// |
| 67 | + /// If the `Future` is poisoned. See [`Future::try_get()`] for a non-panicking version of this |
| 68 | + /// method. |
| 69 | + #[inline] |
| 70 | + #[must_use] |
| 71 | + pub fn get(&self) -> Option<&T> { |
| 72 | + self.try_get().map(|result| result.expect("Future is poisoned")) |
| 73 | + } |
| 74 | + |
| 75 | + /// Returns the value of the `Future`, `None` if this `Future` was not completed yet, or an |
| 76 | + /// error if this `Future` is poisoned. |
| 77 | + #[inline] |
| 78 | + #[must_use] |
| 79 | + pub fn try_get(&self) -> Option<Result<&T, PoisonError>> { |
| 80 | + match self.cell.get() { |
| 81 | + None => None, |
| 82 | + Some(Completed(ref value)) => Some(Ok(value)), |
| 83 | + Some(Poisoned) => Some(Err(PoisonError)), |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +impl<T> Wait for Future<T> { |
| 89 | + type Output = T; |
| 90 | + |
| 91 | + #[inline] |
| 92 | + fn wait(&self) -> &Self::Output { |
| 93 | + match self.cell.wait() { |
| 94 | + Completed(value) => value, |
| 95 | + Poisoned => panic!("{PoisonError}"), |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +impl<T> Clone for Future<T> { |
| 101 | + fn clone(&self) -> Self { |
| 102 | + Self { cell: Arc::clone(&self.cell) } |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +impl<T: fmt::Debug> fmt::Debug for Future<T> { |
| 107 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 108 | + struct Pending; |
| 109 | + |
| 110 | + impl fmt::Debug for Pending { |
| 111 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 112 | + f.write_str("<pending>") |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + struct Poisoned; |
| 117 | + |
| 118 | + impl fmt::Debug for Poisoned { |
| 119 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 120 | + f.write_str("<poisoned>") |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + f.debug_tuple("Future") |
| 125 | + .field(match self.try_get() { |
| 126 | + None => &Pending, |
| 127 | + Some(Ok(value)) => value, |
| 128 | + Some(Err(PoisonError)) => &Poisoned, |
| 129 | + }) |
| 130 | + .finish() |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +#[derive(Clone, PartialEq, Eq, Debug)] |
| 135 | +pub(super) struct ReadyError; |
| 136 | + |
| 137 | +impl fmt::Display for ReadyError { |
| 138 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 139 | + f.write_str("attempted to complete or poison the Future twice") |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +impl std::error::Error for ReadyError {} |
| 144 | + |
| 145 | +#[derive(Clone, PartialEq, Eq, Debug)] |
| 146 | +pub struct PoisonError; |
| 147 | + |
| 148 | +impl fmt::Display for PoisonError { |
| 149 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 150 | + f.write_str("execution of the closure for this Future resulted in a panic") |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +impl std::error::Error for PoisonError {} |
| 155 | + |
| 156 | +#[cfg(test)] |
| 157 | +mod tests { |
| 158 | + use super::*; |
| 159 | + use std::{panic, sync::Barrier, thread, time::Duration}; |
| 160 | + |
| 161 | + #[test] |
| 162 | + fn pending_to_completed() { |
| 163 | + let f = Future::<u32>::pending(); |
| 164 | + |
| 165 | + assert_eq!(f.get(), None); |
| 166 | + assert_eq!(f.try_get(), None); |
| 167 | + |
| 168 | + f.complete(123); |
| 169 | + |
| 170 | + assert_eq!(f.get(), Some(&123)); |
| 171 | + assert_eq!(f.try_get(), Some(Ok(&123))); |
| 172 | + } |
| 173 | + |
| 174 | + #[test] |
| 175 | + fn pending_to_poisoned() { |
| 176 | + let f = Future::<u32>::pending(); |
| 177 | + |
| 178 | + assert_eq!(f.get(), None); |
| 179 | + assert_eq!(f.try_get(), None); |
| 180 | + |
| 181 | + f.try_poison().expect("poison failed"); |
| 182 | + |
| 183 | + panic::catch_unwind(|| f.get()).expect_err("get() should have panicked"); |
| 184 | + assert_eq!(f.try_get(), Some(Err(PoisonError))); |
| 185 | + } |
| 186 | + |
| 187 | + #[test] |
| 188 | + fn wait() { |
| 189 | + let f = Future::<u32>::pending(); |
| 190 | + let g = f.clone(); |
| 191 | + let barrier = Barrier::new(2); |
| 192 | + |
| 193 | + thread::scope(|s| { |
| 194 | + s.spawn(|| { |
| 195 | + barrier.wait(); |
| 196 | + thread::sleep(Duration::from_secs(1)); |
| 197 | + g.complete(123); |
| 198 | + }); |
| 199 | + |
| 200 | + assert_eq!(f.get(), None); |
| 201 | + assert_eq!(f.try_get(), None); |
| 202 | + |
| 203 | + barrier.wait(); |
| 204 | + |
| 205 | + assert_eq!(f.wait(), &123); |
| 206 | + assert_eq!(f.get(), Some(&123)); |
| 207 | + assert_eq!(f.try_get(), Some(Ok(&123))); |
| 208 | + |
| 209 | + // Waiting twice or more should return the same value |
| 210 | + assert_eq!(f.wait(), &123); |
| 211 | + }); |
| 212 | + } |
| 213 | +} |
0 commit comments