pub struct Sender<T, R = DefaultRecycle> { /* private fields */ }
std
only.Expand description
Synchronously receives values from associated Sender
s.
Instances of this struct are created by the channel
and
with_recycle
functions.
Implementations§
source§impl<T, R> Sender<T, R>where
R: Recycle<T>,
impl<T, R> Sender<T, R>where
R: Recycle<T>,
sourcepub fn send_ref(&self) -> Result<SendRef<'_, T>, Closed>
pub fn send_ref(&self) -> Result<SendRef<'_, T>, Closed>
Reserves a slot in the channel to mutate in place, blocking 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 Receiver
end of the channel
uses the Receiver::recv_ref
method for receiving from the channel,
this allows allocations for channel messages to be reused in place.
§Errors
If the Receiver
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::blocking;
use std::{fmt::Write, thread};
let (tx, rx) = blocking::channel::<String>(8);
// Spawn a thread that prints each message received from the channel:
thread::spawn(move || {
for _ in 0..10 {
let msg = rx.recv_ref().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() {
// 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;
}
sourcepub fn send(&self, val: T) -> Result<(), Closed<T>>
pub fn send(&self, val: T) -> Result<(), Closed<T>>
Sends a message by value, blocking 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 Receiver
end of the channel must receive messages by
moving them out of the channel by value (using the
Receiver::recv
method). When messages in the channel own
reusable heap allocations (such as String
s or Vec
s), and the
Receiver
doesn’t need to receive them by value, consider using
send_ref
instead, to enable allocation reuse.
§Errors
If the Receiver
end of the channel has been dropped, this
returns a Closed
error containing the sent value.
§Examples
use thingbuf::mpsc::blocking;
use std::thread;
let (tx, rx) = blocking::channel(8);
// Spawn a thread that prints each message received from the channel:
thread::spawn(move || {
for _ in 0..10 {
let msg = rx.recv().unwrap();
println!("received message {}", msg);
}
});
// Until the channel closes, write the current iteration to the channel.
let mut count = 1;
while tx.send(count).is_ok() {
count += 1;
}
sourcepub fn send_ref_timeout(
&self,
timeout: Duration
) -> Result<SendRef<'_, T>, SendTimeoutError>
Available on non-loom
only.
pub fn send_ref_timeout( &self, timeout: Duration ) -> Result<SendRef<'_, T>, SendTimeoutError>
loom
only.Reserves a slot in the channel to mutate in place, blocking until
there is a free slot to write to, waiting for at most timeout
.
This is similar to the send_timeout
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 Receiver
end of the channel
uses the Receiver::recv_ref
method for receiving from the channel,
this allows allocations for channel messages to be reused in place.
§Errors
Err
(
SendTimeoutError::Timeout
)
if the timeout has elapsed.Err
(
SendTimeoutError::Closed
)
if the channel has closed.
§Examples
Sending formatted strings by writing them directly to channel slots, in place:
use thingbuf::mpsc::{blocking, errors::SendTimeoutError};
use std::{fmt::Write, time::Duration, thread};
let (tx, rx) = blocking::channel::<String>(1);
thread::spawn(move || {
thread::sleep(Duration::from_millis(500));
let msg = rx.recv_ref().unwrap();
println!("{}", msg);
thread::sleep(Duration::from_millis(500));
});
thread::spawn(move || {
let mut value = tx.send_ref_timeout(Duration::from_millis(200)).unwrap();
write!(value, "hello").expect("writing to a `String` should never fail");
thread::sleep(Duration::from_millis(400));
let mut value = tx.send_ref_timeout(Duration::from_millis(200)).unwrap();
write!(value, "world").expect("writing to a `String` should never fail");
thread::sleep(Duration::from_millis(400));
assert_eq!(
Err(&SendTimeoutError::Timeout(())),
tx.send_ref_timeout(Duration::from_millis(200)).as_deref().map(String::as_str)
);
});
sourcepub fn send_timeout(
&self,
val: T,
timeout: Duration
) -> Result<(), SendTimeoutError<T>>
Available on non-loom
only.
pub fn send_timeout( &self, val: T, timeout: Duration ) -> Result<(), SendTimeoutError<T>>
loom
only.Sends a message by value, blocking until there is a free slot to
write to, for at most timeout
.
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_timeout
. This method is
most appropriate when messages don’t own reusable heap allocations,
or when the Receiver
end of the channel must receive messages by
moving them out of the channel by value (using the
Receiver::recv
method). When messages in the channel own
reusable heap allocations (such as String
s or Vec
s), and the
Receiver
doesn’t need to receive them by value, consider using
send_ref_timeout
instead, to enable allocation reuse.
§Errors
Err
(
SendTimeoutError::Timeout
)
if the timeout has elapsed.Err
(
SendTimeoutError::Closed
)
if the channel has closed.
§Examples
use thingbuf::mpsc::{blocking, errors::SendTimeoutError};
use std::{time::Duration, thread};
let (tx, rx) = blocking::channel(1);
thread::spawn(move || {
thread::sleep(Duration::from_millis(500));
let msg = rx.recv().unwrap();
println!("{}", msg);
thread::sleep(Duration::from_millis(500));
});
thread::spawn(move || {
tx.send_timeout(1, Duration::from_millis(200)).unwrap();
thread::sleep(Duration::from_millis(400));
tx.send_timeout(2, Duration::from_millis(200)).unwrap();
thread::sleep(Duration::from_millis(400));
assert_eq!(
Err(SendTimeoutError::Timeout(3)),
tx.send_timeout(3, Duration::from_millis(200))
);
});
sourcepub fn try_send_ref(&self) -> Result<SendRef<'_, T>, TrySendError>
pub fn try_send_ref(&self) -> Result<SendRef<'_, T>, TrySendError>
Attempts to reserve a slot in the channel to mutate in place, without blocking until capacity is available.
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 will never block.
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 argument passed to
channel
/with_recycle
), 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 Receiver
handle was dropped), the function returns TrySendError::Closed
.
Once the channel has closed, subsequent calls to try_send_ref
will
never succeed.
sourcepub fn try_send(&self, val: T) -> Result<(), TrySendError<T>>
pub fn try_send(&self, val: T) -> Result<(), TrySendError<T>>
Attempts to send a message by value immediately, without blocking until capacity is available.
This method differs from send
by returning immediately if the
channel’s buffer is full or no Receiver
exists. Compared with
send
, this method has two failure cases instead of one (one for
disconnection, one for a full buffer), and this method will never block.
§Errors
If the channel capacity has been reached (i.e., the channel has n
buffered values where n
is the argument passed to
channel
/with_recycle
), 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 Receiver
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
.
sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the total capacity of the channel for this Sender
.
This includes both occupied and unoccupied entries.
To determine the channel’s remaining unoccupied capacity, use
remaining
instead.
§Examples
use thingbuf::mpsc::blocking::channel;
let (tx, _) = channel::<usize>(100);
assert_eq!(tx.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!(tx.capacity(), 100);
sourcepub fn remaining(&self) -> usize
pub fn remaining(&self) -> usize
Returns the unoccupied capacity of the channel for this Sender
(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::blocking::channel;
let (tx, rx) = channel::<usize>(100);
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)
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the channel of this Sender
.
To determine the channel’s remaining unoccupied capacity, use
remaining
instead.
§Examples
use thingbuf::mpsc::blocking::channel;
let (tx, rx) = channel::<usize>(100);
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);