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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! A structured concurrency construct which provides a way to spawn and run an arbitrary number of child tasks,
//! possibly await the results of each child task or even cancel all running child tasks.
//! This was heavily influenced by the Swift language's [`TaskGroup`](https://developer.apple.com/documentation/swift/taskgroup).
//!
//! # Installation
//! Add to your source code
//!
//! ```sh
//! cargo add spawn_groups
//! ```
//!
//! # Example
//!
//! ```ignore
//! use async_std::stream::StreamExt;
//! use spawn_groups::{with_err_spawn_group, GetType, Priority};
//! use std::time::Instant;
//! use surf::{Error, Client, http::Mime, StatusCode};
//!
//! async fn get_mimetype<AsStr: AsRef<str>>(url: AsStr, client: Client) -> Option<Mime> {
//! let Ok(resp) = client.get(url).send().await else {
//! return None;
//! };
//! resp.content_type()
//! }
//!
//! #[async_std::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = surf::Client::new();
//! let urls = [
//! "https://www.google.com",
//! "https://www.bing.com",
//! "https://www.yandex.com",
//! "https://www.duckduckgo.com",
//! "https://www.wikipedia.org",
//! "https://www.whatsapp.com",
//! "https://www.yahoo.com",
//! "https://www.amazon.com",
//! "https://www.baidu.com",
//! "https://www.youtube.com",
//! "https://facebook.com",
//! "https://www.instagram.com",
//! "https://tiktok.com",
//! ];
//! with_err_spawn_group(move |mut group| async move {
//! println!("About to start");
//! let now = Instant::now();
//! for url in urls {
//! let client = client.clone();
//! group.spawn_task(Priority::default(), async move {
//! let Some(mimetype) = get_mimetype(url, client).await else {
//! return Err(Error::from_str(StatusCode::ExpectationFailed, format!("No content type found for {}", url)));
//! }
//! Ok(format!("{url}: {}", mimetype))
//! })
//! }
//!
//! while let Some(result) = group.next().await {
//! if let Err(error) = result {
//! eprintln!("{}", error);
//! } else {
//! println!("{}", result.unwrap());
//! }
//! }
//! println("Ended");
//! println!("It took {} nanoseconds", now.elapsed().as_nanos());
//! })
//! .await;
//! Ok(())
//! }
//! ```
//!
//! # Usage
//!
//! To properly use this crate
//! * ``with_spawn_group`` for the creation of a dynamic number of asynchronous tasks that return a value. See [`with_spawn_group`](self::with_spawn_group)
//! for more information
//!
//! * ``with_type_spawn_group`` for the creation of a dynamic number of asynchronous tasks that return a value by specifying the type explicitly. See [`with_type_spawn_group`](self::with_type_spawn_group)
//! for more information
//!
//! * ``with_err_spawn_group`` for the creation of a dynamic number of asynchronous tasks that return a value or an error.
//! See [`with_err_spawn_group`](self::with_err_spawn_group)
//! for more information
//!
//! * ``with_err_type_spawn_group`` for the creation of a dynamic number of asynchronous tasks that return a value or an error by specifiying the return type and the error type explicitly.
//! See [`with_err_type_spawn_group`](self::with_err_type_spawn_group)
//! for more information
//!
//! * ``with_discarding_spawn_group`` for the creation of a dynamic number of asynchronous tasks that returns nothing.
//! See [`with_discarding_spawn_group`](self::with_discarding_spawn_group)
//! for more information
//!
//! * ``block_on`` polls future to finish. See [`block_on`](self::block_on)
//! for more information
//!
//! # Spawning Child Tasks
//!
//! Child tasks are spawned by calling either `spawn_task` or `spawn_task_unless_cancelled` methods on any of the spawn groups' instance.
//!
//! To avoid spawning new child tasks to an already cancelled spawn group, use ``spawn_task_unless_cancelled``
//! rather than the plain ``spawn_task`` which spawns new child tasks unconditionally.
//!
//! # Child Task Execution Order
//! Child tasks are scheduled in any order and spawned child tasks execute concurrently.
//!
//! # Cancellation
//!
//! By calling explicitly calling the ``cancel_all`` method on any of the spawn groups' instance, all running child tasks
//! are immediately cancelled.
//!
//! # Waiting
//!
//! By calling explicitly calling the ``wait_for_all_tasks`` method on any of the spawn groups' instance, all child tasks
//! are immediately awaited for.
//!
//! # Stream
//!
//! Both [`SpawnGroup`](self::spawn_group::SpawnGroup) and [`ErrSpawnGroup`](self::err_spawn_group::ErrSpawnGroup) structs implements the ``futures_lite::Stream``
//! which means that you can await the result of each child task asynchronously and with the help of ``StreamExt`` trait, one can call methods such as ``next``,
//! ``map``, ``filter_map``, ``fold`` and so much more.
//!
//! ```rust
//! use spawn_groups::with_spawn_group;
//! use futures_lite::StreamExt;
//! use spawn_groups::Priority;
//! use spawn_groups::GetType;
//!
//! # spawn_groups::block_on(async move {
//! with_spawn_group(|mut group| async move {
//! for i in 0..=10 {
//! group.spawn_task(Priority::default(), async move {
//! // simulate asynchronous operation
//! i
//! });
//! }
//!
//! // Loop over all the results of the child tasks spawned asynchronously
//! let mut counter = 0;
//! while let Some(x) = group.next().await {
//! counter += x;
//! }
//!
//! assert_eq!(counter, 55);
//!
//! }).await;
//! # });
//!
//! ```
//!
//! # Comparisons against existing alternatives
//! * [`JoinSet`](): Like this alternative, both await the completion of some or all of the child tasks,
//! spawn child tasks in an unordered manner and the result of their child tasks will be returned in the
//! order they complete and also cancel or abort all child tasks. Unlike the `Joinset`,
//! you can explicitly await for all the child task to finish their execution.
//! The Spawn group option provides a scope for the child tasks to execute.
//!
//! * [`FuturesUnordered`]() Like this alternative, both spawn child tasks in an unordered manner,
//! but FuturesUnordered doesn't immediately start running the spawned child tasks until it is being polled.
//! It also doesn't provide a way to cancel all child tasks.
//!
//! # Note
//! * Import ``StreamExt`` trait from ``futures_lite::StreamExt`` or ``futures::stream::StreamExt`` or ``async_std::stream::StreamExt`` to provide a variety of convenient combinator functions on the various spawn groups.
//! * To await all running child tasks to finish their execution, call ``wait_for_all`` or ``wait_non_async`` methods on the various group instances
//!
//! # Warning
//! * This crate relies on atomics, condition variables
//! * Avoid calling long, blocking, non asynchronous functions while using any of the spawn groups because it was built with asynchrony in mind.
pub use DiscardingSpawnGroup;
pub use ErrSpawnGroup;
pub use block_on;
pub use GetType;
pub use Priority;
pub use SpawnGroup;
use Future;
use PhantomData;
/// Starts a scoped closure that takes a mutable ``SpawnGroup`` instance as an argument which can execute any number of child tasks which its result values are of the generic ``ResultType`` type.
///
/// This closure ensures that before the function call ends, all spawned child tasks are implicitly waited for, or the programmer can explicitly wait by calling its ``wait_for_all()`` method
/// of the ``SpawnGroup`` struct.
///
/// This function use a threadpool of the same number of threads as the number of active processor count that is default amount of parallelism a program can use on the system for polling the spawned tasks
///
/// See [`SpawnGroup`](spawn_group::SpawnGroup)
/// for more.
///
/// # Parameters
///
/// * `of_type`: The type which the child task can return
/// * `body`: an async closure that takes a mutable instance of ``SpawnGroup`` as an argument
///
/// # Returns
///
/// Anything the ``body`` parameter returns
///
/// # Example
///
/// ```rust
/// use spawn_groups::GetType;
/// use spawn_groups::with_type_spawn_group;
/// use futures_lite::StreamExt;
/// use spawn_groups::Priority;
///
/// # spawn_groups::block_on(async move {
/// let final_result = with_type_spawn_group(i64::TYPE, |mut group| async move {
/// for i in 0..=10 {
/// group.spawn_task(Priority::default(), async move {
/// // simulate asynchronous operation
/// i
/// });
/// }
///
/// group.fold(0, |acc, x| {
/// acc + x
/// }).await
/// }).await;
///
/// assert_eq!(final_result, 55);
/// # });
/// ```
pub async
/// Starts a scoped closure that takes a mutable ``SpawnGroup`` instance as an argument which can execute any number of child tasks which its result values are of the generic ``ResultType`` type.
///
/// This closure ensures that before the function call ends, all spawned child tasks are implicitly waited for, or the programmer can explicitly wait by calling its ``wait_for_all()`` method
/// of the ``SpawnGroup`` struct.
///
/// This function use a threadpool of the same number of threads as the number of active processor count that is default amount of parallelism a program can use on the system for polling the spawned tasks
///
/// See [`SpawnGroup`](spawn_group::SpawnGroup)
/// for more.
///
/// # Parameters
///
/// * `body`: an async closure that takes a mutable instance of ``SpawnGroup`` as an argument
///
/// # Returns
///
/// Anything the ``body`` parameter returns
///
/// # Example
///
/// ```rust
/// use spawn_groups::GetType;
/// use spawn_groups::with_spawn_group;
/// use futures_lite::StreamExt;
/// use spawn_groups::Priority;
///
/// # spawn_groups::block_on(async move {
/// let final_result = with_spawn_group(|mut group| async move {
/// for i in 0..=10 {
/// group.spawn_task(Priority::default(), async move {
/// // simulate asynchronous operation
/// i
/// });
/// }
///
/// group.fold(0, |acc, x| {
/// acc + x
/// }).await
/// }).await;
///
/// assert_eq!(final_result, 55);
/// # });
/// ```
pub async
/// Starts a scoped closure that takes a mutable ``ErrSpawnGroup`` instance as an argument which can execute any number of child tasks which its result values are of the type ``Result<ResultType, ErrorType>``
/// where ``ResultType`` can be of type and ``ErrorType`` which is any type that implements the standard ``Error`` type.
///
/// This closure ensures that before the function call ends, all spawned child tasks are implicitly waited for, or the programmer can explicitly wait by calling its ``wait_for_all()`` method
/// of the ``ErrSpawnGroup`` struct
///
/// This function use a threadpool of the same number of threads as the number of active processor count that is default amount of parallelism a program can use on the system for polling the spawned tasks
///
/// See [`ErrSpawnGroup`](err_spawn_group::ErrSpawnGroup)
/// for more.
///
/// # Parameters
///
/// * `of_type`: The type which the child task can return
/// * `error_type`: The error type which the child task can return
/// * `body`: an async closure that takes a mutable instance of ``ErrSpawnGroup`` as an argument
///
/// # Returns
///
/// Anything the ``body`` parameter returns
///
/// # Example
///
/// ```rust
/// use std::error::Error;
/// use std::fmt::Display;
/// use spawn_groups::GetType;
/// use spawn_groups::with_err_type_spawn_group;
/// use futures_lite::StreamExt;
/// use spawn_groups::Priority;
///
/// #[derive(Debug)]
/// enum DivisibleByError {
/// THREE,
/// FIVE
/// }
///
/// impl Display for DivisibleByError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// match self {
/// DivisibleByError::THREE => f.write_str("Divisible by three"),
/// DivisibleByError::FIVE => f.write_str("Divisible by five")
/// }
/// }
/// }
///
/// impl Error for DivisibleByError {}
///
/// # spawn_groups::block_on(async move {
/// let final_results = with_err_type_spawn_group(u8::TYPE, DivisibleByError::TYPE, |mut group| async move {
/// for i in 1..=10 {
/// group.spawn_task(Priority::default(), async move {
/// // simulate asynchronous processing that might fail and
/// // return a value of ErrorType specified above
/// if i % 3 == 0 {
/// return Err(DivisibleByError::THREE)
/// } else if i % 5 == 0 {
/// return Err(DivisibleByError::FIVE)
/// }
/// Ok(i)
/// });
/// }
///
/// // Explicitly wait for the all spawned child tasks to finish
/// group.wait_for_all().await;
///
/// let mut sum_result = 0;
/// let mut divisible_by_five = 0;
/// let mut divisible_by_three = 0;
/// while let Some(group_result) = group.next().await {
/// if let Ok(result) = group_result {
/// sum_result += result;
/// } else if let Err(err_result) = group_result {
/// match err_result {
/// DivisibleByError::THREE => divisible_by_three += 1,
/// DivisibleByError::FIVE => divisible_by_five += 1
/// }
/// }
/// }
///
/// (sum_result, divisible_by_three, divisible_by_five)
///
/// }).await;
///
/// assert_eq!(final_results.0, 22);
/// assert_eq!(final_results.1, 3);
/// assert_eq!(final_results.2, 2);
/// # });
/// ```
pub async
/// Starts a scoped closure that takes a mutable ``ErrSpawnGroup`` instance as an argument which can execute any number of child tasks which its result values are of the type ``Result<ResultType, ErrorType>``
/// where ``ResultType`` can be of type and ``ErrorType`` which is any type that implements the standard ``Error`` type.
///
/// This closure ensures that before the function call ends, all spawned child tasks are implicitly waited for, or the programmer can explicitly wait by calling its ``wait_for_all()`` method
/// of the ``ErrSpawnGroup`` struct
///
/// This function use a threadpoolof the same number of threads as the number of active processor count that is default amount of parallelism a program can use on the system for polling the spawned tasks
///
/// See [`ErrSpawnGroup`](err_spawn_group::ErrSpawnGroup)
/// for more.
///
/// # Parameters
///
/// * `body`: an async closure that takes a mutable instance of ``ErrSpawnGroup`` as an argument
///
/// # Returns
///
/// Anything the ``body`` parameter returns
///
/// # Example
///
/// ```rust
/// use std::error::Error;
/// use std::fmt::Display;
/// use spawn_groups::GetType;
/// use spawn_groups::with_err_spawn_group;
/// use futures_lite::StreamExt;
/// use spawn_groups::Priority;
///
/// #[derive(Debug)]
/// enum DivisibleByError {
/// THREE,
/// FIVE
/// }
///
/// impl Display for DivisibleByError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// match self {
/// DivisibleByError::THREE => f.write_str("Divisible by three"),
/// DivisibleByError::FIVE => f.write_str("Divisible by five")
/// }
/// }
/// }
///
/// impl Error for DivisibleByError {}
///
/// # spawn_groups::block_on(async move {
/// let final_results = with_err_spawn_group(|mut group| async move {
/// for i in 1..=10 {
/// group.spawn_task(Priority::default(), async move {
/// // simulate asynchronous processing that might fail and
/// // return a value of ErrorType specified above
/// if i % 3 == 0 {
/// return Err(DivisibleByError::THREE)
/// } else if i % 5 == 0 {
/// return Err(DivisibleByError::FIVE)
/// }
/// Ok(i)
/// });
/// }
///
/// // Explicitly wait for the all spawned child tasks to finish
/// group.wait_for_all().await;
///
/// let mut sum_result = 0;
/// let mut divisible_by_five = 0;
/// let mut divisible_by_three = 0;
/// while let Some(group_result) = group.next().await {
/// if let Ok(result) = group_result {
/// sum_result += result;
/// } else if let Err(err_result) = group_result {
/// match err_result {
/// DivisibleByError::THREE => divisible_by_three += 1,
/// DivisibleByError::FIVE => divisible_by_five += 1
/// }
/// }
/// }
///
/// (sum_result, divisible_by_three, divisible_by_five)
///
/// }).await;
///
/// assert_eq!(final_results.0, 22);
/// assert_eq!(final_results.1, 3);
/// assert_eq!(final_results.2, 2);
/// # });
/// ```
pub async
/// Starts a scoped closure that takes a mutable ``DiscardingSpawnGroup`` instance as an argument which can execute any number of child tasks which return nothing.
///
/// Ensures that before the function call ends, all spawned tasks are implicitly waited for
///
/// This function use a threadpool of the same number of threads as the number of active processor count that is default amount of parallelism a program can use on the system for polling the spawned tasks
///
/// See [`DiscardingSpawnGroup`](discarding_spawn_group::DiscardingSpawnGroup)
/// for more.
///
/// # Parameters
///
/// * `body`: an async closure that takes an instance of ``DiscardingSpawnGroup`` as an argument
///
/// # Returns
///
/// Anything the ``body`` parameter returns
///
/// # Example
///
/// ```rust
/// use spawn_groups::GetType;
/// use spawn_groups::with_discarding_spawn_group;
/// use futures_lite::StreamExt;
/// use spawn_groups::Priority;
///
/// # spawn_groups::block_on(async move {
/// with_discarding_spawn_group(|mut group| async move {
/// for i in 0..11 {
/// group.spawn_task(Priority::default(), async move {
/// // asynchronous processing
/// // or some async network calls
/// });
/// }
///
/// }).await;
/// # });
/// ```
pub async