Skip to main content

Sender

Struct Sender 

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

Sending side of the channel with sync API. It’s possible to convert it to async AsyncSender with as_async, to_async or clone_async based on software requirement.

§Examples

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

Implementations§

Source§

impl<T> Sender<T>

Source

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

Sends data to the channel.

§Examples
 s.send("Hello").unwrap();
Source

pub fn send_many(&self, elements: &mut VecDeque<T>) -> Result<(), SendError<T>>

Sends multiple elements from a VecDeque into the channel.

This method attempts to push as many items from elements as possible, respecting the channel’s capacity and the current state of the receiver side. It behaves similarly to repeatedly calling send for each element, but is more efficient because it holds the internal lock only while it can make progress.

  • If the channel is closed (no receivers), the first element that cannot be sent is returned inside SendError.
  • If the channel’s queue becomes full, mutex guard will be released and remaining elements stay in the supplied VecDeque to be send in a signal.
  • Elements are taken from the front of the deque (FIFO order). When the internal queue has spare capacity, elements are moved from the back of the deque into the internal queue to fill it as quickly as possible.
§Examples
use std::collections::VecDeque;
// Create a bounded channel with capacity 3
let (s, r) = kanal_plus::bounded::<i32>(3);

// Move the sender and the buffer into a new thread that will
// push as many items as the channel can accept.
let handle = std::thread::spawn(move || {
    /// // Prepare a deque with several values
     let mut buf = VecDeque::from(vec![1, 2, 3, 4, 5]);
    // `send_many` consumes items from the front of the deque.
    // It returns `Ok(())` when all possible items have been sent
    // or `Err` if the channel is closed. Here we unwrap the result
    // because the channel stays alive for the whole test.
    s.send_many(&mut buf).unwrap();

    // Return the (now‑partially‑filled) buffer so the main thread can
    // inspect the remaining elements.
    buf
});

// In the current thread we receive the three items that fit into the
// channel's capacity.
assert_eq!(r.recv().unwrap(), 1);
assert_eq!(r.recv().unwrap(), 2);
assert_eq!(r.recv().unwrap(), 3);

std::thread::sleep(std::time::Duration::from_millis(100));

// Sender now written two more items into the channel queue and exited.
let remaining = handle.join().expect("sender thread panicked");

assert_eq!(r.len(), 2);
assert_eq!(r.recv().unwrap(), 4);
assert_eq!(r.recv().unwrap(), 5);

The function returns Ok(()) when all elements have been successfully transferred, or Err(SendError<T>) containing the first element that could not be sent (typically because the receiver side has been closed).

Source

pub fn send_timeout( &self, data: T, duration: Duration, ) -> Result<(), SendTimeoutError<T>>

Sends data to the channel with a deadline, if send fails then the object will be dropped. you can use send_option_timeout if you like to keep the object in case of timeout.

§Examples
 s.send_timeout("Hello",Duration::from_millis(500)).unwrap();
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_async(&self) -> AsyncSender<T>

Clones Sender as the async version of it and returns it

Source

pub fn to_async(self) -> AsyncSender<T>

Converts Sender to AsyncSender and returns it

§Examples
  let (s, r) = kanal_plus::bounded(0);
  co(async move {
    let s=s.to_async();
    s.send("World").await;
  });
  let name=r.recv()?;
  println!("Hello {}!",name);
Source

pub fn as_async(&self) -> &AsyncSender<T>

Borrows Sender as AsyncSender and returns it

§Examples
  let (s, r) = kanal_plus::bounded(0);
  co(async move {
    s.as_async().send("World").await;
  });
  let name=r.recv()?;
  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 Sender<T>

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 Sender<T>

Source§

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

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

impl<T> Drop for Sender<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Sender<T>

§

impl<T> !RefUnwindSafe for Sender<T>

§

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

§

impl<T> Sync for Sender<T>

§

impl<T> Unpin for Sender<T>

§

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