Producer

Struct Producer 

Source
pub struct Producer<T: Send + Sized + 'static> { /* private fields */ }
Expand description

Producer part of ring buffer.

Implementations§

Source§

impl<T: Send + Sized + 'static> Producer<T>

Source

pub fn capacity(&self) -> usize

Returns capacity of the ring buffer.

The capacity of the buffer is constant.

Source

pub fn is_empty(&self) -> bool

Checks if the ring buffer is empty.

The result is relevant until you push items to the producer.

Source

pub fn is_full(&self) -> bool

Checks if the ring buffer is full.

The result may become irrelevant at any time because of concurring activity of the consumer.

Examples found in repository?
examples/message.rs (line 24)
10fn main() {
11    let collector = Collector::new();
12
13    let buf = RingBuffer::<u8>::new(10);
14    let (mut prod, mut cons) = buf.split(&collector.handle());
15
16    let smsg = "The quick brown fox jumps over the lazy dog";
17
18    let pjh = thread::spawn(move || {
19        println!("-> sending message: '{}'", smsg);
20
21        let zero = [0];
22        let mut bytes = smsg.as_bytes().chain(&zero[..]);
23        loop {
24            if prod.is_full() {
25                println!("-> buffer is full, waiting");
26                thread::sleep(Duration::from_millis(1));
27            } else {
28                let n = prod.read_from(&mut bytes, None).unwrap();
29                if n == 0 {
30                    break;
31                }
32                println!("-> {} bytes sent", n);
33            }
34        }
35
36        println!("-> message sent");
37    });
38
39    let cjh = thread::spawn(move || {
40        println!("<- receiving message");
41
42        let mut bytes = Vec::<u8>::new();
43        loop {
44            if cons.is_empty() {
45                if bytes.ends_with(&[0]) {
46                    break;
47                } else {
48                    println!("<- buffer is empty, waiting");
49                    thread::sleep(Duration::from_millis(1));
50                }
51            } else {
52                let n = cons.write_into(&mut bytes, None).unwrap();
53                println!("<- {} bytes received", n);
54            }
55        }
56
57        assert_eq!(bytes.pop().unwrap(), 0);
58        let msg = String::from_utf8(bytes).unwrap();
59        println!("<- message received: '{}'", msg);
60
61        msg
62    });
63
64    pjh.join().unwrap();
65    let rmsg = cjh.join().unwrap();
66
67    assert_eq!(smsg, rmsg);
68}
Source

pub fn len(&self) -> usize

The length of the data stored in the buffer.

Actual length may be equal to or less than the returned value.

Source

pub fn remaining(&self) -> usize

The remaining space in the buffer.

Actual remaining space may be equal to or greater than the returning value.

Source

pub unsafe fn push_access<F>(&mut self, f: F) -> usize
where F: FnOnce(&mut [MaybeUninit<T>], &mut [MaybeUninit<T>]) -> usize,

Allows to write into ring buffer memory directly.

This function is unsafe because it gives access to possibly uninitialized memory

The method takes a function f as argument. f takes two slices of ring buffer content (the second one or both of them may be empty). First slice contains older elements.

f should return number of elements been written. There is no checks for returned number - it remains on the developer’s conscience.

The method always calls f even if ring buffer is full.

The method returns number returned from f.

§Safety

The method gives access to ring buffer underlying memory which may be uninitialized.

Source

pub unsafe fn push_copy(&mut self, elems: &[MaybeUninit<T>]) -> usize

Copies data from the slice to the ring buffer in byte-to-byte manner.

The elems slice should contain initialized data before the method call. After the call the copied part of data in elems should be interpreted as un-initialized.

Returns the number of items been copied.

§Safety

The method copies raw data into the ring buffer.

You should properly fill the slice and manage remaining elements after copy.

Source

pub fn push(&mut self, elem: T) -> Result<(), T>

Appends an element to the ring buffer. On failure returns an error containing the element that hasn’t been appended.

Examples found in repository?
examples/simple.rs (line 12)
6fn main() {
7    let collector = Collector::new();
8
9    let rb = RingBuffer::<i32>::new(2);
10    let (mut prod, mut cons) = rb.split(&collector.handle());
11
12    prod.push(0).unwrap();
13    prod.push(1).unwrap();
14    assert_eq!(prod.push(2), Err(2));
15
16    assert_eq!(cons.pop().unwrap(), 0);
17
18    prod.push(2).unwrap();
19
20    assert_eq!(cons.pop().unwrap(), 1);
21    assert_eq!(cons.pop().unwrap(), 2);
22    assert_eq!(cons.pop(), None);
23}
Source

pub fn push_each<F: FnMut() -> Option<T>>(&mut self, f: F) -> usize

Repeatedly calls the closure f and pushes elements returned from it to the ring buffer.

The closure is called until it returns None or the ring buffer is full.

The method returns number of elements been put into the buffer.

Source

pub fn push_iter<I: Iterator<Item = T>>(&mut self, elems: &mut I) -> usize

Appends elements from an iterator to the ring buffer. Elements that haven’t been added to the ring buffer remain in the iterator.

Returns count of elements been appended to the ring buffer.

Source

pub fn move_from( &mut self, other: &mut Consumer<T>, count: Option<usize>, ) -> usize

Removes at most count elements from the consumer and appends them to the producer. If count is None then as much as possible elements will be moved. The producer and consumer parts may be of different buffers as well as of the same one.

On success returns number of elements been moved.

Source§

impl<T: Copy + Send + Sized + 'static> Producer<T>

Source

pub fn push_slice(&mut self, elems: &[T]) -> usize

Appends elements from slice to the ring buffer. Elements should be Copy.

Returns count of elements been appended to the ring buffer.

Source§

impl Producer<u8>

Source

pub fn read_from( &mut self, reader: &mut dyn Read, count: Option<usize>, ) -> Result<usize>

Reads at most count bytes from Read instance and appends them to the ring buffer. If count is None then as much as possible bytes will be read.

Returns Ok(n) if read succeeded. n is number of bytes been read. n == 0 means that either read returned zero or ring buffer is full.

If read is failed or returned an invalid number then error is returned.

Examples found in repository?
examples/message.rs (line 28)
10fn main() {
11    let collector = Collector::new();
12
13    let buf = RingBuffer::<u8>::new(10);
14    let (mut prod, mut cons) = buf.split(&collector.handle());
15
16    let smsg = "The quick brown fox jumps over the lazy dog";
17
18    let pjh = thread::spawn(move || {
19        println!("-> sending message: '{}'", smsg);
20
21        let zero = [0];
22        let mut bytes = smsg.as_bytes().chain(&zero[..]);
23        loop {
24            if prod.is_full() {
25                println!("-> buffer is full, waiting");
26                thread::sleep(Duration::from_millis(1));
27            } else {
28                let n = prod.read_from(&mut bytes, None).unwrap();
29                if n == 0 {
30                    break;
31                }
32                println!("-> {} bytes sent", n);
33            }
34        }
35
36        println!("-> message sent");
37    });
38
39    let cjh = thread::spawn(move || {
40        println!("<- receiving message");
41
42        let mut bytes = Vec::<u8>::new();
43        loop {
44            if cons.is_empty() {
45                if bytes.ends_with(&[0]) {
46                    break;
47                } else {
48                    println!("<- buffer is empty, waiting");
49                    thread::sleep(Duration::from_millis(1));
50                }
51            } else {
52                let n = cons.write_into(&mut bytes, None).unwrap();
53                println!("<- {} bytes received", n);
54            }
55        }
56
57        assert_eq!(bytes.pop().unwrap(), 0);
58        let msg = String::from_utf8(bytes).unwrap();
59        println!("<- message received: '{}'", msg);
60
61        msg
62    });
63
64    pjh.join().unwrap();
65    let rmsg = cjh.join().unwrap();
66
67    assert_eq!(smsg, rmsg);
68}

Trait Implementations§

Source§

impl Write for Producer<u8>

Source§

fn write(&mut self, buffer: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Producer<T>

§

impl<T> !RefUnwindSafe for Producer<T>

§

impl<T> Send for Producer<T>

§

impl<T> Sync for Producer<T>

§

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

§

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