hirun 0.1.22

A concurrent framework for asynchronous programming based on event-driven, non-blocking I/O mechanism
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
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
use crate::runtime::{Attr, FnOnceFuture, RawTaskContext, TaskRef};
use crate::{Error, Result};
use core::alloc::Layout;
use core::future::Future;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::pin::Pin;
use core::ptr::{self, NonNull};
use core::task::{Context, Poll};

/// 注意返回值类型为`Result<Future::Output>`.
/// 业务层负责处理异步调度失败的返回值.
/// 只用在异步环境中, task::spawn系列函数的返回值
pub struct AwaitHandle<T> {
    task: Option<TaskRef>,
    mark: PhantomData<*const T>,
}

unsafe impl<T: Send> Send for AwaitHandle<T> {}

impl<T> AwaitHandle<T> {
    /// 取消任务,如果成功取消则返回TRUE,否则说明异步任务已经执行完毕,取消失败.
    pub fn abort(&self) -> bool {
        if let Some(ref task) = self.task {
            return task.abort();
        }
        true
    }

    /// 如果异步任务已经执行完毕,返回TRUE,否则返回FALSE.
    pub fn is_finished(&self) -> bool {
        if let Some(ref task) = self.task {
            task.is_finished()
        } else {
            true
        }
    }

    /// 返回AbortHandle,可以按需取消任务执行.
    pub fn abort_handle(mut self) -> AbortHandle<T> {
        AbortHandle::<T> {
            task: self.task.take(),
            mark: PhantomData,
        }
    }
}

impl<T> Future for AwaitHandle<T> {
    type Output = Result<T>;
    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(ref task) = self.task {
            let mut output = MaybeUninit::<T>::uninit();
            match unsafe { task.output(ctx.waker(), output.as_mut_ptr().cast::<()>()) } {
                Poll::Ready(Ok(())) => {
                    ctx.cache(self.task.take().unwrap());
                    Poll::Ready(Ok(unsafe { output.assume_init_read() }))
                }
                Poll::Ready(Err(err)) => {
                    ctx.cache(self.task.take().unwrap());
                    Poll::Ready(Err(err))
                }
                Poll::Pending => Poll::Pending,
            }
        } else {
            Poll::Ready(Err(Error::default()))
        }
    }
}

impl<T> AwaitHandle<T> {
    pub(crate) fn new(task: TaskRef) -> Self {
        Self {
            task: Some(task),
            mark: PhantomData,
        }
    }

    pub(crate) fn null() -> Self {
        Self {
            task: None,
            mark: PhantomData,
        }
    }

    // 应该只在同步环境中调用此接口.
    pub(crate) fn join(self) -> <Self as Future>::Output {
        if let Some(task) = self.task {
            let mut output = MaybeUninit::<T>::uninit();
            unsafe {
                task.join(output.as_mut_ptr().cast::<()>())
                    .map(|_| output.assume_init_read())
            }
        } else {
            Err(Error::default())
        }
    }
}

pub struct AbortHandle<T> {
    task: Option<TaskRef>,
    mark: PhantomData<*const T>,
}

unsafe impl<T: Send> Send for AbortHandle<T> {}

impl<T> AbortHandle<T> {
    /// 取消任务,如果成功取消则返回TRUE,否则说明异步任务已经执行完毕,取消失败.
    pub fn abort(&self) -> bool {
        if let Some(ref task) = self.task {
            return task.abort();
        }
        true
    }
    /// 如果异步任务已经执行完毕,返回TRUE,否则返回FALSE.
    pub fn is_finished(&self) -> bool {
        if let Some(ref task) = self.task {
            task.is_finished()
        } else {
            true
        }
    }
}

/// 提供批量任务的创建工作,可以更高效的等待全部任务或者任何一个子任务的结束.
/// 只能在异步环境下创建异步子任务,以及等待子任务的结束.
/// 注意: 忽略Attr::id,如需要在指定运行时,使用runtime::JoinSet.
#[repr(C)]
pub struct JoinSet<T> {
    running: JoinList<T>,
    exited: JoinList<T>,
    jcnt: u32,
}

unsafe impl<T> Send for JoinSet<T> {}

impl<T> Default for JoinSet<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Drop for JoinSet<T> {
    fn drop(&mut self) {
        self.abort();
        for _ in Iter::new(self) {}
    }
}

impl<T> JoinSet<T> {
    /// 创建JoinSet,用于在一个异步环境下等待多个异步子任务执行完毕.
    /// 异步子任务只能在异步环境下创建.
    pub const fn new() -> Self {
        Self {
            jcnt: 0,
            running: JoinList::new(),
            exited: JoinList::new(),
        }
    }

    /// 是否创建了异步子任务.
    pub fn is_empty(&self) -> bool {
        self.jcnt == 0
    }

    /// 异步子任务的数量.
    pub fn len(&self) -> usize {
        self.jcnt as usize
    }

    /// 创建异步子任务
    pub async fn spawn<F>(&mut self, future: F) -> Result<()>
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_with(future, &Attr::default()).await
    }

    /// 创建异步子任务
    pub async fn spawn_with<F>(&mut self, future: F, attr: &Attr) -> Result<()>
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        let attr = Self::join_attr(attr);
        let handle = super::spawn_with(future, &attr).await;
        self.push_handle(handle)
    }

    /// 创建异步子任务
    pub async fn spawn_local<F>(&mut self, future: F) -> Result<()>
    where
        F: Future<Output = T> + 'static,
        T: 'static,
    {
        self.spawn_local_with(future, &Attr::default()).await
    }

    /// 创建异步子任务
    pub async fn spawn_local_with<F>(&mut self, future: F, attr: &Attr) -> Result<()>
    where
        F: Future<Output = T> + 'static,
        T: 'static,
    {
        let attr = Self::join_attr(attr);
        let handle = super::spawn_local_with(future, &attr).await;
        self.push_handle(handle)
    }

    /// 创建异步子任务
    pub async fn spawn_fn<F>(&mut self, f: F) -> Result<()>
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        self.spawn(FnOnceFuture::new(f)).await
    }

    /// 创建异步子任务
    pub async fn spawn_fn_with<F>(&mut self, f: F, attr: &Attr) -> Result<()>
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_with(FnOnceFuture::new(f), attr).await
    }

    /// 创建异步子任务
    pub async fn spawn_fn_local<F>(&mut self, f: F) -> Result<()>
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_local(FnOnceFuture::new(f)).await
    }

    /// 创建异步子任务
    pub async fn spawn_fn_local_with<F>(&mut self, f: F, attr: &Attr) -> Result<()>
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        self.spawn_local_with(FnOnceFuture::new(f), attr).await
    }

    /// 创建异步子任务
    pub fn abort(&mut self) {
        while let Some(node) = self.running.pop() {
            node.abort();
            unsafe {
                ptr::drop_in_place(node);
            }
        }
    }

    /// 等待所有任务结束后返回每个任务的执行结果.
    /// 执行结果的数据类型为`(id, Result<T>)`, `id`为`JoinSet::spawn`, 即任务创建的顺序,从0开始.
    /// 相对顺序等待每个任务的结束,比如:
    /// `
    /// for h in handles {
    ///     h.await;
    /// }
    /// `
    /// 本方法更加高效,只有全部子任务都结束后才会唤醒本任务.
    pub async fn wait_all(&mut self) -> impl Iterator<Item = (usize, Result<T>)> + '_ {
        WaitAll::new(self).await;
        Iter::new(self)
    }

    /// 等待任何一个任务结束后即返回任务的执行结果.
    /// 执行结果的数据类型为`(id, Result<T>)`, `id`为`JoinSet::spawn`, 即任务创建的顺序,从0开始.
    /// 相对顺序等待每个任务的结束,比如:
    /// `
    /// for h in handles {
    ///     h.await;
    /// }
    /// `
    /// 本方法更加高效,其返回顺序取决于任务结束顺序而非任务的创建顺序
    pub async fn wait_any(&mut self) -> Option<(usize, Result<T>)> {
        WaitAny::new(self).await
    }

    fn try_read_output(&mut self, ctx: &mut Context<'_>) -> u8 {
        let mut wcnt = 0;
        let mut waiting = JoinList::new();
        while let Some(node) = self.running.pop() {
            if node.read_output(ctx) {
                self.jcnt -= 1;
                self.exited.push(node);
            } else {
                waiting.push(node);
                wcnt += 1;
                if wcnt == 128 {
                    break;
                }
            }
        }
        waiting.move_head(&mut self.running);
        wcnt
    }

    pub(crate) fn join_attr(attr: &Attr) -> Attr {
        let layout = Layout::new::<JoinNode<T>>();
        let mut attr = attr.clone();
        let _ = attr.tail(layout);
        attr
    }

    pub(crate) fn push_handle(&mut self, mut handle: AwaitHandle<T>) -> Result<()> {
        if handle.task.is_none() {
            return Err(Error::default());
        }
        let layout = Layout::new::<JoinNode<T>>();
        let tail = unsafe { handle.task.as_ref().unwrap().tail(layout) };
        let node = unsafe { &mut *tail.cast_mut().cast::<MaybeUninit<JoinNode<T>>>() };
        let node = node.write(JoinNode::new(handle.task.take(), self.jcnt));
        self.running.push(node);
        self.jcnt += 1;
        Ok(())
    }
}

struct WaitAll<'a, T> {
    set: &'a mut JoinSet<T>,
}

impl<'a, T> WaitAll<'a, T> {
    fn new(set: &'a mut JoinSet<T>) -> Self {
        Self { set }
    }
}

impl<T> Future for WaitAll<'_, T> {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
        let wcnt = self.set.try_read_output(ctx);
        if wcnt > 0 {
            ctx.task().status.set_wake_expect(wcnt);
            Poll::Pending
        } else {
            // 必须恢复,此task后续的异步调用才能正常调度
            ctx.task().status.set_wake_expect(1);
            Poll::Ready(())
        }
    }
}

struct WaitAny<'a, T> {
    set: &'a mut JoinSet<T>,
}

impl<'a, T> WaitAny<'a, T> {
    fn new(set: &'a mut JoinSet<T>) -> Self {
        Self { set }
    }
}

impl<T> Future for WaitAny<'_, T> {
    type Output = Option<(usize, Result<T>)>;
    fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
        let _ = self.set.try_read_output(ctx);
        if let Some(node) = self.set.exited.pop() {
            let ret = node.get();
            unsafe {
                ptr::drop_in_place(node);
            }
            Poll::Ready(Some(ret))
        } else if self.set.running.empty() {
            Poll::Ready(None)
        } else {
            Poll::Pending
        }
    }
}

struct Iter<'a, T> {
    set: &'a mut JoinSet<T>,
}

impl<'a, T> Iter<'a, T> {
    fn new(set: &'a mut JoinSet<T>) -> Self {
        Self { set }
    }
}

impl<T> Iterator for Iter<'_, T> {
    type Item = (usize, Result<T>);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(node) = self.set.exited.pop() {
            let ret = node.get();
            unsafe {
                ptr::drop_in_place(node);
            }
            return Some(ret);
        }
        None
    }
}

#[repr(C)]
struct JoinNode<T> {
    task: Option<TaskRef>,
    output: Option<Result<T>>,
    next: Option<NonNull<JoinNode<T>>>,
    id: u32,
}

impl<T> JoinNode<T> {
    fn new(task: Option<TaskRef>, id: u32) -> Self {
        Self {
            id,
            task,
            output: None,
            next: None,
        }
    }

    fn get(&mut self) -> (usize, Result<T>) {
        (self.id as usize, self.output.take().unwrap())
    }

    fn abort(&mut self) {
        self.task.as_ref().unwrap().abort();
    }

    fn read_output(&mut self, ctx: &mut Context<'_>) -> bool {
        let mut output = MaybeUninit::<T>::uninit();
        let task = self.task.as_ref().unwrap();
        match unsafe { task.output(ctx.waker(), output.as_mut_ptr().cast::<()>()) } {
            Poll::Ready(Ok(())) => {
                self.output = Some(Ok(unsafe { output.assume_init_read() }));
                true
            }
            Poll::Ready(Err(err)) => {
                self.output = Some(Err(err));
                true
            }
            Poll::Pending => false,
        }
    }
}

struct JoinList<T> {
    first: Option<NonNull<JoinNode<T>>>,
    last: Option<NonNull<JoinNode<T>>>,
}

impl<T> JoinList<T> {
    const fn new() -> Self {
        Self {
            first: None,
            last: None,
        }
    }
    fn push(&mut self, node: &mut JoinNode<T>) {
        let node = NonNull::from(node);
        if let Some(mut last) = self.last {
            let last = unsafe { last.as_mut() };
            last.next = Some(node);
        } else {
            self.first = Some(node);
        }
        self.last = Some(node);
    }

    fn pop(&mut self) -> Option<&mut JoinNode<T>> {
        if let Some(mut first) = self.first {
            let first = unsafe { first.as_mut() };
            if self.last == self.first {
                self.first = None;
                self.last = None;
            } else {
                self.first = first.next;
            }
            return Some(first);
        }
        None
    }

    fn move_head(&mut self, dst: &mut Self) {
        if let Some(mut last) = self.last {
            let last = unsafe { last.as_mut() };
            last.next = dst.first;
            dst.first = self.first;
            self.last = None;
            self.first = None;
        }
    }

    fn empty(&self) -> bool {
        self.first.is_none()
    }
}