Skip to main content

AsyncSender

Struct AsyncSender 

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

Sending side of the channel with async API. It’s possible to convert it to sync Sender with as_sync, to_sync or clone_sync based on software requirement.

§Examples

let (sender, _r) = kanal_plus::bounded_async::<u64>(0);
let sync_sender=sender.clone_sync();

Implementations§

Source§

impl<T> AsyncSender<T>

Source

pub fn send(&self, data: T) -> SendFuture<'_, T>

Sends data asynchronously to the channel.

§Examples
s.send(1).await?;
assert_eq!(r.recv().await?,1);
Source

pub fn send_many<'a, 'b>( &'a self, elements: &'b mut VecDeque<T>, ) -> SendManyFuture<'a, 'b, T>

Sends multiple elements from a VecDeque into the channel asynchronously.

This method consumes the provided VecDeque by repeatedly popping elements from its front and sending each one over the channel. The operation completes when the deque is empty or when the channel is closed.

§Examples
let (s, r) = kanal_plus::bounded_async(3);
let handle = co(async move {
    let mut elems = VecDeque::from(vec![10, 20, 30, 40, 50]);
    // Send all elements in the deque
    s.send_many(&mut elems).await.unwrap();
});

// Receive the values in the same order they were sent
assert_eq!(r.recv().await?, 10);
assert_eq!(r.recv().await?, 20);
assert_eq!(r.recv().await?, 30);

//panic!("here");

tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
// Now the sender has sent the remaining elements
//handle.await.unwrap();

assert_eq!(r.recv().await?, 40);
assert_eq!(r.recv().await?, 50);
Source

pub fn try_send(&self, data: T) -> Result<(), SendTimeoutError<T>>

Tries sending to the channel without waiting on the waitlist, if send fails then the object will be dropped. It returns Ok(true) in case of a successful operation and Ok(false) for a failed one, or error in case that channel is closed. Important note: this function is not lock-free as it acquires a mutex guard of the channel internal for a short time.

§Examples
let (s, r) = kanal_plus::bounded(0);
let t=spawn( move || {
    loop{
        if s.try_send(1).is_ok() {
            break;
        }
    }
});
assert_eq!(r.recv()?,1);
Source

pub fn try_send_realtime(&self, data: T) -> Result<(), SendTimeoutError<T>>

Tries sending to the channel without waiting on the waitlist or for the internal mutex, if send fails then the object will be dropped. It returns Ok(true) in case of a successful operation and Ok(false) for a failed one, or error in case that channel is closed. Do not use this function unless you know exactly what you are doing.

§Examples
let (s, r) = kanal_plus::bounded(0);
let t=spawn( move || {
    loop{
        if s.try_send_realtime(1).is_ok() {
            break;
        }
    }
});
assert_eq!(r.recv()?,1);
Source

pub fn is_disconnected(&self) -> bool

Returns whether the receive side of the channel is closed or not.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
drop(r); // drop receiver and disconnect the receive side from the channel
assert_eq!(s.is_disconnected(),true);
Source

pub fn clone_sync(&self) -> Sender<T>

Clones AsyncSender as Sender with sync api of it.

§Examples
let (s, r) = kanal_plus::unbounded_async();
let sync_sender=s.clone_sync();
// JUST FOR EXAMPLE IT IS WRONG TO USE SYNC INSTANCE IN ASYNC CONTEXT
sync_sender.send(1)?;
assert_eq!(r.recv().await?,1);
Source

pub fn to_sync(self) -> Sender<T>

Converts AsyncSender to Sender and returns it.

§Examples
  let (s, r) = kanal_plus::bounded_async(0);
  // move to sync environment
  std::thread::spawn(move || {
    let s=s.to_sync();
    s.send("World")?;
    anyhow::Ok(())
  });
  let name=r.recv().await?;
  println!("Hello {}!",name);
Source

pub fn as_sync(&self) -> &Sender<T>

Borrows AsyncSender as Sender and returns it.

§Examples
  let (s, r) = kanal_plus::bounded_async(0);
  // move to sync environment
  std::thread::spawn(move || {
    s.as_sync().send("World")?;
    anyhow::Ok(())
  });
  let name=r.recv().await?;
  println!("Hello {}!",name);
Source

pub fn is_bounded(&self) -> bool

Returns whether the channel is bounded or not.

§Examples
let (s, r) = kanal_plus::bounded::<u64>(0);
assert_eq!(s.is_bounded(),true);
assert_eq!(r.is_bounded(),true);
let (s, r) = kanal_plus::unbounded::<u64>();
assert_eq!(s.is_bounded(),false);
assert_eq!(r.is_bounded(),false);
Source

pub fn len(&self) -> usize

Returns length of the queue.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
assert_eq!(s.len(),0);
assert_eq!(r.len(),0);
s.send(10);
assert_eq!(s.len(),1);
assert_eq!(r.len(),1);
Source

pub fn is_empty(&self) -> bool

Returns whether the channel queue is empty or not.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
assert_eq!(s.is_empty(),true);
assert_eq!(r.is_empty(),true);
Source

pub fn is_full(&self) -> bool

Returns whether the channel queue is full or not full channels will block on send and recv calls it always returns true for zero sized channels.

§Examples
let (s, r) = kanal_plus::bounded(1);
s.send("Hi!").unwrap();
assert_eq!(s.is_full(),true);
assert_eq!(r.is_full(),true);
Source

pub fn capacity(&self) -> usize

Returns capacity of channel (not the queue) for unbounded channels, it will return usize::MAX.

§Examples
let (s, r) = kanal_plus::bounded::<u64>(0);
assert_eq!(s.capacity(),0);
assert_eq!(r.capacity(),0);
let (s, r) = kanal_plus::unbounded::<u64>();
assert_eq!(s.capacity(),usize::MAX);
assert_eq!(r.capacity(),usize::MAX);
Source

pub fn receiver_count(&self) -> usize

Returns count of alive receiver instances of the channel.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
let receiver_clone=r.clone();
assert_eq!(r.receiver_count(),2);
Source

pub fn sender_count(&self) -> usize

Returns count of alive sender instances of the channel.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
let sender_clone=s.clone();
assert_eq!(r.sender_count(),2);
Source

pub fn close(&self) -> Result<(), CloseError>

Closes the channel completely on both sides and terminates waiting signals.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
// closes channel on both sides and has same effect as r.close();
s.close().unwrap();
assert_eq!(r.is_closed(),true);
assert_eq!(s.is_closed(),true);
Source

pub fn is_closed(&self) -> bool

Returns whether the channel is closed on both side of send and receive or not.

§Examples
let (s, r) = kanal_plus::unbounded::<u64>();
// closes channel on both sides and has same effect as r.close();
s.close();
assert_eq!(r.is_closed(),true);
assert_eq!(s.is_closed(),true);

Trait Implementations§

Source§

impl<T> Clone for AsyncSender<T>

Available on crate feature async only.
Source§

fn clone(&self) -> Self

Returns a duplicate 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> Debug for AsyncSender<T>

Available on crate feature async only.
Source§

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

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

impl<T> Drop for AsyncSender<T>

Available on crate feature async only.
Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T> Freeze for AsyncSender<T>

§

impl<T> !RefUnwindSafe for AsyncSender<T>

§

impl<T> Send for AsyncSender<T>
where T: Send,

§

impl<T> Sync for AsyncSender<T>

§

impl<T> Unpin for AsyncSender<T>

§

impl<T> !UnwindSafe for AsyncSender<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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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,

Source§

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

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.