theta-sync 0.1.0-alpha.1

A high-performance no_std MPSC channel with full Tokio compatibility
Documentation
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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
#![no_std]

extern crate alloc;

#[cfg(test)]
#[path = "attacks/mod.rs"]
pub mod attacks;

use alloc::{boxed::Box, sync::Arc};
use core::{
    cell::UnsafeCell,
    fmt,
    future::Future,
    hash::{Hash, Hasher},
    mem::{ManuallyDrop, MaybeUninit},
    pin::Pin,
    ptr,
    sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering},
    task::{Context, Poll, Waker},
};

/// Block capacity - platform dependent for optimal memory usage
/// 32 messages on 64-bit targets, 16 on 32-bit targets (same as Tokio)
#[cfg(target_pointer_width = "64")]
const BLOCK_CAP: usize = 32;
#[cfg(target_pointer_width = "32")]
const BLOCK_CAP: usize = 16;

/// Error returned when sending on a closed channel
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SendError<T>(pub T);

impl<T> fmt::Display for SendError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "sending on a closed channel")
    }
}

/// Error returned when receiving fails
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TryRecvError {
    /// The channel is currently empty
    Empty,
    /// The channel is closed and empty
    Disconnected,
}

impl fmt::Display for TryRecvError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TryRecvError::Empty => write!(f, "channel is empty"),
            TryRecvError::Disconnected => write!(f, "channel is disconnected"),
        }
    }
}

/// Creates an unbounded MPSC channel
pub fn unbounded_channel<T>() -> (UnboundedSender<T>, UnboundedReceiver<T>) {
    let block = Block::new(0);
    let block_ptr = Box::into_raw(Box::new(block));

    let shared = Arc::new(Shared {
        head: AtomicPtr::new(block_ptr),
        tail: AtomicPtr::new(block_ptr),
        rx_waker: AtomicPtr::new(ptr::null_mut()),
        waker_lock: AtomicBool::new(false),
        num_senders: AtomicUsize::new(1),
        num_weak_senders: AtomicUsize::new(0),
        closed: AtomicBool::new(false),
    });

    let sender = UnboundedSender {
        shared: Arc::clone(&shared),
    };
    let receiver = UnboundedReceiver {
        shared,
        recv_index: 0,
    };

    (sender, receiver)
}

/// Block structure for the linked list
struct Block<T> {
    /// Next block in the linked list
    next: AtomicPtr<Block<T>>,
    /// Starting index for this block
    start_index: usize,
    /// Values stored in this block
    values: UnsafeCell<[MaybeUninit<ManuallyDrop<T>>; BLOCK_CAP]>,
    /// Bit set indicating which slots are ready
    ready_slots: AtomicUsize,
    /// Number of values written to this block
    len: AtomicUsize,
}

impl<T> Block<T> {
    fn new(start_index: usize) -> Self {
        Self {
            next: AtomicPtr::new(ptr::null_mut()),
            start_index,
            values: UnsafeCell::new([const { MaybeUninit::uninit() }; BLOCK_CAP]),
            ready_slots: AtomicUsize::new(0),
            len: AtomicUsize::new(0),
        }
    }

    /// Returns the relative index within this block for the given global index
    fn relative_index(&self, index: usize) -> Option<usize> {
        if index >= self.start_index && index < self.start_index + BLOCK_CAP {
            Some(index - self.start_index)
        } else {
            None
        }
    }

    /// Writes a value to the specified slot
    /// Returns Ok(()) if successful, Err(value) if slot is already occupied
    fn write(&self, relative_index: usize, value: T) -> Result<(), T> {
        if relative_index >= BLOCK_CAP {
            return Err(value);
        }

        let mask = 1 << relative_index;

        // Try to set the ready bit atomically
        let prev_ready = self.ready_slots.fetch_or(mask, Ordering::AcqRel);

        if prev_ready & mask != 0 {
            // Slot already occupied, return the value back
            return Err(value);
        }

        // Write the value to the slot
        unsafe {
            let values = &mut *self.values.get();
            values[relative_index].write(ManuallyDrop::new(value));
        }

        // Don't increment len here since it's already done atomically in send()
        Ok(())
    }

    /// Reads a value from the specified slot
    /// Returns None if slot is empty or not ready
    fn read(&self, relative_index: usize) -> Option<T> {
        if relative_index >= BLOCK_CAP {
            return None;
        }

        let mask = 1 << relative_index;

        // Try to clear the ready bit atomically to claim the slot
        let prev_ready = self.ready_slots.fetch_and(!mask, Ordering::AcqRel);

        if prev_ready & mask == 0 {
            // Slot was not ready, restore the bit and return None
            return None;
        }

        unsafe {
            let values = &*self.values.get();
            Some(ManuallyDrop::into_inner(
                values[relative_index].assume_init_read(),
            ))
        }
    }

    /// Checks if a slot is ready
    fn is_ready(&self, relative_index: usize) -> bool {
        if relative_index >= BLOCK_CAP {
            return false;
        }

        let mask = 1 << relative_index;
        self.ready_slots.load(Ordering::Acquire) & mask != 0
    }

    /// Returns the number of ready slots
    fn ready_count(&self) -> usize {
        self.ready_slots.load(Ordering::Acquire).count_ones() as usize
    }
}

impl<T> Drop for Block<T> {
    fn drop(&mut self) {
        let ready = self.ready_slots.load(Ordering::Relaxed);
        unsafe {
            let values = &mut *self.values.get();
            for i in 0..BLOCK_CAP {
                if ready & (1 << i) != 0 {
                    ManuallyDrop::drop(values[i].assume_init_mut());
                }
            }
        }
    }
}

/// Shared state between senders and receiver
struct Shared<T> {
    /// Pointer to the head block (where new values are written)
    head: AtomicPtr<Block<T>>,
    /// Pointer to the tail block (where values are read)
    tail: AtomicPtr<Block<T>>,
    /// Waker for the receiver task - using atomic approach for no_std compatibility
    rx_waker: AtomicPtr<Waker>,
    /// Atomic flag to prevent concurrent waker access
    waker_lock: AtomicBool,
    /// Number of active senders (strong references)
    num_senders: AtomicUsize,
    /// Number of weak senders
    num_weak_senders: AtomicUsize,
    /// Channel closed flag
    closed: AtomicBool,
}

impl<T> Shared<T> {
    /// Atomically take and wake the stored waker
    fn wake_receiver(&self) {
        // Quick check if there's even a waker to avoid unnecessary locking
        if self.rx_waker.load(Ordering::Acquire).is_null() {
            return; // No waker, skip the expensive spin lock
        }

        // Spin lock to ensure exclusive access to waker
        while self
            .waker_lock
            .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            core::hint::spin_loop();
        }

        // Take the waker if it exists
        let waker_ptr = self.rx_waker.swap(ptr::null_mut(), Ordering::Acquire);
        if !waker_ptr.is_null() {
            let waker = unsafe { Box::from_raw(waker_ptr) };
            // Release lock before waking to avoid holding it during wake
            self.waker_lock.store(false, Ordering::Release);
            waker.wake();
        } else {
            // Release lock
            self.waker_lock.store(false, Ordering::Release);
        }
    }

    /// Atomically store a new waker
    fn store_waker(&self, waker: Waker) {
        // Spin lock to ensure exclusive access to waker
        while self
            .waker_lock
            .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            core::hint::spin_loop();
        }

        // Replace the old waker
        let new_waker_ptr = Box::into_raw(Box::new(waker));
        let old_waker_ptr = self.rx_waker.swap(new_waker_ptr, Ordering::Release);

        // Clean up old waker if it existed
        if !old_waker_ptr.is_null() {
            unsafe { drop(Box::from_raw(old_waker_ptr)) };
        }

        // Release lock
        self.waker_lock.store(false, Ordering::Release);
    }
}

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

impl<T> Drop for Shared<T> {
    fn drop(&mut self) {
        // Clean up waker
        let waker_ptr = self.rx_waker.load(Ordering::Relaxed);
        if !waker_ptr.is_null() {
            unsafe { drop(Box::from_raw(waker_ptr)) };
        }

        // Clean up all blocks in the linked list
        let mut current = self.tail.load(Ordering::Relaxed);
        while !current.is_null() {
            let block = unsafe { Box::from_raw(current) };
            current = block.next.load(Ordering::Relaxed);
        }
    }
}

/// The sending half of an unbounded MPSC channel
pub struct UnboundedSender<T> {
    shared: Arc<Shared<T>>,
}

/// An unbounded sender that does not prevent the channel from being closed.
///
/// If all [`UnboundedSender`] instances of a channel were dropped and only
/// `WeakUnboundedSender` instances remain, the channel is closed.
///
/// In order to send messages, the `WeakUnboundedSender` needs to be upgraded using
/// [`WeakUnboundedSender::upgrade`], which returns `Option<UnboundedSender>`. It returns `None`
/// if all `UnboundedSender`s have been dropped, and otherwise it returns an `UnboundedSender`.
///
/// [`UnboundedSender`]: UnboundedSender
/// [`WeakUnboundedSender::upgrade`]: WeakUnboundedSender::upgrade
///
/// # Examples
///
/// ```
/// use theta_sync::unbounded_channel;
///
/// let (tx, _rx) = unbounded_channel::<i32>();
/// let tx_weak = tx.downgrade();
///
/// // Upgrading will succeed because `tx` still exists.
/// assert!(tx_weak.upgrade().is_some());
///
/// // If we drop `tx`, then it will fail.
/// drop(tx);
/// assert!(tx_weak.upgrade().is_none());
/// ```
pub struct WeakUnboundedSender<T> {
    shared: Arc<Shared<T>>,
}

impl<T> Clone for WeakUnboundedSender<T> {
    fn clone(&self) -> Self {
        self.shared.num_weak_senders.fetch_add(1, Ordering::Relaxed);
        Self {
            shared: Arc::clone(&self.shared),
        }
    }
}

impl<T> Drop for WeakUnboundedSender<T> {
    fn drop(&mut self) {
        self.shared.num_weak_senders.fetch_sub(1, Ordering::AcqRel);
    }
}

impl<T> Clone for UnboundedSender<T> {
    fn clone(&self) -> Self {
        self.shared.num_senders.fetch_add(1, Ordering::Relaxed);
        Self {
            shared: Arc::clone(&self.shared),
        }
    }
}

impl<T> Drop for UnboundedSender<T> {
    fn drop(&mut self) {
        let prev_count = self.shared.num_senders.fetch_sub(1, Ordering::AcqRel);
        if prev_count == 1 {
            // Last sender dropped, close the channel
            self.shared.closed.store(true, Ordering::Release);

            // Wake up the receiver
            self.shared.wake_receiver();
        }
    }
}

impl<T> UnboundedSender<T> {
    /// Sends a value on this channel
    ///
    /// This method never blocks. It will return an error if the receiver has been dropped.
    pub fn send(&self, mut value: T) -> Result<(), SendError<T>> {
        if self.shared.closed.load(Ordering::Acquire) {
            return Err(SendError(value));
        }

        let mut attempts = 0;
        loop {
            let head_ptr = self.shared.head.load(Ordering::Acquire);
            let head = unsafe { &*head_ptr };

            // Atomically allocate the next slot to maintain FIFO ordering
            let slot_idx = head.len.fetch_add(1, Ordering::AcqRel);

            if slot_idx < BLOCK_CAP {
                // We have a valid slot index, try to write to it
                // This should always succeed since we atomically allocated the slot
                match head.write(slot_idx, value) {
                    Ok(()) => {
                        // Successfully written, wake receiver
                        self.shared.wake_receiver();
                        return Ok(());
                    }
                    Err(returned_value) => {
                        // This should rarely happen, but if it does, the slot was somehow occupied
                        // We need to retry with a new allocation
                        value = returned_value;
                        head.len.fetch_sub(1, Ordering::AcqRel); // Rollback the allocation
                                                                 // Continue the loop to try again
                        continue;
                    }
                }
            } else {
                // Block is full, reset the len counter to prevent overflow
                head.len.store(BLOCK_CAP, Ordering::Release);
            }

            // Block is full, need to allocate a new one
            let next_ptr = head.next.load(Ordering::Acquire);
            if next_ptr.is_null() {
                // Try to allocate and link a new block
                let new_block = Box::into_raw(Box::new(Block::new(head.start_index + BLOCK_CAP)));

                match head.next.compare_exchange_weak(
                    ptr::null_mut(),
                    new_block,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                ) {
                    Ok(_) => {
                        // Successfully linked new block, update head
                        self.shared.head.store(new_block, Ordering::Release);
                    }
                    Err(_) => {
                        // Someone else allocated a block, free ours
                        unsafe { drop(Box::from_raw(new_block)) };
                    }
                }
            } else {
                // Move head to the next block
                self.shared
                    .head
                    .compare_exchange_weak(head_ptr, next_ptr, Ordering::AcqRel, Ordering::Acquire)
                    .ok();
            }

            attempts += 1;
            if attempts > 1000 {
                // Prevent infinite loops in pathological cases
                core::hint::spin_loop();
                attempts = 0;
            }
        }
    }

    /// Returns a unique identifier for this channel based on the shared pointer address
    pub fn id(&self) -> usize {
        Arc::as_ptr(&self.shared) as usize
    }

    /// Checks if the channel is closed
    pub fn is_closed(&self) -> bool {
        self.shared.closed.load(Ordering::Acquire)
    }

    /// Returns true if this sender and another sender send to the same channel
    pub fn same_channel(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.shared, &other.shared)
    }

    /// Converts the `UnboundedSender` to a [`WeakUnboundedSender`] that does not count
    /// towards RAII semantics, i.e. if all `UnboundedSender` instances of the
    /// channel were dropped and only `WeakUnboundedSender` instances remain,
    /// the channel is closed.
    #[must_use = "Downgrade creates a WeakSender without destroying the original non-weak sender."]
    pub fn downgrade(&self) -> WeakUnboundedSender<T> {
        self.shared.num_weak_senders.fetch_add(1, Ordering::Relaxed);
        WeakUnboundedSender {
            shared: Arc::clone(&self.shared),
        }
    }

    /// Returns the number of [`UnboundedSender`] handles.
    pub fn strong_count(&self) -> usize {
        self.shared.num_senders.load(Ordering::Acquire)
    }

    /// Returns the number of [`WeakUnboundedSender`] handles.
    pub fn weak_count(&self) -> usize {
        self.shared.num_weak_senders.load(Ordering::Acquire)
    }

    /// Completes when the receiver has dropped.
    ///
    /// This allows the producers to get notified when interest in the produced values is canceled and immediately stop doing work.
    pub async fn closed(&self) {
        ClosedFuture { sender: self }.await
    }
}

impl<T> WeakUnboundedSender<T> {
    /// Tries to convert a `WeakUnboundedSender` into an [`UnboundedSender`].
    /// This will return `Some` if there are other `UnboundedSender` instances alive and
    /// the channel wasn't previously dropped, otherwise `None` is returned.
    pub fn upgrade(&self) -> Option<UnboundedSender<T>> {
        let mut count = self.shared.num_senders.load(Ordering::Acquire);

        loop {
            if count == 0 {
                // No strong senders remaining, cannot upgrade
                return None;
            }

            match self.shared.num_senders.compare_exchange_weak(
                count,
                count + 1,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    return Some(UnboundedSender {
                        shared: Arc::clone(&self.shared),
                    });
                }
                Err(actual) => count = actual,
            }
        }
    }

    /// Returns the number of [`UnboundedSender`] handles.
    pub fn strong_count(&self) -> usize {
        self.shared.num_senders.load(Ordering::Acquire)
    }

    /// Returns the number of [`WeakUnboundedSender`] handles.
    pub fn weak_count(&self) -> usize {
        self.shared.num_weak_senders.load(Ordering::Acquire)
    }
}

impl<T> PartialEq for UnboundedSender<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl<T> Eq for UnboundedSender<T> {}

impl<T> PartialOrd for UnboundedSender<T> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Ord for UnboundedSender<T> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.id().cmp(&other.id())
    }
}

impl<T> Hash for UnboundedSender<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id().hash(state);
    }
}

impl<T> PartialEq for WeakUnboundedSender<T> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.shared, &other.shared)
    }
}

impl<T> Eq for WeakUnboundedSender<T> {}

impl<T> PartialOrd for WeakUnboundedSender<T> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Ord for WeakUnboundedSender<T> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        let self_ptr = Arc::as_ptr(&self.shared) as usize;
        let other_ptr = Arc::as_ptr(&other.shared) as usize;
        self_ptr.cmp(&other_ptr)
    }
}

impl<T> Hash for WeakUnboundedSender<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let ptr = Arc::as_ptr(&self.shared) as usize;
        ptr.hash(state);
    }
}

impl<T> fmt::Debug for UnboundedSender<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("UnboundedSender")
            .field("id", &self.id())
            .field("strong_count", &self.strong_count())
            .field("weak_count", &self.weak_count())
            .finish()
    }
}

impl<T> fmt::Debug for WeakUnboundedSender<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WeakUnboundedSender")
            .field("strong_count", &self.strong_count())
            .field("weak_count", &self.weak_count())
            .finish()
    }
}

/// The receiving half of an unbounded MPSC channel
pub struct UnboundedReceiver<T> {
    shared: Arc<Shared<T>>,
    /// Current position for reading
    recv_index: usize,
}

impl<T> UnboundedReceiver<T> {
    /// Receives a value from the channel asynchronously
    pub async fn recv(&mut self) -> Option<T> {
        RecvFuture { receiver: self }.await
    }

    /// Attempts to receive a value without blocking
    pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
        loop {
            let tail_ptr = self.shared.tail.load(Ordering::Acquire);
            let tail = unsafe { &*tail_ptr };

            if let Some(relative_idx) = tail.relative_index(self.recv_index) {
                // We're in the current tail block
                if tail.is_ready(relative_idx) {
                    if let Some(value) = tail.read(relative_idx) {
                        self.recv_index += 1;
                        return Ok(value);
                    }
                }

                // Check if we need to move to the next block
                if relative_idx == BLOCK_CAP - 1
                    || tail.ready_count() == tail.len.load(Ordering::Acquire)
                {
                    let next_ptr = tail.next.load(Ordering::Acquire);
                    if !next_ptr.is_null() {
                        // Move to next block and try to free the current one
                        if self
                            .shared
                            .tail
                            .compare_exchange(
                                tail_ptr,
                                next_ptr,
                                Ordering::AcqRel,
                                Ordering::Acquire,
                            )
                            .is_ok()
                        {
                            // Successfully moved tail, free the old block
                            unsafe { drop(Box::from_raw(tail_ptr)) };
                        }
                        continue;
                    }
                }
            } else {
                // We're behind the current tail block, advance
                let next_ptr = tail.next.load(Ordering::Acquire);
                if !next_ptr.is_null() {
                    if self
                        .shared
                        .tail
                        .compare_exchange(tail_ptr, next_ptr, Ordering::AcqRel, Ordering::Acquire)
                        .is_ok()
                    {
                        unsafe { drop(Box::from_raw(tail_ptr)) };
                    }
                    continue;
                }
            }

            // No data available
            if self.shared.closed.load(Ordering::Acquire)
                && self.shared.num_senders.load(Ordering::Acquire) == 0
            {
                return Err(TryRecvError::Disconnected);
            }

            return Err(TryRecvError::Empty);
        }
    }

    /// Returns a unique identifier for this channel based on the shared pointer address
    pub fn id(&self) -> usize {
        Arc::as_ptr(&self.shared) as usize
    }

    /// Checks if the channel is closed and empty
    pub fn is_closed(&self) -> bool {
        self.shared.closed.load(Ordering::Acquire)
            && self.shared.num_senders.load(Ordering::Acquire) == 0
    }

    /// Checks if the channel is currently empty
    pub fn is_empty(&self) -> bool {
        // We need to create a temporary receiver to check if it's empty
        // Since this method takes &self, we can't call try_recv which requires &mut self
        // Instead, we'll check the state without modifying the receiver

        let tail_ptr = self.shared.tail.load(Ordering::Acquire);
        let tail = unsafe { &*tail_ptr };

        if let Some(relative_idx) = tail.relative_index(self.recv_index) {
            // Check if there's data ready at our current position
            if tail.is_ready(relative_idx) {
                return false; // Not empty
            }
        }

        // Check if channel is disconnected
        if self.shared.closed.load(Ordering::Acquire)
            && self.shared.num_senders.load(Ordering::Acquire) == 0
        {
            return true; // Empty and disconnected
        }

        // Assume empty if we can't find ready data at current position
        true
    }

    /// Closes the receiving half of the channel without dropping it
    pub fn close(&mut self) {
        self.shared.closed.store(true, Ordering::Release);
    }

    /// Returns the number of [`UnboundedSender`] handles.
    pub fn sender_strong_count(&self) -> usize {
        self.shared.num_senders.load(Ordering::Acquire)
    }

    /// Returns the number of [`WeakUnboundedSender`] handles.
    pub fn sender_weak_count(&self) -> usize {
        self.shared.num_weak_senders.load(Ordering::Acquire)
    }

    /// Returns the number of messages in the channel.
    pub fn len(&self) -> usize {
        // Count ready messages across all blocks
        let mut count = 0;
        let mut current = self.shared.tail.load(Ordering::Acquire);

        while !current.is_null() {
            let block = unsafe { &*current };
            count += block.ready_count();
            current = block.next.load(Ordering::Acquire);
        }

        count
    }

    fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
        match self.try_recv() {
            Ok(value) => Poll::Ready(Some(value)),
            Err(TryRecvError::Disconnected) => Poll::Ready(None),
            Err(TryRecvError::Empty) => {
                // Store waker and return Pending
                self.shared.store_waker(cx.waker().clone());
                Poll::Pending
            }
        }
    }
}

impl<T> Drop for UnboundedReceiver<T> {
    fn drop(&mut self) {
        self.shared.closed.store(true, Ordering::Release);
    }
}

/// Future returned by `UnboundedReceiver::recv()`
struct RecvFuture<'a, T> {
    receiver: &'a mut UnboundedReceiver<T>,
}

impl<'a, T> Future for RecvFuture<'a, T> {
    type Output = Option<T>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.receiver.poll_recv(cx)
    }
}

/// Future returned by `UnboundedSender::closed()`
struct ClosedFuture<'a, T> {
    sender: &'a UnboundedSender<T>,
}

impl<'a, T> Future for ClosedFuture<'a, T> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.sender.is_closed() {
            Poll::Ready(())
        } else {
            // In a real implementation, we'd store the waker and wake it when the channel closes
            // For now, just return Pending - this is a simplified implementation
            Poll::Pending
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{vec, vec::Vec};

    #[test]
    fn test_basic_send_recv() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        tx.send(1).unwrap();
        tx.send(2).unwrap();
        tx.send(3).unwrap();

        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);
        assert_eq!(rx.try_recv().unwrap(), 3);
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
    }

    #[test]
    fn test_channel_id() {
        let (tx1, rx1) = unbounded_channel::<i32>();
        let (tx2, rx2) = unbounded_channel::<i32>();

        assert_eq!(tx1.id(), rx1.id());
        assert_ne!(tx1.id(), tx2.id());
        assert_ne!(rx1.id(), rx2.id());
    }

    #[test]
    fn test_clone_sender() {
        let (tx, mut rx) = unbounded_channel::<i32>();
        let tx2 = tx.clone();

        tx.send(1).unwrap();
        tx2.send(2).unwrap();

        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);
    }

    #[test]
    fn test_large_number_of_messages() {
        let (tx, mut rx) = unbounded_channel::<usize>();

        // Send more messages than a single block can hold
        for i in 0..100 {
            tx.send(i).unwrap();
        }

        // Receive all messages
        for i in 0..100 {
            assert_eq!(rx.try_recv().unwrap(), i);
        }
    }

    #[test]
    fn test_drop_sender_closes_channel() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        tx.send(42).unwrap();
        drop(tx);

        assert_eq!(rx.try_recv().unwrap(), 42);
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
    }

    #[test]
    fn test_same_channel() {
        let (tx1, _rx) = unbounded_channel::<i32>();
        let tx2 = tx1.clone();
        let (tx3, _rx2) = unbounded_channel::<i32>();

        assert!(tx1.same_channel(&tx2));
        assert!(!tx1.same_channel(&tx3));
    }

    // === EDGE CASES AND INTENSIVE TESTS ===

    #[test]
    fn test_stress_many_messages() {
        let (tx, mut rx) = unbounded_channel::<usize>();
        const NUM_MESSAGES: usize = 10_000;

        // Send many messages
        for i in 0..NUM_MESSAGES {
            tx.send(i).unwrap();
        }

        // Receive all messages in order
        for i in 0..NUM_MESSAGES {
            assert_eq!(rx.try_recv().unwrap(), i);
        }

        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
    }

    #[test]
    fn test_send_recv_interleaved() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Interleave sends and receives
        let mut expected_recv = 0;
        for i in 0..100 {
            tx.send(i).unwrap();
            if i % 2 == 0 {
                assert_eq!(rx.try_recv().unwrap(), expected_recv);
                expected_recv += 1;
            }
        }

        // Receive remaining messages
        while let Ok(value) = rx.try_recv() {
            assert_eq!(value, expected_recv);
            expected_recv += 1;
        }

        assert_eq!(expected_recv, 100); // Should have received all 100 messages
    }

    #[test]
    fn test_drop_receiver_while_sending() {
        let (tx, rx) = unbounded_channel::<i32>();

        // Send some messages
        tx.send(1).unwrap();
        tx.send(2).unwrap();

        // Drop receiver
        drop(rx);

        // Further sends should fail
        assert!(matches!(tx.send(3), Err(SendError(3))));
        assert!(tx.is_closed());
    }

    #[test]
    fn test_multiple_sender_drops() {
        let (tx, mut rx) = unbounded_channel::<i32>();
        let tx2 = tx.clone();
        let tx3 = tx.clone();

        tx.send(1).unwrap();
        tx2.send(2).unwrap();
        tx3.send(3).unwrap();

        // Drop senders one by one
        drop(tx);
        assert!(!rx.is_closed());

        drop(tx2);
        assert!(!rx.is_closed());

        // Last sender drop should close channel
        drop(tx3);

        // Receive existing messages
        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);
        assert_eq!(rx.try_recv().unwrap(), 3);

        // Channel should be disconnected
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
        assert!(rx.is_closed());
    }

    #[test]
    fn test_zero_sized_types() {
        #[derive(Debug, PartialEq)]
        struct ZeroSized;

        let (tx, mut rx) = unbounded_channel::<ZeroSized>();

        tx.send(ZeroSized).unwrap();
        tx.send(ZeroSized).unwrap();

        assert_eq!(rx.try_recv().unwrap(), ZeroSized);
        assert_eq!(rx.try_recv().unwrap(), ZeroSized);
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
    }

    #[test]
    fn test_large_types() {
        #[derive(Debug, PartialEq)]
        struct LargeType([u8; 1024]);

        let (tx, mut rx) = unbounded_channel::<LargeType>();
        let large_value = LargeType([42; 1024]);

        tx.send(large_value).unwrap();
        let received = rx.try_recv().unwrap();
        
        // Verify the entire array, not just first and last bytes
        assert_eq!(received.0.len(), 1024);
        for &byte in &received.0 {
            assert_eq!(byte, 42, "Large type data corruption detected");
        }
        
        // Test multiple large messages to ensure no interference
        let large_value2 = LargeType([123; 1024]);
        let large_value3 = LargeType([255; 1024]);
        
        tx.send(large_value2).unwrap();
        tx.send(large_value3).unwrap();
        
        let received2 = rx.try_recv().unwrap();
        let received3 = rx.try_recv().unwrap();
        
        for &byte in &received2.0 {
            assert_eq!(byte, 123, "Second large message corrupted");
        }
        for &byte in &received3.0 {
            assert_eq!(byte, 255, "Third large message corrupted");
        }
    }

    #[test]
    fn test_unwind_safety_basic() {
        // Test that the channel remains functional even with types that might panic on drop
        #[derive(Debug)]
        struct ConditionalPanic(bool);
        impl Drop for ConditionalPanic {
            fn drop(&mut self) {
                // We can't actually panic in no_std tests, but we can simulate
                // the structure of panic-prone types
                if self.0 {
                    // Simulate resource cleanup that might fail
                    // In real scenarios, this could be file I/O, network calls, etc.
                }
            }
        }

        let (tx, mut rx) = unbounded_channel::<ConditionalPanic>();

        // Send values that simulate both safe and potentially panicking drops
        tx.send(ConditionalPanic(false)).unwrap(); // Safe drop
        tx.send(ConditionalPanic(true)).unwrap();  // Potentially panicking drop
        tx.send(ConditionalPanic(false)).unwrap(); // Safe drop again

        // Channel should work normally regardless of drop behavior
        assert_eq!(rx.try_recv().unwrap().0, false);
        assert_eq!(rx.try_recv().unwrap().0, true);
        assert_eq!(rx.try_recv().unwrap().0, false);
        
        // Test that we can continue using the channel after potentially problematic drops
        tx.send(ConditionalPanic(false)).unwrap();
        assert_eq!(rx.try_recv().unwrap().0, false);
        
        // Channel should remain functional
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
        assert!(!rx.is_closed());
    }

    #[test]
    fn test_block_boundary_conditions() {
        let (tx, mut rx) = unbounded_channel::<usize>();

        // Send exactly BLOCK_CAP messages to fill first block
        for i in 0..BLOCK_CAP {
            tx.send(i).unwrap();
        }

        // Send one more to trigger new block allocation
        tx.send(BLOCK_CAP).unwrap();

        // Receive all messages
        for i in 0..=BLOCK_CAP {
            assert_eq!(rx.try_recv().unwrap(), i);
        }

        // Send messages across multiple blocks
        for i in 0..(BLOCK_CAP * 3) {
            tx.send(i).unwrap();
        }

        for i in 0..(BLOCK_CAP * 3) {
            assert_eq!(rx.try_recv().unwrap(), i);
        }
    }

    #[test]
    fn test_receiver_state_consistency() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Test empty state
        assert!(rx.is_empty());
        assert!(!rx.is_closed());

        // Send and test non-empty state
        tx.send(42).unwrap();
        assert!(!rx.is_empty());
        assert!(!rx.is_closed());

        // Receive and test empty again
        assert_eq!(rx.try_recv().unwrap(), 42);
        assert!(rx.is_empty());
        assert!(!rx.is_closed());

        // Close channel and test closed state
        drop(tx);
        assert!(rx.is_empty());
        assert!(rx.is_closed());
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
    }

    #[test]
    fn test_manual_close() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        tx.send(1).unwrap();
        tx.send(2).unwrap();

        // Manually close receiver
        rx.close();

        // Should still be able to receive existing messages
        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);

        // But sender should see channel as closed
        assert!(tx.is_closed());
        assert!(matches!(tx.send(3), Err(SendError(3))));
    }

    #[test]
    fn test_channel_id_consistency() {
        // Test that sender and receiver from same channel have same ID
        let (tx, rx) = unbounded_channel::<i32>();
        assert_eq!(tx.id(), rx.id());

        // Test that different channels have different IDs (at creation time)
        let (tx2, rx2) = unbounded_channel::<i32>();
        assert_eq!(tx2.id(), rx2.id());

        // Note: Different channels may reuse memory addresses after deallocation,
        // so we only test that senders/receivers from the same channel match
        let tx_clone = tx.clone();
        assert_eq!(tx.id(), tx_clone.id());
        assert!(tx.same_channel(&tx_clone));
        assert!(!tx.same_channel(&tx2));
    }

    #[test]
    fn test_drop_semantics() {
        use alloc::rc::Rc;

        let drop_count = Rc::new(core::cell::RefCell::new(0));

        #[derive(Debug)]
        struct DropCounter(Rc<core::cell::RefCell<i32>>);
        impl Drop for DropCounter {
            fn drop(&mut self) {
                *self.0.borrow_mut() += 1;
            }
        }

        let (tx, mut rx) = unbounded_channel::<DropCounter>();

        // Send some values
        tx.send(DropCounter(drop_count.clone())).unwrap();
        tx.send(DropCounter(drop_count.clone())).unwrap();
        tx.send(DropCounter(drop_count.clone())).unwrap();

        assert_eq!(*drop_count.borrow(), 0); // Nothing dropped yet

        // Receive one value
        let _value1 = rx.try_recv().unwrap();
        assert_eq!(*drop_count.borrow(), 0); // Still holding reference

        drop(_value1);
        assert_eq!(*drop_count.borrow(), 1); // One dropped

        // Drop the channel with remaining values
        drop(tx);
        drop(rx);

        assert_eq!(*drop_count.borrow(), 3); // All should be dropped
    }

    #[test]
    fn test_memory_safety_after_close() {
        let (tx, mut rx) = unbounded_channel::<Vec<u8>>();

        // Send some data
        tx.send(vec![1, 2, 3]).unwrap();
        tx.send(vec![4, 5, 6]).unwrap();

        // Close the receiver
        rx.close();

        // Sender should fail
        assert!(matches!(tx.send(vec![7, 8, 9]), Err(_)));

        // But we should still be able to receive existing data
        assert_eq!(rx.try_recv().unwrap(), vec![1, 2, 3]);
        assert_eq!(rx.try_recv().unwrap(), vec![4, 5, 6]);
    }

    #[test]
    fn test_ordering_guarantees() {
        let (tx, mut rx) = unbounded_channel::<usize>();

        // Send messages in order
        for i in 0..1000 {
            tx.send(i).unwrap();
        }

        // Should receive in the same order
        for i in 0..1000 {
            assert_eq!(rx.try_recv().unwrap(), i);
        }
    }

    #[test]
    fn test_empty_channel_operations() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Operations on empty channel
        assert!(rx.is_empty());
        assert!(!rx.is_closed());
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));

        // Close and test again
        drop(tx);
        assert!(rx.is_empty());
        assert!(rx.is_closed());
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
    }

    #[test]
    fn test_channel_reuse_after_empty() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Send, receive, repeat multiple times
        for round in 0..10 {
            for i in 0..10 {
                tx.send(round * 10 + i).unwrap();
            }

            for i in 0..10 {
                assert_eq!(rx.try_recv().unwrap(), round * 10 + i);
            }

            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
        }
    }

    #[test]
    fn test_mixed_operation_patterns() {
        let (tx, mut rx) = unbounded_channel::<usize>();

        // Pattern: send some, receive some, repeat
        let mut next_send = 0;
        let mut next_recv = 0;

        for _ in 0..100 {
            // Send 1-5 messages
            let send_count = (next_send % 5) + 1;
            for _ in 0..send_count {
                tx.send(next_send).unwrap();
                next_send += 1;
            }

            // Receive 1-3 messages (if available)
            let recv_count = (next_recv % 3) + 1;
            for _ in 0..recv_count {
                if let Ok(value) = rx.try_recv() {
                    assert_eq!(value, next_recv);
                    next_recv += 1;
                } else {
                    break;
                }
            }
        }

        // Receive remaining messages
        while let Ok(value) = rx.try_recv() {
            assert_eq!(value, next_recv);
            next_recv += 1;
        }

        assert_eq!(next_send, next_recv);
    }

    // === WEAK SENDER TESTS ===

    #[test]
    fn test_weak_sender_basic() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Create weak sender
        let weak_tx = tx.downgrade();

        // Upgrade should succeed while strong sender exists
        let upgraded_tx = weak_tx.upgrade().unwrap();

        // Send through upgraded sender
        upgraded_tx.send(42).unwrap();
        assert_eq!(rx.try_recv().unwrap(), 42);

        // Drop original strong sender
        drop(tx);

        // Should still work with upgraded sender
        upgraded_tx.send(43).unwrap();
        assert_eq!(rx.try_recv().unwrap(), 43);

        // Drop upgraded sender
        drop(upgraded_tx);

        // Now upgrade should fail
        assert!(weak_tx.upgrade().is_none());
    }

    #[test]
    fn test_weak_sender_upgrade_failure() {
        let (tx, _rx) = unbounded_channel::<i32>();
        let weak_tx = tx.downgrade();

        // Drop strong sender
        drop(tx);

        // Upgrade should fail
        assert!(weak_tx.upgrade().is_none());
    }

    #[test]
    fn test_weak_sender_counts() {
        let (tx, rx) = unbounded_channel::<i32>();

        // Initial counts
        assert_eq!(tx.strong_count(), 1);
        assert_eq!(tx.weak_count(), 0);
        assert_eq!(rx.sender_strong_count(), 1);
        assert_eq!(rx.sender_weak_count(), 0);

        // Create weak sender
        let weak_tx = tx.downgrade();
        assert_eq!(tx.strong_count(), 1);
        assert_eq!(tx.weak_count(), 1);
        assert_eq!(weak_tx.strong_count(), 1);
        assert_eq!(weak_tx.weak_count(), 1);
        assert_eq!(rx.sender_strong_count(), 1);
        assert_eq!(rx.sender_weak_count(), 1);

        // Clone strong sender
        let tx2 = tx.clone();
        assert_eq!(tx.strong_count(), 2);
        assert_eq!(tx.weak_count(), 1);
        assert_eq!(tx2.strong_count(), 2);
        assert_eq!(weak_tx.strong_count(), 2);
        assert_eq!(weak_tx.weak_count(), 1);
        assert_eq!(rx.sender_strong_count(), 2);
        assert_eq!(rx.sender_weak_count(), 1);

        // Clone weak sender
        let weak_tx2 = weak_tx.clone();
        assert_eq!(tx.strong_count(), 2);
        assert_eq!(tx.weak_count(), 2);
        assert_eq!(weak_tx.weak_count(), 2);
        assert_eq!(weak_tx2.weak_count(), 2);
        assert_eq!(rx.sender_strong_count(), 2);
        assert_eq!(rx.sender_weak_count(), 2);

        // Drop weak sender
        drop(weak_tx);
        assert_eq!(tx.weak_count(), 1);
        assert_eq!(weak_tx2.weak_count(), 1);
        assert_eq!(rx.sender_weak_count(), 1);

        // Drop strong sender
        drop(tx);
        assert_eq!(tx2.strong_count(), 1);
        assert_eq!(weak_tx2.strong_count(), 1);
        assert_eq!(rx.sender_strong_count(), 1);

        // Drop last strong sender
        drop(tx2);
        assert_eq!(weak_tx2.strong_count(), 0);
        assert_eq!(weak_tx2.weak_count(), 1);
        assert_eq!(rx.sender_strong_count(), 0);
        assert_eq!(rx.sender_weak_count(), 1);

        // Upgrade should now fail
        assert!(weak_tx2.upgrade().is_none());
    }

    #[test]
    fn test_weak_sender_channel_close() {
        let (tx, rx) = unbounded_channel::<i32>();
        let weak_tx = tx.downgrade();

        // Drop strong sender
        drop(tx);

        // Channel should be closed
        assert!(rx.is_closed());

        // Weak sender should not be able to upgrade
        assert!(weak_tx.upgrade().is_none());
    }

    #[test]
    fn test_sender_ordering_and_equality() {
        let (tx1, _rx1) = unbounded_channel::<i32>();
        let (tx2, _rx2) = unbounded_channel::<i32>();

        let tx1_clone = tx1.clone();
        let weak_tx1 = tx1.downgrade();
        let weak_tx2 = tx2.downgrade();

        // Same channel senders should be equal
        assert_eq!(tx1, tx1_clone);

        // Different channels should not be equal
        assert_ne!(tx1, tx2);

        // Weak senders from same channel should be equal
        assert_eq!(weak_tx1, weak_tx1.clone());

        // Weak senders from different channels should not be equal
        assert_ne!(weak_tx1, weak_tx2);

        // Test ordering (consistent but not necessarily meaningful)
        let ordering1 = tx1.cmp(&tx2);
        let ordering2 = tx1.cmp(&tx2);
        assert_eq!(ordering1, ordering2); // Should be consistent

        // Test hashing (same senders should have same hash)
        use alloc::collections::BTreeSet;
        let mut set = BTreeSet::new();
        set.insert(tx1.clone());
        set.insert(tx1_clone.clone());
        assert_eq!(set.len(), 1); // Same sender, so only one in set

        set.insert(tx2.clone());
        assert_eq!(set.len(), 2); // Different sender, so now two in set
    }

    #[test]
    fn test_weak_sender_multiple_upgrades() {
        let (tx, mut rx) = unbounded_channel::<i32>();
        let weak_tx = tx.downgrade();

        // Multiple upgrades should work
        let upgraded1 = weak_tx.upgrade().unwrap();
        let upgraded2 = weak_tx.upgrade().unwrap();

        upgraded1.send(1).unwrap();
        upgraded2.send(2).unwrap();

        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);

        // Drop original and one upgrade
        drop(tx);
        drop(upgraded1);

        // Should still be able to upgrade and send
        let upgraded3 = weak_tx.upgrade().unwrap();
        upgraded3.send(3).unwrap();
        assert_eq!(rx.try_recv().unwrap(), 3);

        // Drop remaining senders
        drop(upgraded2);
        drop(upgraded3);

        // Now upgrade should fail
        assert!(weak_tx.upgrade().is_none());
    }

    #[test]
    fn test_sender_hash_collections() {
        use alloc::collections::BTreeSet;

        let (tx1, _rx1) = unbounded_channel::<i32>();
        let (tx2, _rx2) = unbounded_channel::<i32>();
        let tx1_clone = tx1.clone();

        // Test with HashSet equivalent (BTreeSet in no_std)
        let mut set = BTreeSet::new();

        // Insert original sender
        set.insert(tx1.clone());
        assert_eq!(set.len(), 1);

        // Insert clone of same sender - should not increase size
        set.insert(tx1_clone);
        assert_eq!(set.len(), 1);

        // Insert different sender - should increase size
        set.insert(tx2);
        assert_eq!(set.len(), 2);

        // Test weak senders
        let weak_tx1 = tx1.downgrade();
        let weak_tx1_clone = weak_tx1.clone();

        let mut weak_set = BTreeSet::new();
        weak_set.insert(weak_tx1);
        weak_set.insert(weak_tx1_clone); // Should not increase size
        assert_eq!(weak_set.len(), 1);
    }

    // === NEW TOKIO-COMPATIBLE TESTS ===

    #[test]
    fn test_len_method() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Empty channel
        assert_eq!(rx.len(), 0);
        assert!(rx.is_empty());

        // Send some messages and verify len increases
        tx.send(1).unwrap();
        assert_eq!(rx.len(), 1);
        assert!(!rx.is_empty());

        tx.send(2).unwrap();
        tx.send(3).unwrap();
        assert_eq!(rx.len(), 3);
        assert!(!rx.is_empty());
        
        // Receive messages and verify len decreases
        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.len(), 2);
        assert!(!rx.is_empty());
        
        assert_eq!(rx.try_recv().unwrap(), 2);
        assert_eq!(rx.len(), 1);
        assert!(!rx.is_empty());
        
        assert_eq!(rx.try_recv().unwrap(), 3);
        assert_eq!(rx.len(), 0);
        assert!(rx.is_empty());
        
        // Verify empty channel state
        assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
    }

    /// Compare drop behavior with Tokio's implementation
    /// Tests whether unread messages are properly dropped when receiver is dropped
    #[test]
    fn test_tokio_drop_behavior_compatibility() {
        use alloc::sync::Arc;
        use core::sync::atomic::{AtomicUsize, Ordering};

        // Drop counter to track when messages are dropped
        #[derive(Debug)]
        struct DropCounter {
            #[allow(dead_code)]
            id: usize,
            counter: Arc<AtomicUsize>,
        }

        impl Drop for DropCounter {
            fn drop(&mut self) {
                self.counter.fetch_add(1, Ordering::SeqCst);
            }
        }

        const NUM_MESSAGES: usize = 100; // Smaller for unit test

        // Test our implementation
        let our_drop_counter = Arc::new(AtomicUsize::new(0));
        {
            let (tx, mut rx) = unbounded_channel::<DropCounter>();

            // Send messages
            for i in 0..NUM_MESSAGES {
                let msg = DropCounter {
                    id: i,
                    counter: Arc::clone(&our_drop_counter),
                };
                tx.send(msg).unwrap();
            }

            // Receive only first few messages
            for _ in 0..10 {
                let _msg = rx.try_recv().unwrap();
                // Let them drop immediately
            }

            // Drop receiver - this should drop all remaining messages
            drop(rx);
            drop(tx);
        }

        let our_dropped_count = our_drop_counter.load(Ordering::SeqCst);

        // All messages should have been dropped
        assert_eq!(
            our_dropped_count, NUM_MESSAGES,
            "Our implementation should drop all {} messages",
            NUM_MESSAGES
        );
    }

    /// Test the exact same condition as described in Tokio docs:
    /// "If the Receiver handle is dropped, then messages can no longer be read out of the channel.
    /// In this case, all further attempts to send will result in an error. Additionally,
    /// all unread messages will be drained from the channel and dropped."
    #[test]
    fn test_tokio_exact_drop_condition() {
        use alloc::sync::Arc;
        use alloc::vec::Vec;
        use core::sync::atomic::{AtomicUsize, Ordering};

        #[derive(Debug)]
        struct DropTracker {
            #[allow(dead_code)]
            id: usize,
            counter: Arc<AtomicUsize>,
        }

        impl Drop for DropTracker {
            fn drop(&mut self) {
                self.counter.fetch_add(1, Ordering::SeqCst);
            }
        }

        const NUM_MESSAGES: usize = 50; // Smaller for unit test
        let drop_counter = Arc::new(AtomicUsize::new(0));

        let (tx, mut rx) = unbounded_channel::<DropTracker>();
        let tx_clone = tx.clone();

        // Fill the channel with messages
        for i in 0..NUM_MESSAGES {
            let msg = DropTracker {
                id: i,
                counter: Arc::clone(&drop_counter),
            };
            tx.send(msg).unwrap();
        }

        // Receive some messages (but not all)
        let received_before_drop = 10;
        for _ in 0..received_before_drop {
            let _msg = rx.try_recv().unwrap();
        }

        // Test condition 1: Drop receiver while messages remain
        drop(rx);

        // Test condition 2: Further attempts to send should result in error
        let mut send_errors = 0;
        let mut failed_messages = Vec::new();

        // Try to send more messages after receiver is dropped
        for i in NUM_MESSAGES..NUM_MESSAGES + 10 {
            let msg = DropTracker {
                id: i,
                counter: Arc::clone(&drop_counter),
            };

            match tx_clone.send(msg) {
                Ok(_) => {
                    // This shouldn't happen if receiver is properly dropped
                    panic!("Send succeeded after receiver drop - this violates Tokio behavior");
                }
                Err(send_error) => {
                    send_errors += 1;
                    failed_messages.push(send_error.0); // Extract the message from SendError
                }
            }
        }

        // Drop the senders to clean up
        drop(tx);
        drop(tx_clone);

        // Drop the failed messages explicitly to ensure they're counted
        drop(failed_messages);

        let final_drop_count = drop_counter.load(Ordering::SeqCst);

        // Verify the Tokio documented behavior:
        // 1. All unread messages are drained and dropped
        // 2. All received messages are dropped
        // 3. All failed send messages are dropped
        let expected_total_drops = NUM_MESSAGES + send_errors;
        assert_eq!(
            final_drop_count, expected_total_drops,
            "Expected {} drops (original {} + failed sends {}), got {}",
            expected_total_drops, NUM_MESSAGES, send_errors, final_drop_count
        );

        // 4. Further send attempts result in errors
        assert!(
            send_errors > 0,
            "Send attempts after receiver drop should fail"
        );
    }

    #[test]
    fn test_tokio_api_compatibility() {
        let (tx, mut rx) = unbounded_channel::<i32>();

        // Test basic Tokio-like APIs
        assert!(!tx.is_closed());
        assert!(!rx.is_closed());
        assert!(rx.is_empty());
        assert_eq!(rx.len(), 0);

        // Test sender counts
        assert_eq!(tx.strong_count(), 1);
        assert_eq!(tx.weak_count(), 0);
        assert_eq!(rx.sender_strong_count(), 1);
        assert_eq!(rx.sender_weak_count(), 0);

        // Test channel identification
        assert!(tx.same_channel(&tx));
        assert_eq!(tx.id(), rx.id());

        // Test weak sender creation
        let _weak_tx = tx.downgrade();
        assert_eq!(tx.weak_count(), 1);
        assert_eq!(rx.sender_weak_count(), 1);

        // Test message sending and length tracking
        tx.send(42).unwrap();
        assert_eq!(rx.len(), 1);
        assert!(!rx.is_empty());

        // Test message receiving
        assert_eq!(rx.try_recv().unwrap(), 42);
        assert_eq!(rx.len(), 0);
        assert!(rx.is_empty());
    }

    /// Test drop behavior when all senders are dropped (with and without remaining messages)
    /// This complements the receiver drop tests and ensures full Tokio compatibility
    #[test]
    fn test_sender_drop_behavior_comprehensive() {
        use alloc::sync::Arc;
        use core::sync::atomic::{AtomicUsize, Ordering};

        #[derive(Debug)]
        struct DropTracker {
            #[allow(dead_code)]
            id: usize,
            counter: Arc<AtomicUsize>,
        }

        impl Drop for DropTracker {
            fn drop(&mut self) {
                self.counter.fetch_add(1, Ordering::SeqCst);
            }
        }

        // Test Case 1: All senders dropped with remaining messages in channel
        {
            let drop_counter = Arc::new(AtomicUsize::new(0));
            const NUM_MESSAGES: usize = 50;

            let (tx, mut rx) = unbounded_channel::<DropTracker>();
            let tx2 = tx.clone();
            let tx3 = tx.clone();

            // Send messages from multiple senders
            for i in 0..NUM_MESSAGES {
                let msg = DropTracker {
                    id: i,
                    counter: Arc::clone(&drop_counter),
                };

                // Distribute sends across different senders
                match i % 3 {
                    0 => tx.send(msg).unwrap(),
                    1 => tx2.send(msg).unwrap(),
                    2 => tx3.send(msg).unwrap(),
                    _ => unreachable!(),
                }
            }

            // Receive only some messages
            let received_count = 15;
            for _ in 0..received_count {
                let _msg = rx.try_recv().unwrap();
            }

            assert_eq!(rx.len(), NUM_MESSAGES - received_count);
            assert!(!rx.is_closed());

            // Drop all senders - this should make channel disconnected
            drop(tx);
            drop(tx2);
            drop(tx3);

            // Channel should now be closed
            assert!(rx.is_closed());

            // Should still be able to receive remaining messages
            let mut remaining_received = 0;
            while let Ok(_msg) = rx.try_recv() {
                remaining_received += 1;
            }

            assert_eq!(remaining_received, NUM_MESSAGES - received_count);

            // Now channel should show disconnected
            assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));

            // Drop receiver to clean up remaining messages (if any)
            drop(rx);

            // All messages should be dropped
            assert_eq!(
                drop_counter.load(Ordering::SeqCst),
                NUM_MESSAGES,
                "All messages should be dropped when senders and receiver are dropped"
            );
        }

        // Test Case 2: All senders dropped with empty channel
        {
            let drop_counter = Arc::new(AtomicUsize::new(0));
            const NUM_MESSAGES: usize = 30;

            let (tx, mut rx) = unbounded_channel::<DropTracker>();
            let tx2 = tx.clone();

            // Send and immediately receive all messages
            for i in 0..NUM_MESSAGES {
                let msg = DropTracker {
                    id: i + 100, // Different ID range
                    counter: Arc::clone(&drop_counter),
                };

                if i % 2 == 0 {
                    tx.send(msg).unwrap();
                } else {
                    tx2.send(msg).unwrap();
                }

                // Immediately receive
                let _received = rx.try_recv().unwrap();
            }

            // Channel should be empty but not closed
            assert!(rx.is_empty());
            assert!(!rx.is_closed());
            assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));

            // Drop all senders
            drop(tx);
            drop(tx2);

            // Channel should now be closed and empty
            assert!(rx.is_empty());
            assert!(rx.is_closed());
            assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));

            drop(rx);

            // All messages should be dropped (they were all received and dropped)
            assert_eq!(
                drop_counter.load(Ordering::SeqCst),
                NUM_MESSAGES,
                "All messages should be dropped when received"
            );
        }

        // Test Case 3: Gradual sender drop with weak senders
        {
            let drop_counter = Arc::new(AtomicUsize::new(0));
            const NUM_MESSAGES: usize = 40;

            let (tx, mut rx) = unbounded_channel::<DropTracker>();
            let tx2 = tx.clone();
            let weak_tx = tx.downgrade();

            // Send some messages
            for i in 0..NUM_MESSAGES / 2 {
                let msg = DropTracker {
                    id: i + 200, // Different ID range
                    counter: Arc::clone(&drop_counter),
                };
                tx.send(msg).unwrap();
            }

            // Drop one strong sender
            drop(tx);
            assert!(!rx.is_closed()); // Still have tx2

            // Send more messages with remaining sender
            for i in NUM_MESSAGES / 2..NUM_MESSAGES {
                let msg = DropTracker {
                    id: i + 200,
                    counter: Arc::clone(&drop_counter),
                };
                tx2.send(msg).unwrap();
            }

            // Weak sender should still be able to upgrade
            let upgraded = weak_tx.upgrade();
            assert!(upgraded.is_some());
            drop(upgraded); // Important: drop the upgraded sender

            // Drop last strong sender
            drop(tx2);

            // Receive all messages first
            let mut received_all = 0;
            while let Ok(_msg) = rx.try_recv() {
                received_all += 1;
            }

            assert_eq!(received_all, NUM_MESSAGES);

            // Now channel should show as disconnected and closed
            assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
            assert!(rx.is_closed());

            // Weak sender should no longer be able to upgrade
            assert!(weak_tx.upgrade().is_none());

            drop(rx);
            drop(weak_tx);

            // All messages should be dropped
            assert_eq!(
                drop_counter.load(Ordering::SeqCst),
                NUM_MESSAGES,
                "All messages should be dropped with gradual sender drop"
            );
        }
    }
}