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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#![cfg_attr(not(test), no_std)]
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use generic_array::{ArrayLength, GenericArray};
pub struct SpmsRing<T, N: ArrayLength<T>> {
buf: GenericArray<T, N>,
buf_len: usize,
read_idx: AtomicUsize,
write_idx: AtomicUsize,
filled: AtomicBool,
}
pub struct ReadToken {
idx: usize,
initialized: bool,
}
impl Default for ReadToken {
fn default() -> Self {
Self {
idx: 0,
initialized: false,
}
}
}
impl<T, N> Default for SpmsRing<T, N>
where
T: core::default::Default + Copy + core::fmt::Debug,
N: ArrayLength<T>,
{
fn default() -> Self {
Self::new_with_generation(0)
}
}
impl<T, N> SpmsRing<T, N>
where
T: core::default::Default + Copy + core::fmt::Debug,
N: ArrayLength<T>,
{
fn new_with_generation(gen: usize) -> Self {
let mut inst = Self {
buf: GenericArray::default(),
buf_len: 0,
read_idx: AtomicUsize::new(0),
write_idx: AtomicUsize::new(gen),
filled: AtomicBool::new(false),
};
inst.buf_len = inst.buf.len();
assert!(
inst.buf_len % 2 == 0,
"buffer capacity must be a power of two"
);
if gen > inst.buf_len {
inst.filled.store(true, Ordering::SeqCst);
inst.read_idx.store(
inst.write_idx.load(Ordering::SeqCst) - inst.buf_len,
Ordering::SeqCst,
);
}
inst
}
pub fn subscribe(&self) -> ReadToken {
ReadToken::default()
}
fn clamp_index(&self, index: usize) -> usize {
index & (self.buf_len - 1)
}
pub fn publish(&mut self, val: &T) {
let widx = self.write_idx.fetch_add(1, Ordering::SeqCst);
let clamped_widx = self.clamp_index(widx);
self.buf[clamped_widx] = *val;
if self.filled.load(Ordering::SeqCst) {
let new_ridx = widx.wrapping_sub(self.buf_len - 1);
self.read_idx.store(new_ridx, Ordering::SeqCst);
} else if clamped_widx == (self.buf_len - 1) {
self.filled.store(true, Ordering::SeqCst);
}
}
pub fn read_next(&self, token: &mut ReadToken) -> nb::Result<T, ()> {
let oldest = self.read_idx.load(Ordering::SeqCst);
let desired = if !token.initialized {
oldest
} else {
token.idx.wrapping_add(1)
};
let next_write = self.write_idx.load(Ordering::SeqCst);
if desired == next_write {
return Err(nb::Error::WouldBlock);
}
let wgap = next_write.wrapping_sub(desired);
let ridx = if wgap < self.buf_len { desired } else { oldest };
token.initialized = true;
token.idx = ridx;
let clamped_idx = self.clamp_index(ridx);
let val = self.buf[clamped_idx];
Ok(val)
}
pub fn empty(&self) -> bool {
self.write_idx.load(Ordering::SeqCst) == self.read_idx.load(Ordering::SeqCst)
}
pub fn at_capacity(&self) -> bool {
self.filled.load(Ordering::SeqCst)
}
pub fn available(&self) -> usize {
if !self.filled.load(Ordering::SeqCst) {
let widx = self.write_idx.load(Ordering::SeqCst);
let ridx = self.read_idx.load(Ordering::SeqCst);
let avail = widx.wrapping_sub(ridx);
assert!(avail <= self.buf_len);
avail
} else {
self.buf_len
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::sync::atomic::AtomicPtr;
use core::time;
use generic_array::typenum::{U24, U8};
use lazy_static::lazy_static;
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
#[derive(Default, Debug, Copy, Clone)]
struct Simple {
x: u32,
y: u32,
}
impl Simple {
fn new(x: u32, y: u32) -> Self {
Self { x, y }
}
}
#[test]
fn verify_nonblocking() {
const WRITE_COUNT: u32 = 5;
let mut q = SpmsRing::<Simple, U8>::default();
let mut read_token = q.subscribe();
let mut read_res = q.read_next(&mut read_token);
assert!(read_res.is_err());
assert_eq!(read_res.err().unwrap(), nb::Error::WouldBlock);
for i in 0..WRITE_COUNT {
let s = Simple::new(i, i);
q.publish(&s);
assert_eq!(q.available(), (i + 1) as usize);
read_res = q.read_next(&mut read_token);
assert!(read_res.is_ok());
read_res = q.read_next(&mut read_token);
assert_eq!(read_res.err().unwrap(), nb::Error::WouldBlock);
}
}
#[test]
fn alternating_write_read() {
const WRITE_COUNT: u32 = 5;
let mut q = SpmsRing::<Simple, U8>::default();
let mut read_token = q.subscribe();
for i in 0..WRITE_COUNT {
let s = Simple::new(i, i);
q.publish(&s);
assert_eq!(q.available(), (i + 1) as usize);
let cur_msg = q.read_next(&mut read_token).unwrap();
assert_eq!(i, cur_msg.x);
}
let one_more = q.read_next(&mut read_token);
assert!(one_more.is_err());
}
#[test]
fn sequential_write_read() {
const WRITE_COUNT: u32 = 5;
let mut q = SpmsRing::<Simple, U8>::default();
let mut read_token = q.subscribe();
for i in 0..WRITE_COUNT {
let s = Simple::new(i, i);
q.publish(&s);
}
assert_eq!(q.available() as u32, WRITE_COUNT);
for i in 0..WRITE_COUNT {
let cur_msg = q.read_next(&mut read_token).unwrap();
assert_eq!(i, cur_msg.x);
}
let one_more = q.read_next(&mut read_token);
assert!(one_more.is_err());
}
#[test]
fn buffer_overflow_write_read() {
const BUF_SIZE: u32 = 8;
const ITEM_COUNT: u32 = BUF_SIZE * 2;
let mut q = SpmsRing::<Simple, U8>::default();
for i in 0..ITEM_COUNT {
let s = Simple::new(i, i);
q.publish(&s);
}
assert_eq!(q.available() as u32, BUF_SIZE);
let mut read_token = q.subscribe();
let mut pre_val = BUF_SIZE - 1;
for _ in 0..BUF_SIZE {
let cur_msg = q.read_next(&mut read_token).unwrap();
let cur_val = cur_msg.x;
assert_eq!(cur_val - pre_val, 1);
pre_val = cur_val;
}
let one_more = q.read_next(&mut read_token);
assert!(one_more.is_err());
}
#[test]
fn generation_overflow_write_read() {
const BUF_SIZE: u32 = 8;
const ITEM_PUBLISH_COUNT: u32 = BUF_SIZE;
const FIRST_GENERATION: usize = usize::MAX - (ITEM_PUBLISH_COUNT / 2) as usize;
let mut q: SpmsRing<Simple, U8> = SpmsRing::new_with_generation(FIRST_GENERATION);
for i in 0..ITEM_PUBLISH_COUNT {
let s = Simple::new(i, i);
q.publish(&s);
}
assert_eq!(q.available() as u32, BUF_SIZE);
let mut read_token = q.subscribe();
let mut pre_val = 0;
for _read_count in 0..BUF_SIZE {
let cur_msg = q.read_next(&mut read_token).unwrap();
let cur_val = cur_msg.x;
if 0 != pre_val {
assert_eq!(cur_val.wrapping_sub(pre_val), 1);
}
pre_val = cur_val;
}
for i in 0..5 {
let s = Simple::new(i, i);
q.publish(&s);
}
assert_eq!(q.available() as u32, BUF_SIZE);
}
#[test]
fn multithreaded_writer_readers() {
const BUF_SIZE: u32 = 24;
const ITEM_PUBLISH_COUNT: u32 = 3 * BUF_SIZE;
lazy_static! {
static ref Q_PTR: AtomicPtr<SpmsRing::<Simple, U24>> = AtomicPtr::default();
};
let mut shared_q = SpmsRing::<Simple, U24>::default();
Q_PTR.store(&mut shared_q, Ordering::Relaxed);
let (tx, rx): (Sender<u32>, Receiver<u32>) = mpsc::channel();
let mut children = Vec::new();
const NUM_SUBSCRIBERS: u32 = 128;
for subscriber_id in 0..NUM_SUBSCRIBERS {
let thread_tx = tx.clone();
let child = thread::Builder::new()
.name(format!("sid{}", subscriber_id).to_string())
.spawn(move || {
let mut read_tok =
unsafe { Q_PTR.load(Ordering::SeqCst).as_ref().unwrap().subscribe() };
let mut read_count = 0;
let mut prev_val = 0;
let mut read_chain = vec![];
let my_sub_id: u32 = subscriber_id;
while read_count < BUF_SIZE {
let msg_r = unsafe {
Q_PTR
.load(Ordering::SeqCst)
.as_ref()
.unwrap()
.read_next(&mut read_tok)
};
match msg_r {
Ok(msg) => {
read_count += 1;
let cur_val = msg.x;
read_chain.push((read_tok.idx, cur_val));
if cur_val < prev_val {
println!("sid {}: {:?}", my_sub_id, read_chain);
break;
}
prev_val = cur_val;
}
Err(nb::Error::WouldBlock) => {}
_ => break,
}
}
let send_res = thread_tx.send(read_count);
if send_res.is_err() {
println!("couldn't report: {:?}", send_res)
}
})
.expect("couldn't spawn child");
children.push(child);
}
thread::sleep(time::Duration::from_millis(1));
let writer_thread = thread::spawn(move || {
for i in 0..ITEM_PUBLISH_COUNT {
let s = Simple::new(i, i);
unsafe { Q_PTR.load(Ordering::SeqCst).as_mut().unwrap().publish(&s) }
}
let filled = unsafe { Q_PTR.load(Ordering::SeqCst).as_ref().unwrap().at_capacity() };
assert!(filled);
});
writer_thread.join().expect("writer thread panicked");
for _ in 0..NUM_SUBSCRIBERS {
let num_read = rx.recv().expect("couldn't receive num_read");
println!("num_read: {}", num_read);
}
for child in children {
child.join().expect("child panicked");
}
}
}