orion_async/lib.rs
1//!
2//! # orion-async: 消除异步函数内部的本地变量必须支持Send Trait的约束,提升性能.
3//! # orion-async: Eliminate this constraint - the local variables of asynchronous functions must implement Send Trait
4//!
5//! 异步运行时框架的调度接口都会要求Future支持Send Trait,但现有编译器的实现中,
6//! 如果异步函数内部使用了不支持Send Trait的变量类型,则其生成Future不支持Send.
7//!
8//! 理想情况下异步函数生成的Future是否支持Send Trait应该仅有输入参数类型来决定,
9//! 在编译器未支持的情况下,可使用orion-async来解决,可以写更高效的异步代码.
10//!
11//! # Examples
12//!
13//! ```rust
14//! use std::rc::Rc;
15//! use std::future::Future;
16//!
17//! #[orion_async::future(body_send=true)]
18//! async fn foo() {
19//! let val = Rc::new(100);
20//! bar(*val).await;
21//! }
22//! async fn bar(val: i32) {
23//! }
24//! fn test_send_future<T: Future + Send>(t: T) {
25//! }
26//!
27//! test_send_future(foo());
28//!
29//! ```
30//!
31//! 可用于struct的方法
32//!
33//! ```rust
34//! use std::rc::Rc;
35//! use std::future::Future;
36//!
37//! struct Foo;
38//!
39//! impl Foo {
40//! #[orion_async::future(body_send=true)]
41//! async fn foo(self) -> i32 {
42//! let val = Rc::new(100);
43//! self.bar(*val).await
44//! }
45//! async fn bar(&self, val: i32) -> i32 {
46//! val + 100
47//! }
48//! }
49//! fn test_send_future<T: Future + Send>(t: T) {
50//! }
51//!
52//! let foo = Foo;
53//! test_send_future(foo.foo());
54//! ```
55//!
56
57use std::future::{ Future };
58use std::task::{ Context, Poll };
59use std::pin::Pin;
60
61pub use orion_async_macros::{
62 future
63};
64
65pub struct SendFuture<T: Future> {
66 future: T,
67}
68
69unsafe impl<T: Future> Send for SendFuture<T> {}
70
71impl<T: Future> SendFuture<T> {
72 pub unsafe fn new(future: T) -> Self {
73 Self { future: future }
74 }
75}
76
77impl<T: Future> Future for SendFuture<T> {
78 type Output = T::Output;
79 fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
80 Future::poll(unsafe { Pin::new_unchecked(&mut Pin::into_inner_unchecked(self).future) }, ctx)
81 }
82}
83