3 unstable releases
0.2.0 | Feb 6, 2022 |
---|---|
0.1.1 | Feb 6, 2022 |
0.1.0 | Feb 5, 2022 |
#1180 in Asynchronous
23 downloads per month
26KB
325 lines
Future Handles
A rust library to complete futures via a remote handle.
async fn func() -> Option<u32> {
let (future, handle) = unsync::create();
func_with_callback(|| {
handle.complete(1);
});
match future.await {
// The callback was invoked and the result set via the handle.
Ok(res) => Some(res),
// The callback was never invoked, but the handle has been dropped.
Err(_) => None
}
}
lib.rs
:
Overview
A crate to complete futures via a remote handle.
Although it's design shouldn't restrain future_handles
use cases, this crate was primarily
conceived to bridge asynchronous functions running callbacks at competition with rust's
async/await paradigm.
Features
- No locking overhead for single-threaded environments.
- Optional thread-safety with spin-locks.
- Futures always complete with an error if the handle is dropped.
- Both channel-like and scoped APIs.
Examples
Channel-like API:
async fn func() -> Option<u32> {
let (future, handle) = unsync::create();
func_with_callback(|res| {
handle.complete(res);
});
future.await.ok()
}
Scoped API:
async fn func() -> Option<u32> {
let future = unsync::scoped(|handle| {
func_with_callback(|res| {
handle.complete(res);
});
});
future.await.ok()
}
Thread safety
This crate comes a non thread-safe unsync
implementation by default. To make the sync
thread-safe implementation available, enable the sync
feature.
Danger!
Do NOT do this!
async fn func() {
let (future, handle) = unsync::create();
// Start awaiting here...
future.await.unwrap();
// Now we'll never be able set the result!
handle.complete(1);
}
Awaiting a CompletableFuture
before setting the result or dropping the associated
CompleteHandle
will cause a deadlock!
Dependencies
~1–1.6MB
~33K SLoC