util.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. use std::cell::Cell;
  2. use crate::innerlude::*;
  3. // create a cell with a "none" value
  4. #[inline]
  5. pub fn empty_cell() -> Cell<Option<ElementId>> {
  6. Cell::new(None)
  7. }
  8. pub fn type_name_of<T>(_: T) -> &'static str {
  9. std::any::type_name::<T>()
  10. }
  11. use std::future::Future;
  12. use std::pin::Pin;
  13. use std::task::{Context, Poll};
  14. // use crate::task::{Context, Poll};
  15. /// Cooperatively gives up a timeslice to the task scheduler.
  16. ///
  17. /// Calling this function will move the currently executing future to the back
  18. /// of the execution queue, making room for other futures to execute. This is
  19. /// especially useful after running CPU-intensive operations inside a future.
  20. ///
  21. /// See also [`task::spawn_blocking`].
  22. ///
  23. /// [`task::spawn_blocking`]: fn.spawn_blocking.html
  24. ///
  25. /// # Examples
  26. ///
  27. /// Basic usage:
  28. ///
  29. /// ```
  30. /// # async_std::task::block_on(async {
  31. /// #
  32. /// use async_std::task;
  33. ///
  34. /// task::yield_now().await;
  35. /// #
  36. /// # })
  37. /// ```
  38. #[inline]
  39. pub async fn yield_now() {
  40. YieldNow(false).await
  41. }
  42. struct YieldNow(bool);
  43. impl Future for YieldNow {
  44. type Output = ();
  45. // The futures executor is implemented as a FIFO queue, so all this future
  46. // does is re-schedule the future back to the end of the queue, giving room
  47. // for other futures to progress.
  48. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  49. if !self.0 {
  50. self.0 = true;
  51. cx.waker().wake_by_ref();
  52. Poll::Pending
  53. } else {
  54. Poll::Ready(())
  55. }
  56. }
  57. }