1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! # Bondi
//!
//! This is built to provide an inter-process mechanism to communicate
//! between different parties.
//!
//! It allows a [Writer](writer::Writer) send a message that can be read
//! by multiple [Reader](reader::Reader) s concurrently. The role of `Bondi` is to sync these operations,
//! while keeping things **fast**.
//!
//! It's worth mentioning that the current implementation blocks on slow readers. It may be preffered to
//! drop slow consumers, when they cannot keep up with the writer's speed. This variant will likely be the
//! one introduced in the future, to enhance performance. However, this will mean that not every consumer
//! will _necessarily_ get all messages, but only the fast enough ones.
//!
//! ### A Simple example
//! ```no_run
//! // initialize a writer and two readers
//! // send 100 `Message`s, and receive them from different threads
//! #[derive(Debug, Clone)]
//! struct Message(usize);
//!
//! use bondi::Bondi;
//!
//! fn main() {
//!     let bondi = Bondi::new(100);
//!     let writer = bondi.get_tx().unwrap();
//!     let reader = bondi.get_rx().unwrap();
//!     let reader2 = bondi.get_rx().unwrap();
//!
//!     std::thread::spawn(move || {
//!         for i in 0..100 {
//!             writer.write(Message(i));
//!         }
//!     });
//!
//!     std::thread::spawn(move || {
//!         for i in 0..100 {
//!             reader.read();
//!         }
//!     });
//!
//!     std::thread::spawn(move || {
//!         for i in 0..100 {
//!             reader2.read();
//!         }
//!     }).join().unwrap();
//! }
//! ```

pub mod errors;
pub mod reader;
pub mod ring;
pub mod writer;

use errors::BondiError;
use reader::Reader;
use ring::Ring;

use anyhow::Result;
use writer::Writer;

use std::{cell::Cell, sync::Arc};
pub struct Bondi<T> {
    ring: Arc<Ring<T>>,
    writer_created: Cell<bool>,
}

impl<T: Clone + std::fmt::Debug> Bondi<T> {
    pub fn new(capacity: usize) -> Self {
        Self {
            ring: Arc::new(Ring::new(capacity)),
            writer_created: Cell::new(false),
        }
    }
    pub fn get_tx(&self) -> Result<Writer<T>> {
        if self.writer_created.get() {
            return Err(BondiError::WriterAlreadyExists.into());
        }

        self.writer_created.set(true);
        Ok(Writer::new(Arc::clone(&self.ring)))
    }

    pub fn get_rx(&self) -> Result<Reader<T>> {
        let num_consumers = self.ring.new_consumer()?;
        Ok(Reader::new(Arc::clone(&self.ring), num_consumers))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    #[cfg_attr(miri, ignore)]
    fn get_many_readers() {
        // smoke test to ensure that we can get multiple readers
        let bondi = Bondi::<usize>::new(100);
        let reader = bondi.get_rx().unwrap();
        let reader2 = bondi.get_rx().unwrap();
        std::thread::spawn(move || {
            let _ = reader.read();
        });

        std::thread::spawn(move || {
            let _ = reader2.read();
        });

        // there is nothing to read, so don't join
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    #[test]
    fn write_something() {
        let bondi = Bondi::<usize>::new(100);
        let writer = bondi.get_tx().unwrap();
        for i in 0..100 {
            writer.write(i);
        }
    }

    #[test]
    fn write_and_read_something_one_reader_no_wrap() {
        let bondi = Bondi::<usize>::new(100);
        let writer = bondi.get_tx().unwrap();
        let reader = bondi.get_rx().unwrap();
        std::thread::spawn(move || {
            for i in 0..100 {
                writer.write(i);
            }
        });

        std::thread::spawn(move || {
            for i in 0..100 {
                assert_eq!(reader.read(), i);
            }
        })
        .join()
        .unwrap();
    }

    #[test]
    fn write_and_read_something_two_readers_no_wrap() {
        let bondi = Bondi::<usize>::new(100);
        let writer = bondi.get_tx().unwrap();
        let reader = bondi.get_rx().unwrap();
        let reader2 = bondi.get_rx().unwrap();

        std::thread::spawn(move || {
            for i in 0..100 {
                writer.write(i);
                assert_eq!(reader.read(), i);
            }
        });

        std::thread::spawn(move || {
            for i in 0..100 {
                assert_eq!(reader2.read(), i);
                // dbg!(i);
            }
        })
        .join()
        .unwrap();
    }

    #[test]
    fn write_and_read_something_many_readers_with_wrapping() {
        let bondi = Bondi::<usize>::new(100);
        let writer = bondi.get_tx().unwrap();
        let readers = (0..99).into_iter().map(|_| bondi.get_rx().unwrap());
        let last_reader = bondi.get_rx().unwrap();
        std::thread::spawn(move || {
            for i in 0..200 {
                writer.write(i);
            }
        });

        for reader in readers {
            std::thread::spawn(move || {
                for i in 0..200 {
                    assert_eq!(reader.read(), i);
                }
            });
        }

        std::thread::spawn(move || {
            for i in 0..200 {
                assert_eq!(last_reader.read(), i);
            }
        })
        .join()
        .unwrap();
    }

    #[test]
    #[should_panic(expected = "No reader available")]
    fn too_many_readers() {
        let max_readers_available = 1000;
        let bondi = Bondi::<usize>::new(max_readers_available);
        let _readers = (0..max_readers_available)
            .into_iter()
            .map(|_| bondi.get_rx().unwrap())
            .collect::<Vec<_>>();
    }
}