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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Provides strategies used by handles when waiting for sequences on the ring buffer.
//!
//! Also provided are three traits for implementing your own wait logic.
//!
//! # Performance
//!
//! Each strategy provides a tradeoff between latency and CPU use, as detailed in their separate
//! docs, but this is not the only aspect to consider when optimizing performance. The size of the
//! strategy is also an important factor.
//!
//! Each handle struct includes a wait strategy. So the size of the strategy may impact performance
//! if, for example, that additional size prevents the handle from fitting into a single cache line.
//!
//! Cache lines are commonly `64`, or `128` bytes.
//!
//! When the wait strategy is zero-sized, each handle has the following size (in bytes, on a 64-bit
//! system). Changes in these sizes, if compiled for a single system, are considered breaking.
//!
//! | Handle | size |
//! |--------------------------------------------------|------|
//! | [`Consumer`](crate::handles::Consumer) | 40 |
//! | [`Producer`](crate::handles::Producer) | 40 |
//! | [`MultiProducer`](crate::handles::MultiProducer) | 48 |
//!
//! And here are the minimum sizes of the provided strategies (on a 64-bit system), assuming
//! `size_of::<W>() == 0`. Changes in these sizes are also considered breaking.
//!
//! | Strategy | size |
//! |-------------------------------|------|
//! | [`WaitBusy`] | 0 |
//! | [`WaitBusyHint`] | 0 |
//! | [`WaitYield`] | 0 |
//! | [`WaitSleep`] | 8 |
//! | [`WaitPhased<W>`](WaitPhased) | 16 |
//! | [`Timeout<W>`](Timeout) | 8 |
//!
//! Various provided strategies are limited to wait durations of `u64::MAX` nanoseconds, which is
//! done in order to keep their sizes small. Storing a [`Duration`] instead would double the
//! minimum size of these strategies.
//! ```
//! use std::time::Duration;
//!
//! assert_eq!(size_of::<Duration>(), 16);
//! assert_eq!(size_of::<u64>(), 8);
//! ```
use crateBarrier;
use ;
/// Implement to provide logic which will run inside a wait loop.
///
/// This trait is unsuitable when state needs to be held across loop iterations, since
/// [`waiting`](Waiting::waiting) cannot observe outside of the loop.
///
/// If state or fallibility is required, implement [`WaitStrategy`] or [`TryWaitStrategy`] instead.
///
/// If a type, `T`, implements `Waiting`, then `T` will implement `WaitStrategy`, and
/// [`Timeout<T>`](Timeout) will implement `TryWaitStrategy`.
///
/// # Examples
/// ```
/// use ansa::wait::Waiting;
///
/// struct MyWaiter;
///
/// impl Waiting for MyWaiter {
/// fn waiting(&self) {
/// // stuff that will happen on each loop iteration
/// }
/// }
/// ```
/// Implement to provide a wait loop which runs as a handle waits for a sequence.
///
/// If a wait strategy does not require either control over loop behaviour, or carrying state
/// across loop iterations, then prefer implementing [`Waiting`] instead, as it provides a safe
/// interface.
///
/// A well-behaved implementation should return as soon as `barrier sequence >= desired_seq`, but
/// this is not a safety condition.
///
/// # Safety
///
/// This trait is unsafe as there is no guard against invalid implementations of
/// [`wait`](WaitStrategy::wait) causing Undefined Behaviour. Valid implementations must satisfy
/// the following conditions:
/// 1) `wait` must not return while `barrier sequence < desired_seq`.
/// 2) `wait` must return the last read `barrier sequence`.
///
/// If `wait` does not abide by these conditions, then writes to the ring buffer may overlap with
/// other accesses, causing Undefined Behaviour due to mutable aliasing.
///
/// # Examples
/// ```
/// use ansa::{Barrier, wait::WaitStrategy};
///
/// /// Prints the count of wait loop iterations after waiting.
/// struct CountIters;
///
/// // SAFETY: wait returns once barrier_seq >= desired_seq, with barrier_seq itself
/// unsafe impl WaitStrategy for CountIters {
/// fn wait(&self, desired_seq: i64, barrier: &Barrier) -> i64 {
/// let mut counter = 0;
/// let mut barrier_seq = barrier.sequence();
/// while barrier_seq < desired_seq {
/// barrier_seq = barrier.sequence();
/// counter += 1;
/// }
/// println!("looped: {} times", counter);
/// barrier_seq
/// }
/// }
/// ```
///
/// The following example shows only _some_ of the possible implementation mistakes that will
/// cause UB.
/// ```
/// use ansa::{Barrier, wait::WaitStrategy};
///
/// struct BadWait;
///
/// // ** NOT SAFE **
/// unsafe impl WaitStrategy for BadWait {
/// fn wait(&self, desired_seq: i64, barrier: &Barrier) -> i64 {
/// let mut barrier_seq = barrier.sequence();
///
/// // VERY BAD: we've changed only one character from `<` to `>`, but this makes
/// // it possible for waiting to end before the barrier has advanced. Could cause
/// // mutable aliasing, and thus UB.
/// while barrier_seq > desired_seq {
/// barrier_seq = barrier.sequence();
/// }
/// // VERY BAD: we return a sequence unrelated to the barrier, possibly leaving
/// // the disruptor in an inconsistent, non-recoverable state if a handle uses
/// // the value. Could cause mutable aliasing, and thus UB.
/// 10
/// }
/// }
/// ```
pub unsafe
// SAFETY: wait returns once barrier_seq >= desired_seq, with barrier_seq itself
unsafe
/// Implement to provide a fallible wait loop which runs as a handle waits for a sequence.
///
/// If a wait strategy is not fallible, or does not require either control over loop behaviour, or
/// carrying state across loop iterations, then prefer implementing [`Waiting`] instead, as it
/// provides a safe interface.
///
/// A well-behaved implementation should return as soon as `barrier sequence >= desired_seq`, but
/// this is not a safety condition.
///
/// # Safety
///
/// This trait is unsafe as there is no guard against invalid implementations of
/// [`try_wait`](TryWaitStrategy::try_wait) causing Undefined Behaviour. Valid implementations must
/// satisfy the following conditions:
/// 1) `try_wait` must not successfully return while `barrier sequence < desired_seq`.
/// 2) `try_wait`, if successful, must return the last read `barrier sequence`.
///
/// If `try_wait` does not abide by these conditions, then writes to the ring buffer may overlap
/// with other accesses, causing Undefined Behaviour due to mutable aliasing.
///
/// Note that no conditions limit when `try_wait` can return an error.
///
/// # Examples
/// ```
/// use ansa::{Barrier, wait::TryWaitStrategy};
///
/// /// Wait until `max` iterations of the wait loop.
/// struct MaxIters {
/// max: usize
/// }
///
/// struct MaxItersError;
///
/// // SAFETY: only successful if barrier_seq >= desired_seq; returns barrier_seq
/// unsafe impl TryWaitStrategy for MaxIters {
/// type Error = MaxItersError;
///
/// fn try_wait(&self, desired_seq: i64, barrier: &Barrier) -> Result<i64, Self::Error> {
/// let mut iters = 0;
/// let mut barrier_seq = barrier.sequence();
/// while barrier_seq < desired_seq {
/// if iters >= self.max {
/// return Err(MaxItersError)
/// }
/// barrier_seq = barrier.sequence();
/// iters += 1;
/// }
/// Ok(barrier_seq)
/// }
/// }
/// ```
///
/// Implementing a no wait strategy is also possible (though not necessary if using
/// [`Producer::wait_range`](crate::Producer::wait_range) or
/// [`Consumer::wait_range`](crate::Consumer::wait_range)).
/// ```
/// use ansa::{Barrier, wait::TryWaitStrategy};
///
/// struct NoWait;
///
/// struct NoWaitError;
///
/// // SAFETY: only successful if barrier_seq >= desired_seq; returns barrier_seq
/// unsafe impl TryWaitStrategy for NoWait {
/// type Error = NoWaitError;
///
/// fn try_wait(&self, desired_seq: i64, barrier: &Barrier) -> Result<i64, Self::Error> {
/// match barrier.sequence() {
/// barrier_seq if barrier_seq < desired_seq => Err(NoWaitError),
/// barrier_seq => Ok(barrier_seq),
/// }
/// }
/// }
/// ```
///
/// The following example shows only _some_ of the possible implementation mistakes that will
/// cause UB.
/// ```
/// use ansa::{Barrier, wait::TryWaitStrategy};
///
/// struct BadWait;
///
/// // ** NOT SAFE **
/// unsafe impl TryWaitStrategy for BadWait {
/// type Error = ();
///
/// fn try_wait(&self, desired_seq: i64, barrier: &Barrier) -> Result<i64, Self::Error> {
/// let mut barrier_seq = barrier.sequence();
///
/// // VERY BAD: we've changed only one character from `<` to `>`, but this makes
/// // it possible for waiting to end before the barrier has advanced. Could cause
/// // mutable aliasing, and thus UB.
/// while barrier_seq > desired_seq {
/// barrier_seq = barrier.sequence();
/// }
/// // VERY BAD: we return a sequence unrelated to the barrier, possibly leaving
/// // the disruptor in an inconsistent, non-recoverable state if a handle uses
/// // the value. Could cause mutable aliasing, and thus UB.
/// Ok(10)
/// }
/// }
/// ```
pub unsafe
/// Pure busy-spin waiting.
///
/// # Performance
///
/// Offers the lowest possible wait latency at the cost of unrestrained processor use.
///
/// Suitable when CPU resource use is of no concern.
;
/// Busy-wait and signal that a spin loop is occurring.
///
/// See: [`spin_loop`](std::hint::spin_loop) docs for further details.
///
/// # Performance
///
/// The spin loop signal can optimise processor use with minimal cost to latency, but should offer
/// latencies similar to [`WaitBusy`].
///
/// Nonetheless, it is best used when CPU resource consumption is of little concern.
;
/// Busy-wait, but allow the current thread to yield to the OS.
///
/// See: [`yield_now`](std::thread::yield_now) docs for further details.
///
/// # Performance
///
/// Like [`WaitBusy`], processor use is unrestrained, but [`WaitYield`] is more likely to cede CPU
/// resources when those resources are contended by other threads.
;
/// Sleep the current thread on each iteration of the wait loop.
///
/// Equivalent to polling available sequences at a fixed interval.
///
/// Default duration is 50 microseconds.
///
/// The duration of the sleep is limited to `u64::MAX` nanoseconds.
///
/// # Performance
///
/// Trades latency for CPU resource use, depending on the length of the sleep.
/// Performs a phased back-off of strategies during the wait loop.
///
/// This strategy busy spins, then yields, and finally calls the fallback strategy.
///
/// Both durations for spinning and yielding are limited to `u64::MAX` nanoseconds.
///
/// # Performance
///
/// Highly dependent on the fallback strategy, but best used when low latency is not a priority
/// verses CPU resource use.
// SAFETY: wait only returns once barrier_seq >= desired_seq, with barrier_seq itself
unsafe
// SAFETY: Before yield_dur exceeded, try_wait only returns once barrier_seq >= desired_seq, with
// barrier_seq. When exceeded, calls fallback try_wait, which is expected to be validly implemented.
unsafe
/// Indicates that the waiting handle has timed out.
;
/// Wrapper which provides timeout capabilities to strategies implementing `Waiting`.
///
/// If a type, `T`, implements [`Waiting`], then `Timeout<T>` implements [`TryWaitStrategy`].
///
/// This struct is not required for implementing `TryWaitStrategy`, it is only a convenience
/// for automating implementations of timeouts.
///
/// The length of the timeout is limited to `u64::MAX` nanoseconds.
///
/// # Examples
/// ```
/// use ansa::*;
/// use ansa::wait::*;
/// use std::time::Duration;
///
/// let strategy = Timeout::new(Duration::from_millis(1), WaitBusy);
///
/// let _ = DisruptorBuilder::new(64, || 0)
/// .wait_strategy(strategy)
/// .add_handle(0, Handle::Consumer, Follows::LeadProducer)
/// .build()?;
/// # Ok::<(), BuildError>(())
/// ```
// SAFETY: try_wait only successfully returns with barrier_seq once barrier_seq >= desired_seq
unsafe
const