trash_parallelism 0.1.102

Azzybana Raccoon's comprehensive parallelism 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/// Task management utilities for spawning and coordinating async tasks.
///
/// This module provides task spawners and groups for managing concurrent async operations,
/// with built-in cancellation support and error handling using smol runtime.
///
/// # Examples
///
/// Basic task spawning:
/// ```rust
/// use trash_utilities::async::tasks::AsyncTaskSpawner;
/// use smol;
///
/// # smol::block_on(async {
/// let spawner = AsyncTaskSpawner::new();
/// spawner.spawn(|| async {
///     // Your async task here
///     println!("Task executed!");
/// });
/// spawner.wait_all().await;
/// # });
/// ```
// Standard library imports
// External crate imports
use parking_lot::Mutex;
use smol;
use smol_cancellation_token::CancellationToken;

/// Async task spawner with error handling.
///
/// `AsyncTaskSpawner` allows spawning multiple asynchronous tasks concurrently,
/// managing their lifecycles with built-in cancellation support. Tasks are spawned
/// using the smol runtime and can be cancelled collectively.
///
/// # Examples
///
/// ```rust
/// use trash_utilities::async::tasks::AsyncTaskSpawner;
/// use smol;
///
/// # smol::block_on(async {
/// let spawner = AsyncTaskSpawner::new();
/// spawner.spawn(|| async {
///     // Simulate work
///     smol::Timer::after(std::time::Duration::from_millis(100)).await;
///     println!("Task 1 done");
/// });
/// spawner.spawn(|| async {
///     println!("Task 2 done");
/// });
/// spawner.wait_all().await;
/// # });
/// ```
pub struct AsyncTaskSpawner {
    token: CancellationToken,
    handles: Mutex<Vec<smol::Task<()>>>,
}

impl AsyncTaskSpawner {
    /// Create a new task spawner with a default cancellation token.
    ///
    /// # Returns
    ///
    /// A new `AsyncTaskSpawner` instance ready to spawn tasks.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawner;
    ///
    /// let spawner = AsyncTaskSpawner::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            token: CancellationToken::new(),
            handles: Mutex::new(Vec::new()),
        }
    }

    /// Create a builder for more complex configuration.
    ///
    /// Use the builder to customize the cancellation token or other settings.
    ///
    /// # Returns
    ///
    /// An `AsyncTaskSpawnerBuilder` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawner;
    /// use smol_cancellation_token::CancellationToken;
    ///
    /// let token = CancellationToken::new();
    /// let spawner = AsyncTaskSpawner::builder()
    ///     .with_cancellation_token(token)
    ///     .build();
    /// ```
    #[must_use]
    pub fn builder() -> AsyncTaskSpawnerBuilder {
        AsyncTaskSpawnerBuilder::new()
    }

    /// Spawn an async task (non-blocking).
    ///
    /// The task will be executed asynchronously using the smol runtime.
    /// If the spawner's cancellation token is cancelled before spawning,
    /// the task will not be spawned.
    ///
    /// # Parameters
    ///
    /// * `task` - A closure that returns a future representing the async task.
    ///
    /// # Type Parameters
    ///
    /// * `F` - The type of the task closure.
    /// * `Fut` - The type of the future returned by the task.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawner;
    /// use smol;
    ///
    /// # smol::block_on(async {
    /// let spawner = AsyncTaskSpawner::new();
    /// spawner.spawn(|| async {
    ///     println!("Hello from async task!");
    /// });
    /// spawner.wait_all().await;
    /// # });
    /// ```
    pub fn spawn<F, Fut>(&self, task: F)
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        if self.token.is_cancelled() {
            return;
        }

        let handle = smol::spawn(async move {
            task().await;
        });

        self.handles.lock().push(handle);
    }

    /// Cancel all tasks
    pub fn cancel(&self) {
        self.token.cancel();
    }

    /// Cancel all tasks managed by this spawner.
    ///
    /// This sets the cancellation token, which will prevent new tasks from starting
    /// and may interrupt running tasks if they check for cancellation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawner;
    /// use smol;
    ///
    /// # smol::block_on(async {
    /// let spawner = AsyncTaskSpawner::new();
    /// spawner.spawn(|| async {
    ///     // Task logic here
    /// });
    /// spawner.cancel(); // Cancels the task
    /// # });
    /// ```
    /// Wait for all tasks to complete (non-blocking)
    pub async fn wait_all(&self) {
        let handles = std::mem::take(&mut *self.handles.lock());
        for handle in handles {
            let () = handle.await;
        }
    }

    /// Wait for all tasks to complete (non-blocking).
    ///
    /// This method awaits all spawned tasks to finish. It consumes the task handles,
    /// so it can only be called once.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawner;
    /// use smol;
    ///
    /// # smol::block_on(async {
    /// let spawner = AsyncTaskSpawner::new();
    /// spawner.spawn(|| async {
    ///     smol::Timer::after(std::time::Duration::from_millis(10)).await;
    /// });
    /// spawner.wait_all().await; // Waits for the task to complete
    /// # });
    /// ```
    /// Chain method to spawn a task (consumes self)
    #[must_use]
    pub fn with_task<F, Fut>(self, task: F) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        self.spawn(task);
        self
    }

    /// Chain method to cancel tasks (consumes self)
    #[must_use]
    pub fn with_cancel(self) -> Self {
        self.cancel();
        self
    }
}

impl Default for AsyncTaskSpawner {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for `AsyncTaskSpawner` with ergonomic configuration.
///
/// Allows customizing the cancellation token and other settings before building
/// the spawner.
///
/// # Examples
///
/// ```rust
/// use trash_utilities::async::tasks::AsyncTaskSpawner;
/// use smol_cancellation_token::CancellationToken;
///
/// let token = CancellationToken::new();
/// let spawner = AsyncTaskSpawner::builder()
///     .with_cancellation_token(token)
///     .build();
/// ```
pub struct AsyncTaskSpawnerBuilder {
    token: Option<CancellationToken>,
}

impl AsyncTaskSpawnerBuilder {
    /// Create a new builder with default settings.
    ///
    /// # Returns
    ///
    /// An `AsyncTaskSpawnerBuilder` instance with no custom token set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawnerBuilder;
    ///
    /// let builder = AsyncTaskSpawnerBuilder::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self { token: None }
    }

    /// Set a custom cancellation token.
    ///
    /// If not set, a default token will be created.
    ///
    /// # Parameters
    ///
    /// * `token` - The cancellation token to use for the spawner.
    ///
    /// # Returns
    ///
    /// The builder instance for chaining.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawnerBuilder;
    /// use smol_cancellation_token::CancellationToken;
    ///
    /// let token = CancellationToken::new();
    /// let builder = AsyncTaskSpawnerBuilder::new()
    ///     .with_cancellation_token(token);
    /// ```
    #[must_use]
    pub fn with_cancellation_token(mut self, token: CancellationToken) -> Self {
        self.token = Some(token);
        self
    }

    /// Build the `AsyncTaskSpawner` with the configured settings.
    ///
    /// # Returns
    ///
    /// A new `AsyncTaskSpawner` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskSpawnerBuilder;
    ///
    /// let spawner = AsyncTaskSpawnerBuilder::new().build();
    /// ```
    #[must_use]
    pub fn build(self) -> AsyncTaskSpawner {
        AsyncTaskSpawner {
            token: self.token.unwrap_or_default(),
            handles: Mutex::new(Vec::new()),
        }
    }
}

impl Default for AsyncTaskSpawnerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Async task group for managing multiple related tasks (non-blocking).
///
/// `AsyncTaskGroup` provides a way to group related tasks together,
/// allowing collective cancellation and waiting. Similar to `AsyncTaskSpawner`,
/// but designed for tasks that are logically grouped.
///
/// # Examples
///
/// ```rust
/// use trash_utilities::async::tasks::AsyncTaskGroup;
/// use smol;
///
/// # smol::block_on(async {
/// let group = AsyncTaskGroup::new();
/// group.add_task(|| async {
///     println!("Task in group");
/// });
/// group.wait_all().await;
/// # });
/// ```
pub struct AsyncTaskGroup {
    token: CancellationToken,
    tasks: Mutex<Vec<smol::Task<()>>>,
}

impl AsyncTaskGroup {
    /// Create a new task group with a default cancellation token.
    ///
    /// # Returns
    ///
    /// A new `AsyncTaskGroup` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskGroup;
    ///
    /// let group = AsyncTaskGroup::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            token: CancellationToken::new(),
            tasks: Mutex::new(Vec::new()),
        }
    }

    /// Add a task to the group (non-blocking).
    ///
    /// The task will be executed asynchronously. If the group's cancellation
    /// token is cancelled before adding, the task will not be added.
    ///
    /// # Parameters
    ///
    /// * `task` - A closure that returns a future for the task.
    ///
    /// # Type Parameters
    ///
    /// * `F` - The type of the task closure.
    /// * `Fut` - The type of the future.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskGroup;
    /// use smol;
    ///
    /// # smol::block_on(async {
    /// let group = AsyncTaskGroup::new();
    /// group.add_task(|| async {
    ///     println!("Group task executed");
    /// });
    /// group.wait_all().await;
    /// # });
    /// ```
    pub fn add_task<F, Fut>(&self, task: F)
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = ()> + Send + 'static,
    {
        if self.token.is_cancelled() {
            return;
        }

        let task_handle = smol::spawn(async move {
            task().await;
        });

        self.tasks.lock().push(task_handle);
    }

    /// Cancel all tasks in the group.
    ///
    /// Sets the cancellation token, preventing new tasks from starting
    /// and potentially interrupting running ones.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskGroup;
    /// use smol;
    ///
    /// # smol::block_on(async {
    /// let group = AsyncTaskGroup::new();
    /// group.add_task(|| async {
    ///     // Task logic
    /// });
    /// group.cancel();
    /// # });
    /// ```
    pub fn cancel(&self) {
        self.token.cancel();
    }

    /// Wait for all tasks to complete (non-blocking).
    ///
    /// Awaits all tasks in the group to finish. Consumes the task handles.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use trash_utilities::async::tasks::AsyncTaskGroup;
    /// use smol;
    ///
    /// # smol::block_on(async {
    /// let group = AsyncTaskGroup::new();
    /// group.add_task(|| async {
    ///     smol::Timer::after(std::time::Duration::from_millis(10)).await;
    /// });
    /// group.wait_all().await;
    /// # });
    /// ```
    pub async fn wait_all(&self) {
        let tasks = std::mem::take(&mut *self.tasks.lock());
        for task in tasks {
            let () = task.await;
        }
    }
}

impl Default for AsyncTaskGroup {
    fn default() -> Self {
        Self::new()
    }
}