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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! A synchronous multi-producer, single-consumer channel.
//!
//! This provides an equivalent API to the [`mpsc`](crate::mpsc) module, but the
//! [`Receiver`] types in this module wait by blocking the current thread,
//! rather than asynchronously yielding.
use super::*;
use crate::{
    loom::{
        atomic::{self, Ordering},
        sync::Arc,
        thread::{self, Thread},
    },
    recycling::{self, Recycle},
    util::Backoff,
    wait::queue,
};
use core::{fmt, pin::Pin};
use errors::*;

/// Returns a new synchronous multi-producer, single consumer (MPSC)
/// channel with  the provided capacity.
///
/// This channel will use the [default recycling policy].
///
/// [recycling policy]: crate::recycling::DefaultRecycle
#[must_use]
pub fn channel<T: Default + Clone>(capacity: usize) -> (Sender<T>, Receiver<T>) {
    with_recycle(capacity, recycling::DefaultRecycle::new())
}

/// Returns a new synchronous multi-producer, single consumer channel with
/// the provided [recycling policy].
///
/// [recycling policy]: crate::recycling::Recycle
#[must_use]
pub fn with_recycle<T, R: Recycle<T>>(
    capacity: usize,
    recycle: R,
) -> (Sender<T, R>, Receiver<T, R>) {
    assert!(capacity > 0);
    let inner = Arc::new(Inner {
        core: ChannelCore::new(capacity),
        slots: Slot::make_boxed_array(capacity),
        recycle,
    });
    let tx = Sender {
        inner: inner.clone(),
    };
    let rx = Receiver { inner };
    (tx, rx)
}

/// Synchronously receives values from associated [`Sender`]s.
///
/// Instances of this struct are created by the [`channel`] and
/// [`with_recycle`] functions.
#[derive(Debug)]
pub struct Sender<T, R = recycling::DefaultRecycle> {
    inner: Arc<Inner<T, R>>,
}

/// Synchronously sends values to an associated [`Receiver`].
///
/// Instances of this struct are created by the [`channel`] and
/// [`with_recycle`] functions.
#[derive(Debug)]
pub struct Receiver<T, R = recycling::DefaultRecycle> {
    inner: Arc<Inner<T, R>>,
}

struct Inner<T, R> {
    core: super::ChannelCore<Thread>,
    slots: Box<[Slot<T>]>,
    recycle: R,
}

#[cfg(not(all(loom, test)))]
feature! {
    #![feature = "static"]

    use crate::loom::atomic::AtomicBool;

    /// A statically-allocated, blocking bounded MPSC channel.
    ///
    /// A statically-allocated channel allows using a MPSC channel without
    /// requiring _any_ heap allocations. The [asynchronous variant][async] may be
    /// used in `#![no_std]` environments without requiring `liballoc`. This is a
    /// synchronous version which requires the Rust standard library, because it
    /// blocks the current thread in order to wait for send capacity. However, in
    /// some cases, it may offer _very slightly_ better performance than the
    /// non-static blocking channel due to requiring fewer heap pointer
    /// dereferences.
    ///
    /// In order to use a statically-allocated channel, a `StaticChannel` must
    /// be constructed in a `static` initializer. This reserves storage for the
    /// channel's message queue at compile-time. Then, at runtime, the channel
    /// is [`split`] into a [`StaticSender`]/[`StaticReceiver`] pair in order to
    /// be used.
    ///
    /// # Examples
    ///
    /// ```
    /// use thingbuf::mpsc::blocking::StaticChannel;
    ///
    /// // Construct a statically-allocated channel of `usize`s with a capacity
    /// // of 16 messages.
    /// static MY_CHANNEL: StaticChannel<usize, 16> = StaticChannel::new();
    ///
    /// fn main() {
    ///     // Split the `StaticChannel` into a sender-receiver pair.
    ///     let (tx, rx) = MY_CHANNEL.split();
    ///
    ///     // Now, `tx` and `rx` can be used just like any other async MPSC
    ///     // channel...
    /// # drop(tx); drop(rx);
    /// }
    /// ```
    ///
    /// [async]: crate::mpsc::StaticChannel
    /// [`split`]: StaticChannel::split
    pub struct StaticChannel<T, const CAPACITY: usize, R = recycling::DefaultRecycle> {
        core: ChannelCore<Thread>,
        slots: [Slot<T>; CAPACITY],
        is_split: AtomicBool,
        recycle: R,
    }

    /// Synchronously sends values to an associated [`StaticReceiver`].
    ///
    /// Instances of this struct are created by the [`StaticChannel::split`] and
    /// [``StaticChannel::try_split`] functions.
    pub struct StaticSender<T: 'static, R: 'static = recycling::DefaultRecycle> {
        core: &'static ChannelCore<Thread>,
        slots: &'static [Slot<T>],
        recycle: &'static R,
    }

    /// Synchronously receives values from associated [`StaticSender`]s.
    ///
    /// Instances of this struct are created by the [`StaticChannel::split`] and
    /// [``StaticChannel::try_split`] functions.
    pub struct StaticReceiver<T: 'static, R: 'static = recycling::DefaultRecycle> {
        core: &'static ChannelCore<Thread>,
        slots: &'static [Slot<T>],
        recycle: &'static R,
    }

    // === impl StaticChannel ===

    impl<T, const CAPACITY: usize> StaticChannel<T, CAPACITY> {
        /// Constructs a new statically-allocated, blocking bounded MPSC channel.
        ///
        /// A statically-allocated channel allows using a MPSC channel without
        /// requiring _any_ heap allocations. The [asynchronous variant][async] may be
        /// used in `#![no_std]` environments without requiring `liballoc`. This is a
        /// synchronous version which requires the Rust standard library, because it
        /// blocks the current thread in order to wait for send capacity. However, in
        /// some cases, it may offer _very slightly_ better performance than the
        /// non-static blocking channel due to requiring fewer heap pointer
        /// dereferences.
        ///
        /// In order to use a statically-allocated channel, a `StaticChannel` must
        /// be constructed in a `static` initializer. This reserves storage for the
        /// channel's message queue at compile-time. Then, at runtime, the channel
        /// is [`split`] into a [`StaticSender`]/[`StaticReceiver`] pair in order to
        /// be used.
        ///
        /// # Examples
        ///
        /// ```
        /// use thingbuf::mpsc::StaticChannel;
        ///
        /// // Construct a statically-allocated channel of `usize`s with a capacity
        /// // of 16 messages.
        /// static MY_CHANNEL: StaticChannel<usize, 16> = StaticChannel::new();
        ///
        /// fn main() {
        ///     // Split the `StaticChannel` into a sender-receiver pair.
        ///     let (tx, rx) = MY_CHANNEL.split();
        ///
        ///     // Now, `tx` and `rx` can be used just like any other async MPSC
        ///     // channel...
        /// # drop(tx); drop(rx);
        /// }
        /// ```
        ///
        /// [async]: crate::mpsc::StaticChannel
        /// [`split`]: StaticChannel::split
        #[must_use]
        pub const fn new() -> Self {
            Self {
                core: ChannelCore::new(CAPACITY),
                slots: Slot::make_static_array::<CAPACITY>(),
                is_split: AtomicBool::new(false),
                recycle: recycling::DefaultRecycle::new(),
            }
        }
    }

    impl<T, R, const CAPACITY: usize> StaticChannel<T, CAPACITY, R> {
        /// Split a [`StaticChannel`] into a [`StaticSender`]/[`StaticReceiver`]
        /// pair.
        ///
        /// A static channel can only be split a single time. If
        /// [`StaticChannel::split`] or [`StaticChannel::try_split`] have been
        /// called previously, this method will panic. For a non-panicking version
        /// of this method, see [`StaticChannel::try_split`].
        ///
        /// # Panics
        ///
        /// If the channel has already been split.
        #[must_use]
        pub fn split(&'static self) -> (StaticSender<T, R>, StaticReceiver<T, R>) {
            self.try_split().expect("channel already split")
        }

        /// Try to split a [`StaticChannel`] into a [`StaticSender`]/[`StaticReceiver`]
        /// pair, returning `None` if it has already been split.
        ///
        /// A static channel can only be split a single time. If
        /// [`StaticChannel::split`] or [`StaticChannel::try_split`] have been
        /// called previously, this method returns `None`.
        #[must_use]
        pub fn try_split(&'static self) -> Option<(StaticSender<T, R>, StaticReceiver<T, R>)> {
            self.is_split
                .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
                .ok()?;
            let tx = StaticSender {
                core: &self.core,
                slots: &self.slots[..],
                recycle: &self.recycle,
            };
            let rx = StaticReceiver {
                core: &self.core,
                slots: &self.slots[..],
                recycle: &self.recycle,
            };
            Some((tx, rx))
        }
    }

    // === impl StaticSender ===

    impl<T, R> StaticSender<T, R>
    where
        R: Recycle<T>,
    {
        /// Reserves a slot in the channel to mutate in place, blocking until
        /// there is a free slot to write to.
        ///
        /// This is similar to the [`send`] method, but, rather than taking a
        /// message by value to write to the channel, this method reserves a
        /// writable slot in the channel, and returns a [`SendRef`] that allows
        /// mutating the slot in place. If the [`StaticReceiver`] end of the
        /// channel uses the [`StaticReceiver::recv_ref`] method for receiving
        /// from the channel, this allows allocations for channel messages to be
        /// reused in place.
        ///
        /// # Errors
        ///
        /// If the [`StaticReceiver`] end of the channel has been dropped, this
        /// returns a [`Closed`] error.
        ///
        /// # Examples
        ///
        /// Sending formatted strings by writing them directly to channel slots,
        /// in place:
        /// ```
        /// use thingbuf::mpsc::blocking::StaticChannel;
        /// use std::{fmt::Write, thread};
        ///
        /// static CHANNEL: StaticChannel<String, 8> = StaticChannel::new();
        ///
        /// let (tx, rx) = CHANNEL.split();
        ///
        /// // Spawn a thread that prints each message received from the channel:
        /// thread::spawn(move || {
        ///     for _ in 0..10 {
        ///         let msg = rx.recv_ref().unwrap();
        ///         println!("{}", msg);
        ///     }
        /// });
        ///
        /// // Until the channel closes, write formatted messages to the channel.
        /// let mut count = 1;
        /// while let Ok(mut value) = tx.send_ref() {
        ///     // Writing to the `SendRef` will reuse the *existing* string
        ///     // allocation in place.
        ///     write!(value, "hello from message {}", count)
        ///         .expect("writing to a `String` should never fail");
        ///     count += 1;
        /// }
        /// ```
        ///
        /// [`send`]: Self::send
        pub fn send_ref(&self) -> Result<SendRef<'_, T>, Closed> {
            send_ref(self.core, self.slots, self.recycle)
        }

        /// Sends a message by value, blocking until there is a free slot to
        /// write to.
        ///
        /// This method takes the message by value, and replaces any previous
        /// value in the slot. This means that the channel will *not* function
        /// as an object pool while sending messages with `send`. This method is
        /// most appropriate when messages don't own reusable heap allocations,
        /// or when the [`StaticReceiver`] end of the channel must receive messages
        /// by moving them out of the channel by value (using the
        /// [`StaticReceiver::recv`] method). When messages in the channel own
        /// reusable heap allocations (such as `String`s or `Vec`s), and the
        /// [`StaticReceiver`] doesn't need to receive them by value, consider using
        /// [`send_ref`] instead, to enable allocation reuse.
        ///
        /// # Errors
        ///
        /// If the [`StaticReceiver`] end of the channel has been dropped, this
        /// returns a [`Closed`] error containing the sent value.
        ///
        /// # Examples
        ///
        /// ```
        /// use thingbuf::mpsc::blocking::StaticChannel;
        /// use std::{fmt::Write, thread};
        ///
        /// static CHANNEL: StaticChannel<i32, 8> = StaticChannel::new();
        /// let (tx, rx) = CHANNEL.split();
        ///
        /// // Spawn a thread that prints each message received from the channel:
        /// thread::spawn(move || {
        ///     for _ in 0..10 {
        ///         let msg = rx.recv().unwrap();
        ///         println!("received message {}", msg);
        ///     }
        /// });
        ///
        /// // Until the channel closes, write the current iteration to the channel.
        /// let mut count = 1;
        /// while tx.send(count).is_ok() {
        ///     count += 1;
        /// }
        /// ```
        /// [`send_ref`]: Self::send_ref
        pub fn send(&self, val: T) -> Result<(), Closed<T>> {
            match self.send_ref() {
                Err(Closed(())) => Err(Closed(val)),
                Ok(mut slot) => {
                    *slot = val;
                    Ok(())
                }
            }
        }

        /// Attempts to reserve a slot in the channel to mutate in place,
        /// without blocking until capacity is available.
        ///
        /// This method differs from [`send_ref`] by returning immediately if the
        /// channel’s buffer is full or no [`StaticReceiver`] exists. Compared with
        /// [`send_ref`], this method has two failure cases instead of one (one for
        /// disconnection, one for a full buffer), and this method will never block.
        ///
        /// Like [`send_ref`], this method returns a [`SendRef`] that may be
        /// used to mutate a slot in the channel's buffer in place. Dropping the
        /// [`SendRef`] completes the send operation and makes the mutated value
        /// available to the [`StaticReceiver`].
        ///
        /// # Errors
        ///
        /// If the channel capacity has been reached (i.e., the channel has `n`
        /// buffered values where `n` is the `usize` const generic parameter of
        /// the [`StaticChannel`]), then [`TrySendError::Full`] is returned. In
        /// this case, a future call to `try_send` may succeed if additional
        /// capacity becomes available.
        ///
        /// If the receive half of the channel is closed (i.e., the [`StaticReceiver`]
        /// handle was dropped), the function returns [`TrySendError::Closed`].
        /// Once the channel has closed, subsequent calls to `try_send_ref` will
        /// never succeed.
        ///
        /// [`send_ref`]: Self::send_ref
        pub fn try_send_ref(&self) -> Result<SendRef<'_, T>, TrySendError> {
            self.core
                .try_send_ref(self.slots, self.recycle)
                .map(SendRef)
        }

        /// Attempts to send a message by value immediately, without blocking until
        /// capacity is available.
        ///
        /// This method differs from [`send`] by returning immediately if the
        /// channel’s buffer is full or no [`StaticReceiver`] exists. Compared
        /// with  [`send`], this method has two failure cases instead of one (one for
        /// disconnection, one for a full buffer), and this method will never block.
        ///
        /// # Errors
        ///
        /// If the channel capacity has been reached (i.e., the channel has `n`
        /// buffered values where `n` is the `usize` const generic parameter of
        /// the [`StaticChannel`]), then [`TrySendError::Full`] is returned. In
        /// this case, a future call to `try_send` may succeed if additional
        /// capacity becomes available.
        ///
        /// If the receive half of the channel is closed (i.e., the
        /// [`StaticReceiver`]  handle was dropped), the function returns
        /// [`TrySendError::Closed`]. Once the channel has closed, subsequent
        /// calls to `try_send` will  never succeed.
        ///
        /// In both cases, the error includes the value passed to `try_send`.
        ///
        /// [`send`]: Self::send
        pub fn try_send(&self, val: T) -> Result<(), TrySendError<T>> {
            self.core.try_send(self.slots, val, self.recycle)
        }
    }

    impl<T, R> Clone for StaticSender<T, R> {
        fn clone(&self) -> Self {
            test_dbg!(self.core.tx_count.fetch_add(1, Ordering::Relaxed));
            Self {
                core: self.core,
                slots: self.slots,
                recycle: self.recycle,
            }
        }
    }

    impl<T, R> Drop for StaticSender<T, R> {
        fn drop(&mut self) {
            if test_dbg!(self.core.tx_count.fetch_sub(1, Ordering::Release)) > 1 {
                return;
            }

            // if we are the last sender, synchronize
            test_dbg!(atomic::fence(Ordering::SeqCst));
            if self.core.core.close() {
                self.core.rx_wait.close_tx();
            }
        }
    }

    impl<T, R: fmt::Debug> fmt::Debug for StaticSender<T, R> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("StaticSender")
                .field("core", &self.core)
                .field("slots", &format_args!("&[..]"))
                .field("recycle", &self.recycle)
                .finish()
        }
    }

    // === impl StaticReceiver ===

    impl<T, R> StaticReceiver<T, R> {
        /// Receives the next message for this receiver, **by reference**.
        ///
        /// This method returns `None` if the channel has been closed and there are
        /// no remaining messages in the channel's buffer. This indicates that no
        /// further values can ever be received from this `StaticReceiver`. The channel is
        /// closed when all [`StaticSender`]s have been dropped.
        ///
        /// If there are no messages in the channel's buffer, but the channel has
        /// not yet been closed, this method will block until a message is sent or
        /// the channel is closed.
        ///
        /// This method returns a [`RecvRef`] that can be used to read from (or
        /// mutate) the received message by reference. When the [`RecvRef`] is
        /// dropped, the receive operation completes and the slot occupied by
        /// the received message becomes usable for a future [`send_ref`] operation.
        ///
        /// If all [`StaticSender`]s for this channel write to the channel's
        /// slots in place by using the [`send_ref`] or [`try_send_ref`]
        /// methods, this method allows messages that own heap allocations to be reused in
        /// place.
        ///
        /// # Examples
        ///
        /// ```
        /// use thingbuf::mpsc::blocking::StaticChannel;
        /// use std::{thread, fmt::Write};
        ///
        /// static CHANNEL: StaticChannel<String, 100> = StaticChannel::new();
        /// let (tx, rx) = CHANNEL.split();
        ///
        /// thread::spawn(move || {
        ///     let mut value = tx.send_ref().unwrap();
        ///     write!(value, "hello world!")
        ///         .expect("writing to a `String` should never fail");
        /// });
        ///
        /// assert_eq!(Some("hello world!"), rx.recv_ref().as_deref().map(String::as_str));
        /// assert_eq!(None, rx.recv().as_deref());
        /// ```
        ///
        /// Values are buffered:
        ///
        /// ```
        /// use thingbuf::mpsc::blocking::StaticChannel;
        /// use std::fmt::Write;
        ///
        /// static CHANNEL: StaticChannel<String, 100> = StaticChannel::new();
        /// let (tx, rx) = CHANNEL.split();
        ///
        /// write!(tx.send_ref().unwrap(), "hello").unwrap();
        /// write!(tx.send_ref().unwrap(), "world").unwrap();
        ///
        /// assert_eq!("hello", rx.recv_ref().unwrap().as_str());
        /// assert_eq!("world", rx.recv_ref().unwrap().as_str());
        /// ```
        ///
        /// [`send_ref`]: StaticSender::send_ref
        /// [`try_send_ref`]: StaticSender::try_send_ref
        pub fn recv_ref(&self) -> Option<RecvRef<'_, T>> {
            recv_ref(self.core, self.slots)
        }

        /// Receives the next message for this receiver, **by value**.
        ///
        /// This method returns `None` if the channel has been closed and there are
        /// no remaining messages in the channel's buffer. This indicates that no
        /// further values can ever be received from this `StaticReceiver`. The channel is
        /// closed when all [`StaticSender`]s have been dropped.
        ///
        /// If there are no messages in the channel's buffer, but the channel has
        /// not yet been closed, this method will block until a message is sent or
        /// the channel is closed.
        ///
        /// When a message is received, it is moved out of the channel by value,
        /// and replaced with a new slot according to the configured [recycling
        /// policy]. If all [`StaticSender`]s for this channel write to the channel's
        /// slots in place by using the [`send_ref`] or [`try_send_ref`] methods,
        /// consider using the [`recv_ref`] method instead, to enable the
        /// reuse of heap allocations.
        ///
        /// # Examples
        ///
        /// ```
        /// use thingbuf::mpsc::blocking::StaticChannel;
        /// use std::thread;
        ///
        /// static CHANNEL: StaticChannel<i32, 100> = StaticChannel::new();
        /// let (tx, rx) = CHANNEL.split();
        ///
        /// thread::spawn(move || {
        ///    tx.send(1).unwrap();
        /// });
        ///
        /// assert_eq!(Some(1), rx.recv());
        /// assert_eq!(None, rx.recv());
        /// ```
        ///
        /// Values are buffered:
        ///
        /// ```
        /// use thingbuf::mpsc::blocking::StaticChannel;
        ///
        /// static CHANNEL: StaticChannel<i32, 100> = StaticChannel::new();
        /// let (tx, rx) = CHANNEL.split();
        ///
        /// tx.send(1).unwrap();
        /// tx.send(2).unwrap();
        ///
        /// assert_eq!(Some(1), rx.recv());
        /// assert_eq!(Some(2), rx.recv());
        /// ```
        ///
        /// [`send_ref`]: StaticSender::send_ref
        /// [`try_send_ref`]: StaticSender::try_send_ref
        /// [recycling policy]: crate::recycling::Recycle
        /// [`recv_ref`]: Self::recv_ref
        pub fn recv(&self) -> Option<T>
        where
            R: Recycle<T>,
        {
            let mut val = self.recv_ref()?;
            Some(recycling::take(&mut *val, self.recycle))
        }

        /// Attempts to receive the next message for this receiver by reference
        /// without blocking.
        ///
        /// This method differs from [`recv_ref`] by returning immediately if the
        /// channel is empty or closed.
        ///
        /// # Errors
        ///
        /// This method returns an error when the channel is closed or there are
        /// no remaining messages in the channel's buffer.
        ///
        /// # Examples
        ///
        /// ```
        /// use thingbuf::mpsc::{blocking, errors::TryRecvError};
        ///
        /// let (tx, rx) = blocking::channel(100);
        /// assert!(matches!(rx.try_recv_ref(), Err(TryRecvError::Empty)));
        ///
        /// tx.send(1).unwrap();
        /// drop(tx);
        ///
        /// assert_eq!(*rx.try_recv_ref().unwrap(), 1);
        /// assert!(matches!(rx.try_recv_ref(), Err(TryRecvError::Closed)));
        /// ```
        ///
        /// [`recv_ref`]: Self::recv_ref
        pub fn try_recv_ref(&self) -> Result<RecvRef<'_, T>, TryRecvError>
        where
            R: Recycle<T>,
        {
            self.core.try_recv_ref(self.slots.as_ref()).map(RecvRef)
        }

        /// Attempts to receive the next message for this receiver by value
        /// without blocking.
        ///
        /// This method differs from [`recv`] by returning immediately if the
        /// channel is empty or closed.
        ///
        /// # Errors
        ///
        /// This method returns an error when the channel is closed or there are
        /// no remaining messages in the channel's buffer.
        ///
        /// # Examples
        ///
        /// ```
        /// use thingbuf::mpsc::{blocking, errors::TryRecvError};
        ///
        /// let (tx, rx) = blocking::channel(100);
        /// assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
        ///
        /// tx.send(1).unwrap();
        /// drop(tx);
        ///
        /// assert_eq!(rx.try_recv().unwrap(), 1);
        /// assert_eq!(rx.try_recv(), Err(TryRecvError::Closed));
        /// ```
        ///
        /// [`recv`]: Self::recv
        pub fn try_recv(&self) -> Result<T, TryRecvError>
        where
            R: Recycle<T>,
        {
            self.core.try_recv(self.slots.as_ref(), self.recycle)
        }

        /// Returns `true` if the channel has closed (all corresponding
        /// [`StaticSender`]s have been dropped).
        ///
        /// If this method returns `true`, no new messages will become available
        /// on this channel. Previously sent messages may still be available.
        pub fn is_closed(&self) -> bool {
            test_dbg!(self.core.tx_count.load(Ordering::SeqCst)) <= 1
        }
    }

    impl<'a, T, R> Iterator for &'a StaticReceiver<T, R> {
        type Item = RecvRef<'a, T>;

        fn next(&mut self) -> Option<Self::Item> {
            self.recv_ref()
        }
    }

    impl<T, R> Drop for StaticReceiver<T, R> {
        fn drop(&mut self) {
            self.core.close_rx();
        }
    }

    impl<T, R: fmt::Debug> fmt::Debug for StaticReceiver<T, R> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("StaticReceiver")
                .field("core", &self.core)
                .field("slots", &format_args!("&[..]"))
                .field("recycle", &self.recycle)
                .finish()
        }
    }
}

impl_send_ref! {
    /// A reference to a message being sent to a blocking channel.
    ///
    /// A `SendRef` represents the exclusive permission to mutate a given
    /// element in a channel. A `SendRef<T>` [implements `DerefMut<T>`] to allow
    /// writing to that element. This is analogous to the [`Ref`] type, except
    /// that it completes a `send_ref` or `try_send_ref` operation when it is
    /// dropped.
    ///
    /// This type is returned by the [`Sender::send_ref`] and
    /// [`Sender::try_send_ref`] (or [`StaticSender::send_ref`] and
    /// [`StaticSender::try_send_ref`]) methods.
    ///
    /// [implements `DerefMut<T>`]: #impl-DerefMut
    /// [`Ref`]: crate::Ref
    pub struct SendRef<Thread>;
}

impl_recv_ref! {
    /// A reference to a message being received from a blocking channel.
    ///
    /// A `RecvRef` represents the exclusive permission to mutate a given
    /// element in a channel. A `RecvRef<T>` [implements `DerefMut<T>`] to allow
    /// writing to that element. This is analogous to the [`Ref`] type, except
    /// that it completes a `recv_ref` operation when it is dropped.
    ///
    /// This type is returned by the [`Receiver::recv_ref`] and
    /// [`StaticReceiver::recv_ref`] methods.
    ///
    /// [implements `DerefMut<T>`]: #impl-DerefMut
    /// [`Ref`]: crate::Ref
    pub struct RecvRef<Thread>;
}

// === impl Sender ===

impl<T, R> Sender<T, R>
where
    R: Recycle<T>,
{
    /// Reserves a slot in the channel to mutate in place, blocking until
    /// there is a free slot to write to.
    ///
    /// This is similar to the [`send`] method, but, rather than taking a
    /// message by value to write to the channel, this method reserves a
    /// writable slot in the channel, and returns a [`SendRef`] that allows
    /// mutating the slot in place. If the [`Receiver`] end of the channel
    /// uses the [`Receiver::recv_ref`] method for receiving from the channel,
    /// this allows allocations for channel messages to be reused in place.
    ///
    /// # Errors
    ///
    /// If the [`Receiver`] end of the channel has been dropped, this
    /// returns a [`Closed`] error.
    ///
    /// # Examples
    ///
    /// Sending formatted strings by writing them directly to channel slots,
    /// in place:
    /// ```
    /// use thingbuf::mpsc::blocking;
    /// use std::{fmt::Write, thread};
    ///
    /// let (tx, rx) = blocking::channel::<String>(8);
    ///
    /// // Spawn a thread that prints each message received from the channel:
    /// thread::spawn(move || {
    ///     for _ in 0..10 {
    ///         let msg = rx.recv_ref().unwrap();
    ///         println!("{}", msg);
    ///     }
    /// });
    ///
    /// // Until the channel closes, write formatted messages to the channel.
    /// let mut count = 1;
    /// while let Ok(mut value) = tx.send_ref() {
    ///     // Writing to the `SendRef` will reuse the *existing* string
    ///     // allocation in place.
    ///     write!(value, "hello from message {}", count)
    ///         .expect("writing to a `String` should never fail");
    ///     count += 1;
    /// }
    /// ```
    ///
    /// [`send`]: Self::send
    pub fn send_ref(&self) -> Result<SendRef<'_, T>, Closed> {
        send_ref(
            &self.inner.core,
            self.inner.slots.as_ref(),
            &self.inner.recycle,
        )
    }

    /// Sends a message by value, blocking until there is a free slot to
    /// write to.
    ///
    /// This method takes the message by value, and replaces any previous
    /// value in the slot. This means that the channel will *not* function
    /// as an object pool while sending messages with `send`. This method is
    /// most appropriate when messages don't own reusable heap allocations,
    /// or when the [`Receiver`] end of the channel must receive messages by
    /// moving them out of the channel by value (using the
    /// [`Receiver::recv`] method). When messages in the channel own
    /// reusable heap allocations (such as `String`s or `Vec`s), and the
    /// [`Receiver`] doesn't need to receive them by value, consider using
    /// [`send_ref`] instead, to enable allocation reuse.
    ///
    /// # Errors
    ///
    /// If the [`Receiver`] end of the channel has been dropped, this
    /// returns a [`Closed`] error containing the sent value.
    ///
    /// # Examples
    ///
    /// ```
    /// use thingbuf::mpsc::blocking;
    /// use std::thread;
    ///
    /// let (tx, rx) = blocking::channel(8);
    ///
    /// // Spawn a thread that prints each message received from the channel:
    /// thread::spawn(move || {
    ///     for _ in 0..10 {
    ///         let msg = rx.recv().unwrap();
    ///         println!("received message {}", msg);
    ///     }
    /// });
    ///
    /// // Until the channel closes, write the current iteration to the channel.
    /// let mut count = 1;
    /// while tx.send(count).is_ok() {
    ///     count += 1;
    /// }
    /// ```
    /// [`send_ref`]: Self::send_ref
    pub fn send(&self, val: T) -> Result<(), Closed<T>> {
        match self.send_ref() {
            Err(Closed(())) => Err(Closed(val)),
            Ok(mut slot) => {
                *slot = val;
                Ok(())
            }
        }
    }

    /// Attempts to reserve a slot in the channel to mutate in place,
    /// without blocking until capacity is available.
    ///
    /// This method differs from [`send_ref`] by returning immediately if the
    /// channel’s buffer is full or no [`Receiver`] exists. Compared with
    /// [`send_ref`], this method has two failure cases instead of one (one for
    /// disconnection, one for a full buffer), and this method will never block.
    ///
    /// Like [`send_ref`], this method returns a [`SendRef`] that may be
    /// used to mutate a slot in the channel's buffer in place. Dropping the
    /// [`SendRef`] completes the send operation and makes the mutated value
    /// available to the [`Receiver`].
    ///
    /// # Errors
    ///
    /// If the channel capacity has been reached (i.e., the channel has `n`
    /// buffered values where `n` is the argument passed to
    /// [`channel`]/[`with_recycle`]), then [`TrySendError::Full`] is
    /// returned. In this case, a future call to `try_send` may succeed if
    /// additional capacity becomes available.
    ///
    /// If the receive half of the channel is closed (i.e., the [`Receiver`]
    /// handle was dropped), the function returns [`TrySendError::Closed`].
    /// Once the channel has closed, subsequent calls to `try_send_ref` will
    /// never succeed.
    ///
    /// [`send_ref`]: Self::send_ref
    pub fn try_send_ref(&self) -> Result<SendRef<'_, T>, TrySendError> {
        self.inner
            .core
            .try_send_ref(self.inner.slots.as_ref(), &self.inner.recycle)
            .map(SendRef)
    }

    /// Attempts to send a message by value immediately, without blocking until
    /// capacity is available.
    ///
    /// This method differs from [`send`] by returning immediately if the
    /// channel’s buffer is full or no [`Receiver`] exists. Compared with
    /// [`send`], this method has two failure cases instead of one (one for
    /// disconnection, one for a full buffer), and this method will never block.
    ///
    /// # Errors
    ///
    /// If the channel capacity has been reached (i.e., the channel has `n`
    /// buffered values where `n` is the argument passed to
    /// [`channel`]/[`with_recycle`]), then [`TrySendError::Full`] is
    /// returned. In this case, a future call to `try_send` may succeed if
    /// additional capacity becomes available.
    ///
    /// If the receive half of the channel is closed (i.e., the [`Receiver`]
    /// handle was dropped), the function returns [`TrySendError::Closed`].
    /// Once the channel has closed, subsequent calls to `try_send` will
    /// never succeed.
    ///
    /// In both cases, the error includes the value passed to `try_send`.
    ///
    /// [`send`]: Self::send
    pub fn try_send(&self, val: T) -> Result<(), TrySendError<T>> {
        self.inner
            .core
            .try_send(self.inner.slots.as_ref(), val, &self.inner.recycle)
    }
}

impl<T, R> Clone for Sender<T, R> {
    fn clone(&self) -> Self {
        test_dbg!(self.inner.core.tx_count.fetch_add(1, Ordering::Relaxed));
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T, R> Drop for Sender<T, R> {
    fn drop(&mut self) {
        if test_dbg!(self.inner.core.tx_count.fetch_sub(1, Ordering::Release)) > 1 {
            return;
        }

        // if we are the last sender, synchronize
        test_dbg!(atomic::fence(Ordering::SeqCst));
        if self.inner.core.core.close() {
            self.inner.core.rx_wait.close_tx();
        }
    }
}

// === impl Receiver ===

impl<T, R> Receiver<T, R> {
    /// Receives the next message for this receiver, **by reference**.
    ///
    /// This method returns `None` if the channel has been closed and there are
    /// no remaining messages in the channel's buffer. This indicates that no
    /// further values can ever be received from this `Receiver`. The channel is
    /// closed when all [`Sender`]s have been dropped.
    ///
    /// If there are no messages in the channel's buffer, but the channel has
    /// not yet been closed, this method will block until a message is sent or
    /// the channel is closed.
    ///
    /// This method returns a [`RecvRef`] that can be used to read from (or
    /// mutate) the received message by reference. When the [`RecvRef`] is
    /// dropped, the receive operation completes and the slot occupied by
    /// the received message becomes usable for a future [`send_ref`] operation.
    ///
    /// If all [`Sender`]s for this channel write to the channel's slots in
    /// place by using the [`send_ref`] or [`try_send_ref`] methods, this
    /// method allows messages that own heap allocations to be reused in
    /// place.
    ///
    /// # Examples
    ///
    /// ```
    /// use thingbuf::mpsc::blocking;
    /// use std::{thread, fmt::Write};
    ///
    /// let (tx, rx) = blocking::channel::<String>(100);
    ///
    /// thread::spawn(move || {
    ///     let mut value = tx.send_ref().unwrap();
    ///     write!(value, "hello world!")
    ///         .expect("writing to a `String` should never fail");
    /// });
    ///
    /// assert_eq!(Some("hello world!"), rx.recv_ref().as_deref().map(String::as_str));
    /// assert_eq!(None, rx.recv().as_deref());
    /// ```
    ///
    /// Values are buffered:
    ///
    /// ```
    /// use thingbuf::mpsc::blocking;
    /// use std::fmt::Write;
    ///
    /// let (tx, rx) = blocking::channel::<String>(100);
    ///
    /// write!(tx.send_ref().unwrap(), "hello").unwrap();
    /// write!(tx.send_ref().unwrap(), "world").unwrap();
    ///
    /// assert_eq!("hello", rx.recv_ref().unwrap().as_str());
    /// assert_eq!("world", rx.recv_ref().unwrap().as_str());
    /// ```
    ///
    /// [`send_ref`]: Sender::send_ref
    /// [`try_send_ref`]: Sender::try_send_ref
    pub fn recv_ref(&self) -> Option<RecvRef<'_, T>> {
        recv_ref(&self.inner.core, self.inner.slots.as_ref())
    }

    /// Receives the next message for this receiver, **by value**.
    ///
    /// This method returns `None` if the channel has been closed and there are
    /// no remaining messages in the channel's buffer. This indicates that no
    /// further values can ever be received from this `Receiver`. The channel is
    /// closed when all [`Sender`]s have been dropped.
    ///
    /// If there are no messages in the channel's buffer, but the channel has
    /// not yet been closed, this method will block until a message is sent or
    /// the channel is closed.
    ///
    /// When a message is received, it is moved out of the channel by value,
    /// and replaced with a new slot according to the configured [recycling
    /// policy]. If all [`Sender`]s for this channel write to the channel's
    /// slots in place by using the [`send_ref`] or [`try_send_ref`] methods,
    /// consider using the [`recv_ref`] method instead, to enable the
    /// reuse of heap allocations.
    ///
    /// # Examples
    ///
    /// ```
    /// use thingbuf::mpsc::blocking;
    /// use std::{thread, fmt::Write};
    ///
    /// let (tx, rx) = blocking::channel(100);
    ///
    /// thread::spawn(move || {
    ///    tx.send(1).unwrap();
    /// });
    ///
    /// assert_eq!(Some(1), rx.recv());
    /// assert_eq!(None, rx.recv());
    /// ```
    ///
    /// Values are buffered:
    ///
    /// ```
    /// use thingbuf::mpsc::blocking;
    ///
    /// let (tx, rx) = blocking::channel(100);
    ///
    /// tx.send(1).unwrap();
    /// tx.send(2).unwrap();
    ///
    /// assert_eq!(Some(1), rx.recv());
    /// assert_eq!(Some(2), rx.recv());
    /// ```
    ///
    /// [`send_ref`]: Sender::send_ref
    /// [`try_send_ref`]: Sender::try_send_ref
    /// [recycling policy]: crate::recycling::Recycle
    /// [`recv_ref`]: Self::recv_ref
    pub fn recv(&self) -> Option<T>
    where
        R: Recycle<T>,
    {
        let mut val = self.recv_ref()?;
        Some(recycling::take(&mut *val, &self.inner.recycle))
    }

    /// Attempts to receive the next message for this receiver by reference
    /// without blocking.
    ///
    /// This method differs from [`recv_ref`] by returning immediately if the
    /// channel is empty or closed.
    ///
    /// # Errors
    ///
    /// This method returns an error when the channel is closed or there are
    /// no remaining messages in the channel's buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use thingbuf::mpsc::{blocking, errors::TryRecvError};
    ///
    /// let (tx, rx) = blocking::channel(100);
    /// assert!(matches!(rx.try_recv_ref(), Err(TryRecvError::Empty)));
    ///
    /// tx.send(1).unwrap();
    /// drop(tx);
    ///
    /// assert_eq!(*rx.try_recv_ref().unwrap(), 1);
    /// assert!(matches!(rx.try_recv_ref(), Err(TryRecvError::Closed)));
    /// ```
    ///
    /// [`recv_ref`]: Self::recv_ref
    pub fn try_recv_ref(&self) -> Result<RecvRef<'_, T>, TryRecvError> {
        self.inner
            .core
            .try_recv_ref(self.inner.slots.as_ref())
            .map(RecvRef)
    }

    /// Attempts to receive the next message for this receiver by value
    /// without blocking.
    ///
    /// This method differs from [`recv`] by returning immediately if the
    /// channel is empty or closed.
    ///
    /// # Errors
    ///
    /// This method returns an error when the channel is closed or there are
    /// no remaining messages in the channel's buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use thingbuf::mpsc::{blocking, errors::TryRecvError};
    ///
    /// let (tx, rx) = blocking::channel(100);
    /// assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
    ///
    /// tx.send(1).unwrap();
    /// drop(tx);
    ///
    /// assert_eq!(rx.try_recv().unwrap(), 1);
    /// assert_eq!(rx.try_recv(), Err(TryRecvError::Closed));
    /// ```
    ///
    /// [`recv`]: Self::recv
    pub fn try_recv(&self) -> Result<T, TryRecvError>
    where
        R: Recycle<T>,
    {
        self.inner
            .core
            .try_recv(self.inner.slots.as_ref(), &self.inner.recycle)
    }

    /// Returns `true` if the channel has closed (all corresponding
    /// [`Sender`]s have been dropped).
    ///
    /// If this method returns `true`, no new messages will become available
    /// on this channel. Previously sent messages may still be available.
    pub fn is_closed(&self) -> bool {
        test_dbg!(self.inner.core.tx_count.load(Ordering::SeqCst)) <= 1
    }
}

impl<'a, T, R> Iterator for &'a Receiver<T, R> {
    type Item = RecvRef<'a, T>;

    fn next(&mut self) -> Option<Self::Item> {
        self.recv_ref()
    }
}

impl<T, R> Drop for Receiver<T, R> {
    fn drop(&mut self) {
        self.inner.core.close_rx();
    }
}

// === impl Inner ===

impl<T, R: fmt::Debug> fmt::Debug for Inner<T, R> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Inner")
            .field("core", &self.core)
            .field("slots", &format_args!("Box<[..]>"))
            .field("recycle", &self.recycle)
            .finish()
    }
}

impl<T, R> Drop for Inner<T, R> {
    fn drop(&mut self) {
        self.core.core.drop_slots(&mut self.slots[..])
    }
}

#[inline]
fn recv_ref<'a, T>(core: &'a ChannelCore<Thread>, slots: &'a [Slot<T>]) -> Option<RecvRef<'a, T>> {
    loop {
        match core.poll_recv_ref(slots, thread::current) {
            Poll::Ready(r) => {
                return r.map(|slot| {
                    RecvRef(RecvRefInner {
                        _notify: super::NotifyTx(&core.tx_wait),
                        slot,
                    })
                })
            }
            Poll::Pending => {
                test_println!("parking ({:?})", thread::current());
                thread::park();
            }
        }
    }
}

#[inline]
fn send_ref<'a, T, R: Recycle<T>>(
    core: &'a ChannelCore<Thread>,
    slots: &'a [Slot<T>],
    recycle: &'a R,
) -> Result<SendRef<'a, T>, Closed<()>> {
    // fast path: avoid getting the thread and constructing the node if the
    // slot is immediately ready.
    match core.try_send_ref(slots, recycle) {
        Ok(slot) => return Ok(SendRef(slot)),
        Err(TrySendError::Closed(_)) => return Err(Closed(())),
        _ => {}
    }

    let mut waiter = queue::Waiter::new();
    let mut unqueued = true;
    let thread = thread::current();
    let mut boff = Backoff::new();
    loop {
        let node = unsafe {
            // Safety: in this case, it's totally safe to pin the waiter, as
            // it is owned uniquely by this function, and it cannot possibly
            // be moved while this thread is parked.
            Pin::new_unchecked(&mut waiter)
        };

        let wait = if unqueued {
            test_dbg!(core.tx_wait.start_wait(node, &thread))
        } else {
            test_dbg!(core.tx_wait.continue_wait(node, &thread))
        };

        match wait {
            WaitResult::Closed => return Err(Closed(())),
            WaitResult::Notified => {
                boff.spin_yield();
                match core.try_send_ref(slots.as_ref(), recycle) {
                    Ok(slot) => return Ok(SendRef(slot)),
                    Err(TrySendError::Closed(_)) => return Err(Closed(())),
                    _ => {}
                }
            }
            WaitResult::Wait => {
                unqueued = false;
                thread::park();
            }
        }
    }
}