breadx_blocking/lib.rs
1// MIT/Apache2 License
2
3//! This crate provides the [`BlockingDisplay`] and [`BlockingDisplayImmut`] objects, which allow the user to
4//! convert a `breadx::Display` into a `breadx::AsyncDisplay`.
5//!
6//! Occasionally, you have an object that implements `breadx::Display` that you need to implement
7//! `breadx::AsyncDisplay`. Although the `*Display` objects in `breadx` can be easily changed to implement
8//! `breadx::AsyncDisplay` by changing the `Connection` to an `AsyncConnection`, `Display` implementations
9//! outside of `breadx` may not share this guarantee.
10//!
11//! `BlockingDisplay<T>` implements `AsyncDisplay` when `T` implements `Display`. `BlockingDisplayImmut<T>`
12//! implements `AsyncDisplay` and `&AsyncDisplay` when `T` implements `&Display`.
13//!
14//! This is implemented on the [`blocking`] thread-pool when the `tokio` feature is not enabled, and is
15//! implemented via [`spawn_blocking`] when it is.
16//!
17//! [`blocking`]: https://crates.io/crates/blocking
18//! [`spawn_blocking`]: https://docs.rs/tokio/1.9.0/tokio/task/fn.spawn_blocking.html
19
20#![forbid(unsafe_code)]
21
22//#[cfg(any(feature = "immutable", not(feature = "tokio")))]
23#[cfg(not(feature = "tokio-support"))]
24use std::future::Future;
25
26//#[cfg(feature = "immutable")]
27//use std::task::{Context, Poll};
28
29mod blocking_display;
30pub use blocking_display::BlockingDisplay;
31
32//#[cfg(feature = "immutable")]
33//mod immutable;
34//#[cfg(feature = "immutable")]
35//pub use immutable::BlockingDisplayImmut;
36
37#[cfg(not(feature = "tokio-support"))]
38pub(crate) fn spawn_blocking<R: Send + 'static>(
39 f: impl FnOnce() -> R + Send + 'static,
40) -> impl Future<Output = R> {
41 blocking::unblock(f)
42}
43
44#[cfg(feature = "tokio-support")]
45pub(crate) async fn spawn_blocking<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R {
46 tokio::task::spawn_blocking(f)
47 .await
48 .expect("Task error occurred")
49}
50
51/*#[cfg(feature = "immutable")]
52pub(crate) fn now_or_never<R>(f: impl Future<Output = R>) -> Option<R> {
53 // pin future on stack
54 pin_utils::pin_mut!(f);
55
56 // create context
57 let waker = noop_waker::noop_waker();
58 let mut ctx = Context::from_waker(&waker);
59
60 // poll future
61 match f.poll(&mut ctx) {
62 Poll::Ready(out) => Some(out),
63 Poll::Pending => None,
64 }
65}*/