preloader 0.1.3

Asynchronous data preloader library
Documentation
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Asynchronous data preloader module
//!
//! This module provides the `Preloader` struct for asynchronously loading and caching data.
//! You can perform other tasks while the data is loading, and retrieve the result immediately once loading is complete.

use std::{cell::UnsafeCell, future::Future, sync::atomic::Ordering};

use atomic_enum::atomic_enum;
use tokio::sync::{
    oneshot::{self, Receiver},
    Mutex,
};

// preloader error define
#[derive(Debug, thiserror::Error)]
pub enum PreloaderError {
    #[error("Preloader is not loaded")]
    NotLoaded,
    #[error("Preloader is loading")]
    Loading,
}

type Result<T> = std::result::Result<T, PreloaderError>;

/// Enum representing the current state of the preloader
#[atomic_enum]
enum PreloaderState {
    /// Initial state - loading has not started yet
    Idle,
    /// Start state - loading process has started
    Start,
    /// Loading state - data is being loaded asynchronously
    Loading,
    /// Loaded state - data has been successfully loaded and is available
    Loaded,
}

/// Asynchronous data preloader
///
/// `Preloader` is a struct for asynchronously loading and caching data.
/// Once data loading is complete, the result is returned immediately, and the original future is executed only once even if called multiple times.
///
/// # Example
///
/// ```rust
/// use preloader::Preloader;
/// let preloader: Preloader<String> = Preloader::new();
/// ```
///
/// # Thread Safety
///
/// `Preloader` implements `Send` and `Sync`, so it can be safely used across multiple threads.
///
/// # Generic Type
///
/// - `T`: The type of data to load. Must satisfy `Send + 'static`.
pub struct Preloader<T: Send + 'static> {
    /// Current state of the preloader
    state: AtomicPreloaderState,
    /// Handle for the asynchronous task
    handle: Mutex<Option<Receiver<T>>>,
    /// Cell storing the loaded data
    value: UnsafeCell<Option<T>>,
}

unsafe impl<T: Send + 'static> Send for Preloader<T> {}
unsafe impl<T: Send + 'static> Sync for Preloader<T> {}

impl<T: Send + 'static> Preloader<T> {
    /// Creates a new `Preloader` instance.
    ///
    /// # Returns
    ///
    /// A new `Preloader` instance in the initial `Idle` state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// let preloader: Preloader<String> = Preloader::new();
    /// ```
    pub fn new() -> Self {
        Self {
            state: AtomicPreloaderState::new(PreloaderState::Idle),
            handle: Mutex::new(None),
            value: UnsafeCell::new(None),
        }
    }

    /// Starts an asynchronous task to load data.
    ///
    /// This method can only be called in the `Idle` state. If loading is already in progress or completed,
    /// it does nothing and returns immediately.
    ///
    /// # Parameters
    ///
    /// - `future`: The asynchronous task to execute. Must implement `Future<Output = T> + Send + 'static`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let preloader = Preloader::new();
    ///     preloader.load(async {
    ///         // Simulate a time-consuming task
    ///         tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    ///         42
    ///     }).await;
    /// }
    /// ```
    pub async fn load(&self, future: impl Future<Output = T> + Send + 'static) {
        let Ok(PreloaderState::Idle) = self.state.compare_exchange(
            PreloaderState::Idle,
            PreloaderState::Start,
            Ordering::Relaxed,
            Ordering::Relaxed,
        ) else {
            return;
        };

        let (tx, rx) = oneshot::channel();

        tokio::spawn(async move {
            let value = future.await;
            _ = tx.send(value);
        });

        self.set_handle(rx).await;
    }

    /// Retrieves the loaded data.
    ///
    /// Returns an error if the data is not yet loaded.
    /// If the data is still loading, waits until loading is complete.
    ///
    /// # Returns
    ///
    /// - `Ok(&T)`: If the data was successfully loaded
    /// - `Err(String)`: If the data is not loaded or an error occurred during loading
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let preloader = Preloader::new();
    ///     // Start loading first
    ///     preloader.load(async { "data".to_string() }).await;
    ///     // Retrieve data
    ///     match preloader.get().await {
    ///         Ok(data) => println!("Loaded data: {}", data),
    ///         Err(e) => println!("Error: {}", e),
    ///     }
    /// }
    /// ```
    pub async fn get(&self) -> Result<&T> {
        match self.state.load(Ordering::Relaxed) {
            PreloaderState::Idle | PreloaderState::Start => {
                return Err(PreloaderError::NotLoaded);
            }
            PreloaderState::Loading => {
                let mut handle = self.handle.lock().await;
                if let Some(handle) = handle.take() {
                    let value = handle.await.map_err(|_| PreloaderError::Loading)?;
                    self.set_value(value);
                    return Ok(self.get_value());
                } else {
                    // If handle is already None, just return the value
                    return Ok(self.get_value());
                }
            }
            PreloaderState::Loaded => {
                return Ok(self.get_value());
            }
        }
    }

    /// Takes the loaded data, consuming it.
    ///
    /// This method consumes the loaded data, leaving None in its place.
    /// Returns an error if the data is not yet loaded.
    /// If the data is still loading, waits until loading is complete.
    ///
    /// # Returns
    ///
    /// - `Ok(T)`: If the data was successfully loaded and taken
    /// - `Err(PreloaderError)`: If the data is not loaded or an error occurred during loading
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let preloader = Preloader::new();
    ///     // Start loading
    ///     preloader.load(async { "data".to_string() }).await;
    ///     // Take data, consuming the preloader
    ///     match preloader.take().await {
    ///         Ok(data) => println!("Taken data: {}", data),
    ///         Err(e) => println!("Error: {}", e),
    ///     }
    ///     // Note: preloader is consumed and cannot be used after take()
    ///     // The following code would not compile:
    ///     // match preloader.try_get() { ... } // Error: use of moved value
    /// }
    /// ```
    /// Takes the loaded data, consuming the Preloader.
    ///
    /// This method consumes the Preloader itself, ensuring it cannot be used after taking the value.
    /// Returns an error if the data is not yet loaded.
    /// If the data is still loading, waits until loading is complete.
    ///
    /// # Returns
    ///
    /// - `Ok(T)`: If the data was successfully loaded and taken
    /// - `Err(PreloaderError)`: If the data is not loaded or an error occurred during loading
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let preloader = Preloader::new();
    ///     // Start loading
    ///     preloader.load(async { "data".to_string() }).await;
    ///     // Take data, consuming the preloader
    ///     match preloader.take().await {
    ///         Ok(data) => println!("Taken data: {}", data),
    ///         Err(e) => println!("Error: {}", e),
    ///     }
    ///     // Preloader cannot be used after take() as it has been consumed
    /// }
    /// ```
    pub async fn take(self) -> Result<T> {
        match self.get().await {
            Ok(_) => self.take_value(),
            Err(e) => Err(e),
        }
    }

    /// Retrieves the loaded data without checking the state.
    ///
    /// This method is unsafe and should only be used when you are sure that the data is loaded.
    ///
    /// # Returns
    ///
    pub unsafe fn get_unchecked(&self) -> &T {
        match self.state.load(Ordering::Relaxed) {
            PreloaderState::Idle | PreloaderState::Start => {
                panic!("Preloader is not loaded");
            }
            PreloaderState::Loading => {
                return self.get_value();
            }
            PreloaderState::Loaded => {
                return self.get_value();
            }
        }
    }

    /// Attempts to retrieve the loaded data immediately.
    ///
    /// Unlike `get()`, this method does not block. If the data is not yet loaded or is still loading, returns an error immediately.
    ///
    /// # Returns
    ///
    /// - `Ok(&T)`: If the data was successfully loaded
    /// - `Err(String)`: If the data is not loaded or is still loading
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let preloader = Preloader::new();
    ///     // Try before loading
    ///     match preloader.try_get() {
    ///         Ok(data) => println!("Data: {}", data),
    ///         Err(e) => println!("Not loaded yet: {}", e),
    ///     }
    ///     // Start loading
    ///     preloader.load(async { "data".to_string() }).await;
    ///     // Try while loading
    ///     match preloader.try_get() {
    ///         Ok(data) => println!("Data: {}", data),
    ///         Err(e) => println!("Still loading: {}", e),
    ///     }
    /// }
    /// ```
    pub fn try_get(&self) -> Result<&T> {
        match self.state.load(Ordering::Relaxed) {
            PreloaderState::Idle | PreloaderState::Start => {
                return Err(PreloaderError::NotLoaded);
            }
            PreloaderState::Loading => {
                let mut handle = self
                    .handle
                    .try_lock()
                    .map_err(|_| PreloaderError::Loading)?;

                if let Some(handle) = handle.as_mut() {
                    let value = handle.try_recv().map_err(|_| PreloaderError::Loading)?;
                    self.set_value(value);
                }
                return Ok(self.get_value());
            }
            PreloaderState::Loaded => {
                return Ok(self.get_value());
            }
        }
    }

    /// Retrieves the loaded data without checking the state.
    ///
    /// This method is unsafe and should only be used when you are sure that the data is loaded.
    ///
    /// # Returns
    ///
    /// Reference to the stored value
    pub unsafe fn try_get_unchecked(&self) -> &T {
        match self.state.load(Ordering::Relaxed) {
            PreloaderState::Idle | PreloaderState::Start => {
                panic!("Preloader is not loaded");
            }
            PreloaderState::Loading => {
                panic!("Preloader is loading");
            }
            PreloaderState::Loaded => self.get_value(),
        }
    }

    /// Sets the handle for the asynchronous task and changes the state to `Loading`.
    ///
    /// # Parameters
    ///
    /// - `handle`: Receiver for the asynchronous task
    #[inline]
    async fn set_handle(&self, handle: Receiver<T>) {
        *self.handle.lock().await = Some(handle);
        self.state.store(PreloaderState::Loading, Ordering::Release);
    }

    /// Safely retrieves the stored value.
    ///
    /// # Returns
    ///
    /// Reference to the stored value
    ///
    /// # Safety
    ///
    /// This method should only be called in the `Loaded` state, and the value is guaranteed to exist.
    #[inline]
    fn get_value(&self) -> &T {
        unsafe { &*self.value.get() }.as_ref().unwrap()
    }

    /// Stores the value and changes the state to `Loaded`.
    ///
    /// # Parameters
    ///
    /// - `value`: The value to store
    #[inline]
    fn set_value(&self, value: T) {
        unsafe { *self.value.get() = Some(value) };
        // Set handle to None to prevent duplicate receiving
        if let Ok(mut handle) = self.handle.try_lock() {
            *handle = None;
        }
        self.state.store(PreloaderState::Loaded, Ordering::Release);
    }

    /// Takes the stored value, leaving None in its place.
    ///
    /// # Returns
    ///
    /// Result containing the stored value or an error if the value is None
    ///
    /// # Safety
    ///
    /// This method should only be called when the value is guaranteed to exist.
    #[inline]
    fn take_value(self) -> Result<T> {
        unsafe {
            let value = (*self.value.get()).take();
            if let Some(value) = value {
                Ok(value)
            } else {
                Err(PreloaderError::NotLoaded)
            }
        }
    }

    /// Checks if the preloader has completed loading and data is available.
    ///
    /// This method returns true if the preloader is in the `Loaded` state,
    /// indicating that data is ready to be accessed without blocking.
    ///
    /// # Returns
    ///
    /// - `true`: If the data is loaded and ready for immediate access
    /// - `false`: If the data is not loaded yet or is still loading
    ///
    /// # Example
    ///
    /// ```rust
    /// use preloader::Preloader;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let preloader = Preloader::new();
    ///     
    ///     // Check before loading
    ///     assert!(!preloader.is_loaded());
    ///     
    ///     // Start loading
    ///     preloader.load(async { "data".to_string() }).await;
    ///     
    ///     // Wait for completion
    ///     preloader.get().await.unwrap();
    ///     
    ///     // Check after loading
    ///     assert!(preloader.is_loaded());
    /// }
    /// ```
    pub fn is_loaded(&self) -> bool {
        self.try_get().is_ok()
    }
}