Struct thingbuf::mpsc::StaticSender

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

Asynchronously sends values to an associated StaticReceiver.

Instances of this struct are created by the StaticChannel::split and ``StaticChannel::try_split` functions.

Implementations§

source§

impl<T, R> StaticSender<T, R>
where R: Recycle<T>,

source

pub async fn send_ref(&self) -> Result<SendRef<'_, T>, Closed>

Reserves a slot in the channel to mutate in place, waiting until there is a free slot to write to.

This is similar to the send method, but, rather than taking a message by value to write to the channel, this method reserves a writable slot in the channel, and returns a SendRef that allows mutating the slot in place. If the StaticReceiver end of the channel uses the StaticReceiver::recv_ref or StaticReceiver::poll_recv_ref methods for receiving from the channel, this allows allocations for channel messages to be reused in place.

§Errors

If the StaticReceiver end of the channel has been dropped, this returns a Closed error.

§Examples

Sending formatted strings by writing them directly to channel slots, in place:

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

static CHANNEL: mpsc::StaticChannel<String, 8> = mpsc::StaticChannel::new();

#[tokio::main]
async fn main() {
    let (tx, rx) = CHANNEL.split();

    // Spawn a task that prints each message received from the channel:
    tokio::spawn(async move {
        for _ in 0..10 {
            let msg = rx.recv_ref().await.unwrap();
            println!("{}", msg);
        }
    });

    // Until the channel closes, write formatted messages to the channel.
    let mut count = 1;
    while let Ok(mut value) = tx.send_ref().await {
        // Writing to the `SendRef` will reuse the *existing* string
        // allocation in place.
        write!(value, "hello from message {}", count)
            .expect("writing to a `String` should never fail");
        count += 1;
    }
}
source

pub async fn send(&self, val: T) -> Result<(), Closed<T>>

Sends a message by value, waiting until there is a free slot to write to.

This method takes the message by value, and replaces any previous value in the slot. This means that the channel will not function as an object pool while sending messages with send. This method is most appropriate when messages don’t own reusable heap allocations, or when the StaticReceiver end of the channel must receive messages by moving them out of the channel by value (using the StaticReceiver::recv method). When messages in the channel own reusable heap allocations (such as Strings or Vecs), and the StaticReceiver doesn’t need to receive them by value, consider using send_ref instead, to enable allocation reuse.

§Errors

If the StaticReceiver end of the channel has been dropped, this returns a Closed error containing the sent value.

§Examples
use thingbuf::mpsc;

static CHANNEL: mpsc::StaticChannel<i32, 8> = mpsc::StaticChannel::new();

#[tokio::main]
async fn main() {
    let (tx, rx) = CHANNEL.split();

    // Spawn a task that prints each message received from the channel:
    tokio::spawn(async move {
        for _ in 0..10 {
            let msg = rx.recv().await.unwrap();
            println!("received message {}", msg);
        }
    });

    // Until the channel closes, write the current iteration to the channel.
    let mut count = 1;
    while tx.send(count).await.is_ok() {
        count += 1;
    }
}
source

pub fn try_send_ref(&self) -> Result<SendRef<'_, T>, TrySendError>

Attempts to reserve a slot in the channel to mutate in place, without waiting for capacity.

This method differs from send_ref by returning immediately if the channel’s buffer is full or no Receiver exists. Compared with send_ref, this method has two failure cases instead of one (one for disconnection, one for a full buffer), and this method is not async, because it will never wait.

Like send_ref, this method returns a SendRef that may be used to mutate a slot in the channel’s buffer in place. Dropping the SendRef completes the send operation and makes the mutated value available to the Receiver.

§Errors

If the channel capacity has been reached (i.e., the channel has n buffered values where n is the usize const generic parameter of the StaticChannel), then TrySendError::Full is returned. In this case, a future call to try_send may succeed if additional capacity becomes available.

If the receive half of the channel is closed (i.e., the StaticReceiver handle was dropped), the function returns TrySendError::Closed. Once the channel has closed, subsequent calls to try_send_ref will never succeed.

source

pub fn try_send(&self, val: T) -> Result<(), TrySendError<T>>

Attempts to send a message by value immediately, without waiting for capacity.

This method differs from send by returning immediately if the channel’s buffer is full or no StaticReceiver exists. Compared with send, this method has two failure cases instead of one (one for disconnection, one for a full buffer), and this method is not async, because it will never wait.

§Errors

If the channel capacity has been reached (i.e., the channel has n buffered values where n is the usize const generic parameter of the StaticChannel), then TrySendError::Full is returned. In this case, a future call to try_send may succeed if additional capacity becomes available.

If the receive half of the channel is closed (i.e., the StaticReceiver handle was dropped), the function returns TrySendError::Closed. Once the channel has closed, subsequent calls to try_send will never succeed.

In both cases, the error includes the value passed to try_send.

source

pub fn capacity(&self) -> usize

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

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

§Examples
use thingbuf::mpsc::StaticChannel;

static CHANNEL: StaticChannel<usize, 100> = StaticChannel::new();

let (tx, _) = CHANNEL.split();
assert_eq!(tx.capacity(), 100);

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



let (tx, rx) = CHANNEL.split();
*tx.try_send_ref().unwrap() = 1;
*tx.try_send_ref().unwrap() = 2;
*tx.try_send_ref().unwrap() = 3;

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

pub fn remaining(&self) -> usize

Returns the unoccupied capacity of the channel for this StaticSender (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::StaticChannel;

static CHANNEL: StaticChannel<usize, 100> = StaticChannel::new();

let (tx, rx) = CHANNEL.split();
assert_eq!(tx.remaining(), 100);

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

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

pub fn len(&self) -> usize

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

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

§Examples
use thingbuf::mpsc::StaticChannel;

static CHANNEL: StaticChannel<usize, 100> = StaticChannel::new();

let (tx, rx) = CHANNEL.split();
assert_eq!(tx.len(), 0);

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

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

pub fn is_empty(&self) -> bool

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

§Examples
use thingbuf::mpsc::StaticChannel;

static CHANNEL: StaticChannel<usize, 100> = StaticChannel::new();

let (tx, rx) = CHANNEL.split();
assert!(tx.is_empty());

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

assert!(!tx.is_empty());

Trait Implementations§

source§

impl<T> Clone for StaticSender<T>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T, R: Debug> Debug for StaticSender<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 StaticSender<T, R>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

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

§

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

§

impl<T, R> Send for StaticSender<T, R>
where R: Sync, T: Sync,

§

impl<T, R> Sync for StaticSender<T, R>
where R: Sync, T: Sync,

§

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

§

impl<T, R = DefaultRecycle> !UnwindSafe for StaticSender<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> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.