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
//! Ffi-safe wrapper types around the
//! [crossbeam-channel](https://crates.io/crates/crossbeam-channel/)
//! channel types.
#![allow(clippy::missing_const_for_fn)]

use std::{
    fmt::{self, Debug},
    marker::PhantomData,
    time::Duration,
};

use crossbeam_channel::{
    Receiver, RecvError, RecvTimeoutError, SendError, SendTimeoutError, Sender, TryRecvError,
    TrySendError,
};

use core_extensions::SelfOps;

use crate::{
    marker_type::UnsafeIgnoredType,
    pointer_trait::AsPtr,
    prefix_type::WithMetadata,
    sabi_types::RRef,
    std_types::{RBox, RDuration, RErr, ROk, ROption, RResult},
    traits::{ErasedType, IntoReprRust},
};

mod errors;
mod extern_fns;
mod iteration;

#[cfg(all(test, not(feature = "test_miri_track_raw")))]
mod tests;

use self::errors::{
    RRecvError, RRecvTimeoutError, RSendError, RSendTimeoutError, RTryRecvError, RTrySendError,
};

pub use self::iteration::{RIntoIter, RIter};

///////////////////////////////////////////////////////////////////////////////

/// Creates a receiver that can never receive any value.
///
/// # Example
///
#[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
#[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
/// use abi_stable::external_types::crossbeam_channel as mpmc;
///
/// let rx = mpmc::never::<()>();
///
/// assert_eq!(rx.try_recv().ok(), None);
///
/// ```
pub fn never<T>() -> RReceiver<T> {
    crossbeam_channel::never::<T>().into()
}

/// Creates a channel which can hold up to `capacity` elements in its internal queue.
///
/// If `capacity==0`,the value must be sent to a receiver in the middle of a `recv` call.
///
/// # Panics
///
/// Panics if `capacity >= usize::max_value() / 4`.
///
/// # Example
///
#[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
#[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
/// use abi_stable::external_types::crossbeam_channel as mpmc;
///
/// let (tx, rx) = mpmc::bounded::<u32>(3);
///
/// std::thread::spawn(move || {
///     tx.send(10).unwrap();
///     tx.send(11).unwrap();
///     tx.send(12).unwrap();
/// });
///
/// assert_eq!(rx.recv().unwrap(), 10);
/// assert_eq!(rx.recv().unwrap(), 11);
/// assert_eq!(rx.recv().unwrap(), 12);
/// assert!(rx.try_recv().is_err());
///
/// ```
///
pub fn bounded<T>(capacity: usize) -> (RSender<T>, RReceiver<T>) {
    let (tx, rx) = crossbeam_channel::bounded::<T>(capacity);
    (tx.into(), rx.into())
}

/// Creates a channel which can hold an unbounded amount elements in its internal queue.
///
/// # Example
///
#[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
#[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
/// use abi_stable::external_types::crossbeam_channel as mpmc;
///
/// let (tx, rx) = mpmc::unbounded::<&'static str>();
///
/// let join_guard = std::thread::spawn(move || {
///     assert_eq!(rx.recv().unwrap(), "foo");
///     assert_eq!(rx.recv().unwrap(), "bar");
///     assert_eq!(rx.recv().unwrap(), "baz");
///     assert!(rx.try_recv().is_err());
/// });
///
/// tx.send("foo").unwrap();
/// tx.send("bar").unwrap();
/// tx.send("baz").unwrap();
///
/// join_guard.join().unwrap();
///
/// ```
///
///
pub fn unbounded<T>() -> (RSender<T>, RReceiver<T>) {
    let (tx, rx) = crossbeam_channel::unbounded::<T>();
    (tx.into(), rx.into())
}

///////////////////////////////////////////////////////////////////////////////

/// The sender end of a channel,
/// which can be either bounded or unbounded.
///
/// # Example
///
#[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
#[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
/// use abi_stable::external_types::crossbeam_channel as mpmc;
///
/// let (tx, rx) = mpmc::bounded::<&'static str>(1024);
///
/// std::thread::spawn(move || {
///     for _ in 0..4 {
///         tx.send("Are we there yet.").unwrap();
///     }
/// });
///
/// assert_eq!(rx.recv().unwrap(), "Are we there yet.");
/// assert_eq!(rx.recv().unwrap(), "Are we there yet.");
/// assert_eq!(rx.recv().unwrap(), "Are we there yet.");
/// assert_eq!(rx.recv().unwrap(), "Are we there yet.");
/// assert!(rx.recv().is_err());
///
///
/// ```
///
///
#[repr(C)]
#[derive(StableAbi)]
pub struct RSender<T> {
    channel: RBox<ErasedSender<T>>,
    vtable: VTable_Ref<T>,
}

impl<T> RSender<T> {
    fn vtable(&self) -> VTable_Ref<T> {
        self.vtable
    }

    /// Blocks until `value` is either sent,or the the other end is disconnected.
    ///
    /// If the channel queue is full,this will block to send `value`.
    ///
    /// If the channel is disconnected,this will return an error with `value`.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<u32>(3);
    ///
    /// tx.send(1057).unwrap();
    ///
    /// drop(rx);
    /// assert!(tx.send(0).is_err());
    ///
    /// ```
    ///
    pub fn send(&self, value: T) -> Result<(), SendError<T>> {
        let vtable = self.vtable();

        vtable.send()(self.channel.as_rref(), value).piped(result_from)
    }

    /// Immediately sends `value`,or returns with an error.
    ///
    /// An error will be returned in these 2 conditions:
    ///
    /// - the channel is full.
    ///
    /// - the channel has been disconnected.
    ///
    /// If the channel has a capacity of 0,it will only send `value` if
    /// the other end is calling `recv`.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<bool>(1);
    ///
    /// tx.try_send(true).unwrap();
    /// assert!(tx.try_send(true).unwrap_err().is_full());
    ///
    /// drop(rx);
    /// assert!(tx.try_send(false).unwrap_err().is_disconnected());
    ///
    /// ```
    ///
    ///
    pub fn try_send(&self, value: T) -> Result<(), TrySendError<T>> {
        let vtable = self.vtable();

        vtable.try_send()(self.channel.as_rref(), value).piped(result_from)
    }

    /// Blocks until a timeout to send `value`.
    ///
    /// An error will be returned in these 2 conditions:
    ///
    /// - the value could not be sent before the timeout.
    ///
    /// - the channel has been disconnected.
    ///
    /// If the channel has a capacity of 0,it will only send `value` if
    /// the other end calls `recv` before the timeout.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// use std::time::Duration;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(1);
    ///
    /// let timeout = Duration::from_millis(1);
    ///
    /// tx.send_timeout((), timeout).unwrap();
    /// assert!(tx.send_timeout((), timeout).unwrap_err().is_timeout());
    ///
    /// drop(rx);
    /// assert!(tx.send_timeout((), timeout).unwrap_err().is_disconnected());
    ///
    /// ```
    ///
    pub fn send_timeout(&self, value: T, timeout: Duration) -> Result<(), SendTimeoutError<T>> {
        let vtable = self.vtable();

        vtable.send_timeout()(self.channel.as_rref(), value, timeout.into()).piped(result_from)
    }

    /// Returns true if there are no values in the channel queue.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(1);
    ///
    /// assert!(tx.is_empty());
    ///
    /// tx.send(()).unwrap();
    /// assert!(!tx.is_empty());
    ///
    /// rx.recv().unwrap();
    /// assert!(tx.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        let vtable = self.vtable();

        vtable.sender_is_empty()(self.channel.as_rref())
    }

    /// Returns true if the channel queue is full.
    ///
    /// This always returns true for channels constructed with `bounded(0)`.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(2);
    ///
    /// assert!(!tx.is_full());
    ///
    /// tx.send(()).unwrap();
    /// assert!(!tx.is_full());
    ///
    /// tx.send(()).unwrap();
    /// assert!(tx.is_full());
    ///
    /// rx.recv().unwrap();
    /// assert!(!tx.is_full());
    /// ```
    pub fn is_full(&self) -> bool {
        let vtable = self.vtable();

        vtable.sender_is_full()(self.channel.as_rref())
    }

    /// Returns the amount of values in the channel queue.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(2);
    ///
    /// assert_eq!(tx.len(), 0);
    ///
    /// tx.send(()).unwrap();
    /// assert_eq!(tx.len(), 1);
    ///
    /// tx.send(()).unwrap();
    /// assert_eq!(tx.len(), 2);
    ///
    /// rx.recv().unwrap();
    /// assert_eq!(tx.len(), 1);
    ///
    /// ```
    pub fn len(&self) -> usize {
        let vtable = self.vtable();

        vtable.sender_len()(self.channel.as_rref())
    }

    /// Returns the amount of values the channel queue can hold.
    ///
    /// This returns None if the channel is unbounded.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// {
    ///     let (tx, rx) = mpmc::bounded::<()>(2);
    ///     assert_eq!(tx.capacity(), Some(2));
    /// }
    /// {
    ///     let (tx, rx) = mpmc::unbounded::<()>();
    ///     assert_eq!(tx.capacity(), None);
    /// }
    ///
    /// ```
    pub fn capacity(&self) -> Option<usize> {
        let vtable = self.vtable();

        vtable.sender_capacity()(self.channel.as_rref()).into_rust()
    }
}

impl<T> Clone for RSender<T> {
    /// Clones this channel end,getting another handle into the channel.
    ///
    /// Note that this allocates an RBox<_>.
    fn clone(&self) -> Self {
        let vtable = self.vtable();

        Self {
            channel: vtable.clone_sender()(self.channel.as_rref()),
            vtable: self.vtable,
        }
    }
}

impl<T> Debug for RSender<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt("RSender{..}", f)
    }
}

unsafe impl<T: Send> Sync for RSender<T> {}

unsafe impl<T: Send> Send for RSender<T> {}

impl_from_rust_repr! {
    impl[T] From<Sender<T>> for RSender<T> {
        fn(this){
            Self{
                channel:ErasedSender::from_unerased_value(this),
                vtable: MakeVTable::<T>::VTABLE,
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////////

/// The receiver end of a channel,
/// which can be either bounded or unbounded.
///
/// # Examples
///
#[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
#[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
/// use abi_stable::external_types::crossbeam_channel as mpmc;
///
/// let (tx, rx) = mpmc::unbounded::<&'static str>();
///
/// let join_guard = std::thread::spawn(move || {
///     assert_eq!(rx.recv().unwrap(), "PING");
///     assert_eq!(rx.recv().unwrap(), "PING");
///     assert_eq!(rx.recv().unwrap(), "PING");
///     assert_eq!(rx.recv().unwrap(), "PING");
///     assert!(rx.try_recv().unwrap_err().is_empty());
/// });
///
/// for _ in 0..4 {
///     tx.send("PING").unwrap();
/// }
///
/// join_guard.join().unwrap();
///
/// assert!(tx.send("").is_err());
///
/// ```
///
#[repr(C)]
#[derive(StableAbi)]
pub struct RReceiver<T> {
    channel: RBox<ErasedReceiver<T>>,
    vtable: VTable_Ref<T>,
}

impl<T> RReceiver<T> {
    fn vtable(&self) -> VTable_Ref<T> {
        self.vtable
    }

    /// Blocks until a value is either received,or the the other end is disconnected.
    ///
    /// If the channel queue is empty,this will block to receive a value.
    ///
    /// This will return an error if the channel is disconnected.
    ///
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<&'static str>(3);
    ///
    /// tx.send("J__e H____y").unwrap();
    /// assert_eq!(rx.recv().unwrap(), "J__e H____y");
    ///
    /// drop(tx);
    /// assert!(rx.recv().is_err());
    ///
    /// ```
    ///
    pub fn recv(&self) -> Result<T, RecvError> {
        let vtable = self.vtable();

        vtable.recv()(self.channel.as_rref()).piped(result_from)
    }

    /// Immediately receives a value,or returns with an error.
    ///
    /// An error will be returned in these 2 conditions:
    ///
    /// - the channel is empty.
    ///
    /// - the channel has been disconnected.
    ///
    /// If the channel has a capacity of 0,it will only receive a value if
    /// the other end is calling `send`.
    ///
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<&'static str>(3);
    ///
    /// assert!(rx.try_recv().is_err());
    ///
    /// tx.send("D__e S_____r").unwrap();
    /// assert_eq!(rx.try_recv().unwrap(), "D__e S_____r");
    ///
    /// drop(tx);
    /// assert!(rx.try_recv().is_err());
    ///
    /// ```
    pub fn try_recv(&self) -> Result<T, TryRecvError> {
        let vtable = self.vtable();

        vtable.try_recv()(self.channel.as_rref()).piped(result_from)
    }

    /// Blocks until a timeout to receive a value.
    ///
    /// An error will be returned in these 2 conditions:
    ///
    /// - A value could not be received before the timeout.
    ///
    /// - the channel has been disconnected.
    ///
    /// If the channel has a capacity of 0,it will only receive a value if
    /// the other end calls `send` before the timeout.
    ///
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// use std::time::Duration;
    ///
    /// let (tx, rx) = mpmc::bounded::<&'static str>(3);
    ///
    /// let timeout = Duration::from_millis(1);
    ///
    /// assert!(rx.recv_timeout(timeout).unwrap_err().is_timeout());
    ///
    /// tx.send("D__e S_____r").unwrap();
    /// assert_eq!(rx.recv_timeout(timeout).unwrap(), "D__e S_____r");
    ///
    /// drop(tx);
    /// assert!(rx.recv_timeout(timeout).unwrap_err().is_disconnected());
    ///
    /// ```
    ///
    pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
        let vtable = self.vtable();

        vtable.recv_timeout()(self.channel.as_rref(), timeout.into()).piped(result_from)
    }

    /// Returns true if there are no values in the channel queue.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(1);
    ///
    /// assert!(rx.is_empty());
    ///
    /// tx.send(()).unwrap();
    /// assert!(!rx.is_empty());
    ///
    /// rx.recv().unwrap();
    /// assert!(rx.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        let vtable = self.vtable();

        vtable.receiver_is_empty()(self.channel.as_rref())
    }

    /// Returns true if the channel queue is full.
    ///
    /// This always returns true for channels constructed with `bounded(0)`.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(2);
    ///
    /// assert!(!rx.is_full());
    ///
    /// tx.send(()).unwrap();
    /// assert!(!rx.is_full());
    ///
    /// tx.send(()).unwrap();
    /// assert!(rx.is_full());
    ///
    /// rx.recv().unwrap();
    /// assert!(!rx.is_full());
    /// ```
    pub fn is_full(&self) -> bool {
        let vtable = self.vtable();

        vtable.receiver_is_full()(self.channel.as_rref())
    }

    /// Returns the amount of values in the channel queue.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// let (tx, rx) = mpmc::bounded::<()>(2);
    ///
    /// assert_eq!(rx.len(), 0);
    ///
    /// tx.send(()).unwrap();
    /// assert_eq!(rx.len(), 1);
    ///
    /// tx.send(()).unwrap();
    /// assert_eq!(rx.len(), 2);
    ///
    /// rx.recv().unwrap();
    /// assert_eq!(rx.len(), 1);
    ///
    /// ```
    pub fn len(&self) -> usize {
        let vtable = self.vtable();

        vtable.receiver_len()(self.channel.as_rref())
    }

    /// Returns the amount of values the channel queue can hold.
    ///
    /// This returns None if the channel is unbounded.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// {
    ///     let (tx, rx) = mpmc::bounded::<()>(2);
    ///     assert_eq!(rx.capacity(), Some(2));
    /// }
    /// {
    ///     let (tx, rx) = mpmc::unbounded::<()>();
    ///     assert_eq!(rx.capacity(), None);
    /// }
    ///
    /// ```
    pub fn capacity(&self) -> Option<usize> {
        let vtable = self.vtable();

        vtable.receiver_capacity()(self.channel.as_rref()).into_rust()
    }

    /// Creates an Iterator that receives values from the channel.
    ///
    /// # Example
    ///
    #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")]
    #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")]
    /// use abi_stable::external_types::crossbeam_channel as mpmc;
    ///
    /// use std::thread;
    ///
    /// let (tx, rx) = mpmc::bounded::<usize>(1);
    ///
    /// thread::spawn(move || {
    ///     for i in 0..1000 {
    ///         tx.send(i).unwrap();
    ///     }
    /// });
    ///
    /// for (i, n) in rx.iter().enumerate() {
    ///     assert_eq!(i, n);
    /// }
    ///
    /// ```
    pub fn iter(&self) -> RIter<'_, T> {
        RIter { channel: self }
    }
}

impl<'a, T> IntoIterator for &'a RReceiver<T> {
    type Item = T;
    type IntoIter = RIter<'a, T>;

    /// Creates an Iterator that receives values from the channel.
    #[inline]
    fn into_iter(self) -> RIter<'a, T> {
        self.iter()
    }
}

impl<T> IntoIterator for RReceiver<T> {
    type Item = T;
    type IntoIter = RIntoIter<T>;

    /// Creates an Iterator that receives values from the channel.
    #[inline]
    fn into_iter(self) -> RIntoIter<T> {
        RIntoIter { channel: self }
    }
}

impl<T> Clone for RReceiver<T> {
    /// Clones this channel end,getting another handle into the channel.
    ///
    /// Note that this allocates an RBox<_>.
    fn clone(&self) -> Self {
        let vtable = self.vtable();

        Self {
            channel: vtable.clone_receiver()(self.channel.as_rref()),
            vtable: self.vtable,
        }
    }
}

impl<T> Debug for RReceiver<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt("RReceiver{..}", f)
    }
}

unsafe impl<T: Send> Sync for RReceiver<T> {}

unsafe impl<T: Send> Send for RReceiver<T> {}

impl_from_rust_repr! {
    impl[T] From<Receiver<T>> for RReceiver<T> {
        fn(this){
            Self{
                channel:ErasedReceiver::from_unerased_value(this),
                vtable:MakeVTable::<T>::VTABLE,
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////////

#[inline]
fn result_from<T, E0, E1>(res: RResult<T, E0>) -> Result<T, E1>
where
    E0: Into<E1>,
{
    match res {
        ROk(x) => Ok(x),
        RErr(e) => Err(e.into()),
    }
}

#[repr(C)]
#[derive(StableAbi)]
struct ErasedSender<T>(PhantomData<T>, UnsafeIgnoredType<Sender<T>>);

impl<T> ErasedType<'_> for ErasedSender<T> {
    type Unerased = Sender<T>;
}

#[repr(C)]
#[derive(StableAbi)]
struct ErasedReceiver<T>(PhantomData<T>, UnsafeIgnoredType<Receiver<T>>);

impl<T> ErasedType<'_> for ErasedReceiver<T> {
    type Unerased = Receiver<T>;
}

///////////////////////////////////////////////////////////////////////////////

#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix))]
#[sabi(missing_field(panic))]
//#[sabi(debug_print)]
struct VTable<T> {
    send: extern "C" fn(this: RRef<'_, ErasedSender<T>>, T) -> RResult<(), RSendError<T>>,
    try_send: extern "C" fn(this: RRef<'_, ErasedSender<T>>, T) -> RResult<(), RTrySendError<T>>,
    send_timeout: extern "C" fn(
        this: RRef<'_, ErasedSender<T>>,
        value: T,
        timeout: RDuration,
    ) -> RResult<(), RSendTimeoutError<T>>,
    clone_sender: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> RBox<ErasedSender<T>>,
    sender_is_empty: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> bool,
    sender_is_full: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> bool,
    sender_len: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> usize,
    sender_capacity: extern "C" fn(this: RRef<'_, ErasedSender<T>>) -> ROption<usize>,

    recv: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> RResult<T, RRecvError>,
    try_recv: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> RResult<T, RTryRecvError>,
    recv_timeout: extern "C" fn(
        this: RRef<'_, ErasedReceiver<T>>,
        timeout: RDuration,
    ) -> RResult<T, RRecvTimeoutError>,
    clone_receiver: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> RBox<ErasedReceiver<T>>,
    receiver_is_empty: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> bool,
    receiver_is_full: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> bool,
    receiver_len: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> usize,
    #[sabi(last_prefix_field)]
    receiver_capacity: extern "C" fn(this: RRef<'_, ErasedReceiver<T>>) -> ROption<usize>,
}

struct MakeVTable<'a, T>(&'a T);

impl<'a, T: 'a> MakeVTable<'a, T> {
    const VALUE: VTable<T> = VTable {
        send: ErasedSender::send,
        try_send: ErasedSender::try_send,
        send_timeout: ErasedSender::send_timeout,
        clone_sender: ErasedSender::clone,
        sender_is_empty: ErasedSender::is_empty,
        sender_is_full: ErasedSender::is_full,
        sender_len: ErasedSender::len,
        sender_capacity: ErasedSender::capacity,

        recv: ErasedReceiver::recv,
        try_recv: ErasedReceiver::try_recv,
        recv_timeout: ErasedReceiver::recv_timeout,
        clone_receiver: ErasedReceiver::clone,
        receiver_is_empty: ErasedReceiver::is_empty,
        receiver_is_full: ErasedReceiver::is_full,
        receiver_len: ErasedReceiver::len,
        receiver_capacity: ErasedReceiver::capacity,
    };

    staticref! {
        const WM_VALUE: WithMetadata<VTable<T>> = WithMetadata::new(Self::VALUE)
    }

    // The VTABLE for this type in this executable/library
    const VTABLE: VTable_Ref<T> = VTable_Ref(Self::WM_VALUE.as_prefix());
}