Receiver

Struct Receiver 

Source
pub struct Receiver<T: State> { /* private fields */ }
Expand description

Completion receiver for one-shot tasks

Implements Future directly, allowing direct .await usage on both owned values and mutable references

一次性任务完成通知接收器

直接实现了 Future,允许对拥有的值和可变引用都直接使用 .await

§Examples

§Using unit type for simple completion

use lite_sync::oneshot::lite::Sender;
 
let (notifier, receiver) = Sender::<()>::new();
 
tokio::spawn(async move {
    // ... do work ...
    notifier.notify(());  // Signal completion
});
 
// Two equivalent ways to await:
let result = receiver.await;               // Direct await via Future impl
assert_eq!(result, Ok(()));

§Awaiting on mutable reference

use lite_sync::oneshot::lite::Sender;
 
let (notifier, mut receiver) = Sender::<()>::new();
 
tokio::spawn(async move {
    // ... do work ...
    notifier.notify(());
});
 
// Can also await on &mut receiver
let result = (&mut receiver).await;
assert_eq!(result, Ok(()));

§Using custom state

use lite_sync::oneshot::lite::{State, Sender};
 
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CustomState {
    Success,
    Failure,
    Timeout,
}
 
impl State for CustomState {
    fn to_u8(&self) -> u8 {
        match self {
            CustomState::Success => 1,
            CustomState::Failure => 2,
            CustomState::Timeout => 3,
        }
    }
     
    fn from_u8(value: u8) -> Option<Self> {
        match value {
            1 => Some(CustomState::Success),
            2 => Some(CustomState::Failure),
            3 => Some(CustomState::Timeout),
            _ => None,
        }
    }
     
    fn pending_value() -> u8 {
        0
    }
     
    fn closed_value() -> u8 {
        255
    }
}
 
let (notifier, receiver) = Sender::<CustomState>::new();
 
tokio::spawn(async move {
    notifier.notify(CustomState::Success);
});
 
match receiver.await {
    Ok(CustomState::Success) => { /* Success! */ },
    Ok(CustomState::Failure) => { /* Failed */ },
    Ok(CustomState::Timeout) => { /* Timed out */ },
    Err(_) => { /* Sender dropped */ },
}

Implementations§

Source§

impl<T: State> Receiver<T>

Source

pub async fn recv(self) -> Result<T, SendError>

Receive a value asynchronously

This is equivalent to using .await directly on the receiver

Returns Err(SendError) if the sender was dropped before sending a value

异步接收一个值

这等同于直接在 receiver 上使用 .await

如果发送器在发送值之前被丢弃则返回 Err(SendError)

§Returns

Returns the completion state or error if sender was dropped

§返回值

返回完成状态或发送器被丢弃时的错误

Source

pub fn try_recv(&mut self) -> Result<Option<T>, SendError>

Try to receive a value without blocking

Returns None if no value has been sent yet Returns Err(SendError) if the sender was dropped

尝试接收值而不阻塞

如果还没有发送值则返回 None 如果发送器被丢弃则返回 Err(SendError)

§Returns

Returns Some(value) if value is ready, None if pending, or Err(SendError) if sender dropped

§返回值

如果值已就绪返回 Some(value),如果待处理返回 None,如果发送器被丢弃返回 Err(SendError)

Trait Implementations§

Source§

impl<T: State> Debug for Receiver<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: State> Future for Receiver<T>

Direct Future implementation for Receiver

This allows both receiver.await and (&mut receiver).await to work

Optimized implementation:

  • Fast path: Immediate return if already completed (no allocation)
  • Slow path: Direct waker registration (no Box allocation, just copy two pointers)
  • No intermediate future state needed
  • Detects when sender is dropped and returns error

为 Receiver 直接实现 Future

这允许 receiver.await(&mut receiver).await 都能工作

优化实现:

  • 快速路径:如已完成则立即返回(无分配)
  • 慢速路径:直接注册 waker(无 Box 分配,只复制两个指针)
  • 无需中间 future 状态
  • 检测发送器何时被丢弃并返回错误
Source§

type Output = Result<T, SendError>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more
Source§

impl<T: State> Unpin for Receiver<T>

Auto Trait Implementations§

§

impl<T> Freeze for Receiver<T>

§

impl<T> !RefUnwindSafe for Receiver<T>

§

impl<T> Send for Receiver<T>

§

impl<T> Sync for Receiver<T>

§

impl<T> !UnwindSafe for Receiver<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<F> IntoFuture for F
where F: Future,

Source§

type Output = <F as Future>::Output

The output that the future will produce on completion.
Source§

type IntoFuture = F

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.