Struct thingbuf::mpsc::Receiver

source ·
pub struct Receiver<T, R = DefaultRecycle> { /* private fields */ }
Available on crate feature alloc only.
Expand description

Asynchronously receives values from associated Senders.

Instances of this struct are created by the channel and with_recycle functions.

Implementations§

source§

impl<T, R> Receiver<T, R>

source

pub fn recv_ref(&self) -> RecvRefFuture<'_, T>

Receives the next message for this receiver, by reference.

This method returns None if the channel has been closed and there are no remaining messages in the channel’s buffer. This indicates that no further values can ever be received from this Receiver. The channel is closed when all Senders have been dropped.

If there are no messages in the channel’s buffer, but the channel has not yet been closed, this method will wait until a message is sent or the channel is closed.

This method returns a RecvRef that can be used to read from (or mutate) the received message by reference. When the RecvRef is dropped, the receive operation completes and the slot occupied by the received message becomes usable for a future send_ref operation.

If all Senders for this channel write to the channel’s slots in place by using the send_ref or try_send_ref methods, this method allows messages that own heap allocations to be reused in place.

§Examples
use thingbuf::mpsc;
use std::fmt::Write;

#[tokio::main]
async fn main() {
    let (tx, rx) = mpsc::channel::<String>(100);
    tokio::spawn(async move {
        let mut value = tx.send_ref().await.unwrap();
        write!(value, "hello world!")
            .expect("writing to a `String` should never fail");
    });

    assert_eq!(Some("hello world!"), rx.recv_ref().await.as_deref().map(String::as_str));
    assert_eq!(None, rx.recv().await.as_deref());
}

Values are buffered:

use thingbuf::mpsc;
use std::fmt::Write;

#[tokio::main]
async fn main() {
    let (tx, rx) = mpsc::channel::<String>(100);

    write!(tx.send_ref().await.unwrap(), "hello").unwrap();
    write!(tx.send_ref().await.unwrap(), "world").unwrap();

    assert_eq!("hello", rx.recv_ref().await.unwrap().as_str());
    assert_eq!("world", rx.recv_ref().await.unwrap().as_str());
}
source

pub fn recv(&self) -> RecvFuture<'_, T, R>
where R: Recycle<T>,

Receives the next message for this receiver, by value.

This method returns None if the channel has been closed and there are no remaining messages in the channel’s buffer. This indicates that no further values can ever be received from this Receiver. The channel is closed when all Senders have been dropped.

If there are no messages in the channel’s buffer, but the channel has not yet been closed, this method will wait until a message is sent or the channel is closed.

When a message is received, it is moved out of the channel by value, and replaced with a new slot according to the configured recycling policy. If all Senders for this channel write to the channel’s slots in place by using the send_ref or try_send_ref methods, consider using the recv_ref method instead, to enable the reuse of heap allocations.

§Examples
use thingbuf::mpsc;

#[tokio::main]
async fn main() {

    let (tx, rx) = mpsc::channel(100);

    tokio::spawn(async move {
        tx.send(1).await.unwrap();
    });

    assert_eq!(Some(1), rx.recv().await);
    assert_eq!(None, rx.recv().await);
}

Values are buffered:

use thingbuf::mpsc;

#[tokio::main]
async fn main() {
    let (tx, rx) = mpsc::channel(100);

    tx.send(1).await.unwrap();
    tx.send(2).await.unwrap();

    assert_eq!(Some(1), rx.recv().await);
    assert_eq!(Some(2), rx.recv().await);
}
source

pub fn try_recv_ref(&self) -> Result<RecvRef<'_, T>, TryRecvError>
where R: Recycle<T>,

Attempts to receive the next message for this receiver by reference without waiting for a new message when the channel is empty.

This method differs from recv_ref by returning immediately if the channel is empty or closed.

§Errors

This method returns an error when the channel is closed or there are no remaining messages in the channel’s buffer.

§Examples
use thingbuf::mpsc::{channel, errors::TryRecvError};

let (tx, rx) = channel(100);
assert!(matches!(rx.try_recv_ref(), Err(TryRecvError::Empty)));

tx.try_send(1).unwrap();
drop(tx);

assert_eq!(*rx.try_recv_ref().unwrap(), 1);
assert!(matches!(rx.try_recv_ref(), Err(TryRecvError::Closed)));
source

pub fn try_recv(&self) -> Result<T, TryRecvError>
where R: Recycle<T>,

Attempts to receive the next message for this receiver by reference without waiting for a new message when the channel is empty.

This method differs from recv by returning immediately if the channel is empty or closed.

§Errors

This method returns an error when the channel is closed or there are no remaining messages in the channel’s buffer.

§Examples
use thingbuf::mpsc::{channel, errors::TryRecvError};

let (tx, rx) = channel(100);
assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));

tx.try_send(1).unwrap();
drop(tx);

assert_eq!(rx.try_recv().unwrap(), 1);
assert_eq!(rx.try_recv(), Err(TryRecvError::Closed));
source

pub fn poll_recv_ref( &self, cx: &mut Context<'_> ) -> Poll<Option<RecvRef<'_, T>>>

Attempts to receive a message by reference from this channel, registering the current task for wakeup if the a message is not yet available, and returning None if the channel has closed and all messages have been received.

Like Receiver::recv_ref, this method returns a RecvRef that can be used to read from (or mutate) the received message by reference. When the RecvRef is dropped, the receive operation completes and the slot occupied by the received message becomes usable for a future send_ref operation.

If all Senders for this channel write to the channel’s slots in place by using the send_ref or try_send_ref methods, this method allows messages that own heap allocations to be reused in place.

To wait asynchronously until a message becomes available, use the recv_ref method instead.

§Returns
  • Poll::Pending if no messages are available but the channel is not closed, or if a spurious failure happens.
  • Poll::Ready(Some(RecvRef<T>)) if a message is available.
  • Poll::Ready(None) if the channel has been closed (i.e., all Senders have been dropped), and all messages sent before it was closed have been received.

When the method returns Poll::Pending, the Waker in the provided Context is scheduled to receive a wakeup when a message is sent on any sender, or when the channel is closed. Note that on multiple calls to poll_recv_ref, only the Waker from the Context passed to the most recent call is scheduled to receive a wakeup.

source

pub fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Option<T>>
where R: Recycle<T>,

Attempts to receive a message by value from this channel, registering the current task for wakeup if the value is not yet available, and returning None if the channel has closed and all messages have been received.

When a message is received, it is moved out of the channel by value, and replaced with a new slot according to the configured recycling policy. If all Senders for this channel write to the channel’s slots in place by using the send_ref or try_send_ref methods, consider using the poll_recv_ref method instead, to enable the reuse of heap allocations.

To wait asynchronously until a message becomes available, use the recv method instead.

§Returns
  • Poll::Pending if no messages are available but the channel is not closed, or if a spurious failure happens.
  • Poll::Ready(Some(message)) if a message is available.
  • Poll::Ready(None) if the channel has been closed (i.e., all Senders have been dropped) and all messages sent before it was closed have been received.

When the method returns Poll::Pending, the Waker in the provided Context is scheduled to receive a wakeup when a message is sent on any sender, or when the channel is closed. Note that on multiple calls to poll_recv, only the Waker from the Context passed to the most recent call is scheduled to receive a wakeup.

source

pub fn is_closed(&self) -> bool

Returns true if the channel has closed (all corresponding Senders have been dropped).

If this method returns true, no new messages will become available on this channel. Previously sent messages may still be available.

source

pub fn capacity(&self) -> usize

Returns the total capacity of the channel for this Receiver. This includes both occupied and unoccupied entries.

To determine the channel’s remaining unoccupied capacity, use remaining instead.

§Examples
use thingbuf::mpsc::channel;

let (tx, rx) = channel::<usize>(100);
assert_eq!(rx.capacity(), 100);

Even after sending several messages, the capacity remains the same:


let (tx, rx) = channel::<usize>(100);
*tx.try_send_ref().unwrap() = 1;
*tx.try_send_ref().unwrap() = 2;
*tx.try_send_ref().unwrap() = 3;

assert_eq!(rx.capacity(), 100);
source

pub fn remaining(&self) -> usize

Returns the unoccupied capacity of the channel for this Receiver (i.e., how many additional elements can be sent before the channel will be full).

This is equivalent to subtracting the channel’s len from its capacity.

§Examples
use thingbuf::mpsc::channel;

let (tx, rx) = channel::<usize>(100);
assert_eq!(rx.remaining(), 100);

*tx.try_send_ref().unwrap() = 1;
*tx.try_send_ref().unwrap() = 2;
*tx.try_send_ref().unwrap() = 3;
assert_eq!(rx.remaining(), 97);

let _ = rx.try_recv_ref().unwrap();
assert_eq!(rx.remaining(), 98)
source

pub fn len(&self) -> usize

Returns the number of elements in the channel of this Receiver.

To determine the channel’s remaining unoccupied capacity, use remaining instead.

§Examples
use thingbuf::mpsc::channel;

let (tx, rx) = channel::<usize>(100);
assert_eq!(rx.len(), 0);

*tx.try_send_ref().unwrap() = 1;
*tx.try_send_ref().unwrap() = 2;
*tx.try_send_ref().unwrap() = 3;
assert_eq!(rx.len(), 3);

let _ = rx.try_recv_ref().unwrap();
assert_eq!(rx.len(), 2);
source

pub fn is_empty(&self) -> bool

Returns whether the number of elements in the channel of this Receiver is 0.

§Examples
use thingbuf::mpsc::channel;
let (tx, rx) = channel::<usize>(100);
assert!(rx.is_empty());

*tx.try_send_ref().unwrap() = 1;

assert!(!rx.is_empty());

Trait Implementations§

source§

impl<T: Debug, R: Debug> Debug for Receiver<T, R>

source§

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

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

impl<T, R> Drop for Receiver<T, R>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T, R> Freeze for Receiver<T, R>

§

impl<T, R = DefaultRecycle> !RefUnwindSafe for Receiver<T, R>

§

impl<T, R> Send for Receiver<T, R>
where R: Sync + Send, T: Sync + Send,

§

impl<T, R> Sync for Receiver<T, R>
where R: Sync + Send, T: Sync + Send,

§

impl<T, R> Unpin for Receiver<T, R>

§

impl<T, R = DefaultRecycle> !UnwindSafe for Receiver<T, R>

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<T, U> TryFrom<U> for T
where U: Into<T>,

§

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>,

§

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.