use std::thread; use ya_ring_buf::{ ClosedError, PushError, }; fn main() { // Create buffer let (mut sender, mut receiver) = ya_ring_buf::new_waitless(3); // We can push 3 elements... assert_eq!(sender.push(1), Ok(())); assert_eq!(sender.push(2), Ok(())); assert_eq!(sender.push(3), Ok(())); // ... until the buffer fills up. assert_eq!(sender.push(4), Err(PushError::Full(4))); // We can receive elements in the same order... assert_eq!(receiver.pop(), Ok(Some(1))); assert_eq!(receiver.pop(), Ok(Some(2))); assert_eq!(receiver.pop(), Ok(Some(3))); // Until there's nothing left assert_eq!(receiver.pop(), Ok(None)); // We can extend with an iterator: let mut remaining = sender.extend(0..4).unwrap(); // Items that wouldn't fit are returned: assert_eq!(remaining.next(), Some(3)); assert_eq!(remaining.next(), None); assert_eq!(receiver.pop(), Ok(Some(0))); assert_eq!(receiver.pop(), Ok(Some(1))); assert_eq!(receiver.pop(), Ok(Some(2))); assert_eq!(receiver.pop(), Ok(None)); // And most importantly, we can send across threads! let t1 = thread::spawn(move || { for i in 0.. { loop { match sender.push(i) { Ok(()) => { // Pushed OK! break; } Err(PushError::Full(v)) => { // Buffer full, come back later. // In a real program, you'd wait on something here, and // not busy loop! assert_eq!(v, i); thread::yield_now(); } Err(PushError::Closed(v)) => { // The receiver was dropped. assert_eq!(v, i); return; } } } } }); let t2 = thread::spawn(move || { for i in 0..10 { loop { match receiver.pop() { Ok(Some(v)) => { // Got an element, check it assert_eq!(v, i); break; } Ok(None) => { // No elements, come back later. // In a real program, you'd wait on something here, and // not busy loop! thread::yield_now(); } Err(ClosedError(())) => { // The sender was dropped return; } } } } }); t1.join().unwrap(); t2.join().unwrap(); }