Struct Channel

Source
pub struct Channel<T> { /* private fields */ }
Expand description

An unsynchronized (!Sync), asynchronous and bounded channel.

Unlike unbounded channels, these are created with a constant maximum capacity, up to which values can be send to the channel. Any further sends will have to wait (block), until capacity is restored by receiving already stored values.

Implementations§

Source§

impl<T> Channel<T>

Source

pub fn with_initial_capacity(capacity: usize, initial: usize) -> Self

Returns a new bounded channel with pre-allocated initial capacity.

§Panics

Panics, if capacity is zero.

Source

pub fn from_iter(capacity: usize, iter: impl IntoIterator<Item = T>) -> Self

Returns a new bounded channel with a given capacity and pre-queued elements.

The initial capacity will be the difference between capacity and the number of elements returned by the Iterator. The total channel capacity will be the maximum of capacity and the iterator’s length.

§Panics

Panics, if capacity is zero.

Source

pub fn split(&mut self) -> (SenderRef<'_, T>, ReceiverRef<'_, T>)

Splits the channel into borrowing SenderRef and ReceiverRef handles.

§Examples
use async_unsync::bounded;

// must use a non-temporary binding for the channel
let mut chan = bounded::channel(1);
let (tx, mut rx) = chan.split();
tx.send(1).await.unwrap();

// dropping the handles will close the channel
drop((tx, rx));
assert!(chan.is_closed());

// ...but the queued value can still be received
assert_eq!(chan.try_recv(), Ok(1));
assert!(chan.try_recv().is_err());
Source

pub fn into_split(self) -> (Sender<T>, Receiver<T>)

Consumes and splits the channel into owning Sender and Receiver handles.

This requires one additional allocation over split, but avoids potential lifetime restrictions, since the returned handles are valid for the 'static lifetime, meaning they can be used in spawned (local) tasks.

Source

pub fn into_deque(self) -> VecDeque<T>

Converts into the underlying VecDeque container.

Source

pub fn len(&self) -> usize

Returns the number of queued elements.

This number may diverge from the channel’s reported capacity. This will occur, when capacity is decreased by reserving it without using it right away.

Source

pub fn max_capacity(&self) -> usize

Returns the maximum buffer capacity of the channel.

This is the capacity initially specified when creating the channel and remains constant.

Source

pub fn capacity(&self) -> usize

Returns the current capacity of the channel.

The capacity goes down when sending a value and goes up when receiving a value. When the capacity is zero, any subsequent sends will only resolve once sufficient capacity is available

Source

pub fn close(&self)

Closes the channel, ensuring that all subsequent sends will fail.

§Examples
use async_unsync::{bounded, TrySendError};

let chan = bounded::channel(1);
chan.close();
assert_eq!(chan.try_send(1), Err(TrySendError::Closed(1)));
Source

pub fn is_closed(&self) -> bool

Returns true if the channel is closed.

Source

pub fn is_empty(&self) -> bool

Returns true if the channel is empty.

Source

pub fn try_recv(&self) -> Result<T, TryRecvError>

Receives an element through the channel.

§Errors

Fails, if the channel is empty or disconnected.

Source

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

Polls the channel, resolving if an element was received or the channel is closed but ignoring whether there are any remaining Sender(s) or not.

§Panics

This may panic, if there are is more than one concurrent poll for receiving (i.e. either directly through poll_recv or by the future returned by recv) an element. In order to avoid this, there should be only one logical receiver per each channel.

Source

pub async fn recv(&self) -> Option<T>

Receives an element through the channel.

§Errors

Fails, if the channel is closed (i.e., all senders have been dropped).

Source

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

Sends a value through the channel if there is sufficient capacity.

§Errors

Fails, if the queue is closed or there is no available capacity.

Source

pub async fn send(&self, elem: T) -> Result<(), SendError<T>>

Sends a value, potentially waiting until there is capacity.

§Errors

Fails, if the queue is closed.

Source

pub fn try_reserve(&self) -> Result<Permit<'_, T>, TrySendError<()>>

Attempts to reserve a slot in the channel without blocking, if none are available.

The returned Permit can be used to immediately send a value to the channel at a later point. Dropping the permit without sending a value will return the capacity to the channel.

§Errors

Fails, if there are no available permits or the channel has been closed.

§Examples
use async_unsync::bounded;

let chan = bounded::channel(1);

// reserve capacity, reducing available slots to 0
let permit = chan.try_reserve().unwrap();
assert!(chan.try_send(1).is_err());
assert!(chan.try_reserve().is_err());

permit.send(1);
assert_eq!(chan.recv().await, Some(1));
Source

pub async fn reserve(&self) -> Result<Permit<'_, T>, SendError<()>>

Attempts to reserve a slot in the channel without blocking.

If no capacity is available in the channel, this will block until a slot becomes available. The returned Permit can be used to immediately send a value to the channel at a later point. Dropping the permit without sending a value will return the capacity to the channel.

§Errors

Fails, if there are no available permits or the channel has been closed.

§Examples
use async_unsync::bounded;

let chan = bounded::channel(1);

// reserve capacity, reducing available slots to 0
let permit = chan.reserve().await.unwrap();
assert!(chan.try_send(1).is_err());
assert!(chan.try_reserve().is_err());

permit.send(1);
assert_eq!(chan.recv().await, Some(1));

Trait Implementations§

Source§

impl<T> Debug for Channel<T>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> !Freeze for Channel<T>

§

impl<T> !RefUnwindSafe for Channel<T>

§

impl<T> !Send for Channel<T>

§

impl<T> !Sync for Channel<T>

§

impl<T> Unpin for Channel<T>
where T: Unpin,

§

impl<T> !UnwindSafe for Channel<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<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.