File: threading_test.cpp

package info (click to toggle)
glaze 6.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,312 kB
  • sloc: cpp: 109,539; sh: 99; ansic: 26; makefile: 13
file content (2335 lines) | stat: -rw-r--r-- 75,969 bytes parent folder | download
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
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
// Glaze Library
// For the license information refer to glaze.hpp

#include <cstdint>
#include <random>
#include <thread>

#include "glaze/glaze_exceptions.hpp"
#include "glaze/thread/async_string.hpp"
#include "glaze/thread/async_vector.hpp"
#include "glaze/thread/guard.hpp"
#include "ut/ut.hpp"

using namespace ut;

static_assert(glz::is_atomic<glz::guard<int>>);
static_assert(glz::read_supported<glz::guard<int>, glz::JSON>);
static_assert(glz::read_supported<glz::guard<int>, glz::JSON>);

suite atom_tests = [] {
   "construction"_test = [] {
      glz::guard<int> a;
      expect(a.load() == 0) << "Default constructor should initialize to 0";

      glz::guard<int> b(42);
      expect(b.load() == 42) << "Value constructor should initialize to given value";

      glz::guard<double> c(3.14);
      expect(c.load() == 3.14) << "Should work with floating point types";
   };

   "copy_semantics"_test = [] {
      glz::guard<int> a(42);
      glz::guard<int> b = a;
      expect(b.load() == 42) << "Copy constructor should copy the value";

      glz::guard<int> c(10);
      c = a;
      expect(c.load() == 42) << "Copy assignment should copy the value";

      glz::guard<int> d;
      d = 100;
      expect(d.load() == 100) << "Assignment from T should store the value";
   };

   "move_semantics"_test = [] {
      glz::guard<int> a(42);
      glz::guard<int> b = std::move(a);
      expect(b.load() == 42) << "Move constructor should copy the value";
      expect(a.load() == 42) << "Source should still have its value after move";

      glz::guard<int> c(10);
      c = std::move(a);
      expect(c.load() == 42) << "Move assignment should copy the value";
      expect(a.load() == 42) << "Source should still have its value after move";
   };

   "comparison_with_atom"_test = [] {
      glz::guard<int> a(42);
      glz::guard<int> b(42);
      glz::guard<int> c(100);

      expect(a == b) << "Equal atoms should compare equal";
      expect(a != c) << "Different atoms should not compare equal";
      expect(a < c) << "Less than should work";
      expect(a <= b) << "Less than or equal should work";
      expect(c > a) << "Greater than should work";
      expect(b >= a) << "Greater than or equal should work";
   };

   "comparison_with_value"_test = [] {
      glz::guard<int> a(42);

      expect(a == 42) << "Atom should compare equal with equal value";
      expect(a != 100) << "Atom should not compare equal with different value";
      expect(a < 100) << "Less than should work with value";
      expect(a <= 42) << "Less than or equal should work with value";
      expect(a > 10) << "Greater than should work with value";
      expect(a >= 42) << "Greater than or equal should work with value";

      expect(42 == a) << "Value should compare equal with equal glz::guard";
      expect(100 != a) << "Value should not compare equal with different glz::guard";
      expect(10 < a) << "Less than should work with value on left";
      expect(42 <= a) << "Less than or equal should work with value on left";
      expect(100 > a) << "Greater than should work with value on left";
      expect(42 >= a) << "Greater than or equal should work with value on left";
   };

   "load_store"_test = [] {
      glz::guard<int> a(42);
      expect(a.load() == 42) << "Load should return current value";

      a.store(100);
      expect(a.load() == 100) << "Store should update the value";

      expect(static_cast<int>(a) == 100) << "Conversion operator should return the value";
   };

   "exchange"_test = [] {
      glz::guard<int> a(42);
      int old = a.exchange(100);

      expect(old == 42) << "Exchange should return old value";
      expect(a.load() == 100) << "Exchange should update the value";
   };

   "compare_exchange"_test = [] {
      glz::guard<int> a(42);

      int expected = 42;
      bool success = a.compare_exchange_strong(expected, 100);

      expect(success) << "Compare exchange should succeed when expected matches";
      expect(a.load() == 100) << "Value should be updated on successful exchange";

      expected = 42;
      success = a.compare_exchange_strong(expected, 200);

      expect(!success) << "Compare exchange should fail when expected doesn't match";
      expect(expected == 100) << "Expected should be updated to actual value on failure";
      expect(a.load() == 100) << "Value should not change on failed exchange";
   };

   "arithmetic_operations"_test = [] {
      glz::guard<int> a(42);

      expect(a.fetch_add(10) == 42) << "Fetch add should return old value";
      expect(a.load() == 52) << "Fetch add should update the value";

      expect(a.fetch_sub(20) == 52) << "Fetch sub should return old value";
      expect(a.load() == 32) << "Fetch sub should update the value";

      expect(a += 8) << "Addition assignment should return new value";
      expect(a.load() == 40) << "Addition assignment should update the value";

      expect(a -= 5) << "Subtraction assignment should return new value";
      expect(a.load() == 35) << "Subtraction assignment should update the value";

      expect(++a == 36) << "Pre-increment should return new value";
      expect(a.load() == 36) << "Pre-increment should update the value";

      expect(a++ == 36) << "Post-increment should return old value";
      expect(a.load() == 37) << "Post-increment should update the value";

      expect(--a == 36) << "Pre-decrement should return new value";
      expect(a.load() == 36) << "Pre-decrement should update the value";

      expect(a-- == 36) << "Post-decrement should return old value";
      expect(a.load() == 35) << "Post-decrement should update the value";
   };

   "bitwise_operations"_test = [] {
      glz::guard<int> a(0b1100);

      expect(a.fetch_and(0b1010) == 0b1100) << "Fetch AND should return old value";
      expect(a.load() == 0b1000) << "Fetch AND should update the value";

      expect(a.fetch_or(0b0011) == 0b1000) << "Fetch OR should return old value";
      expect(a.load() == 0b1011) << "Fetch OR should update the value";

      expect(a.fetch_xor(0b1111) == 0b1011) << "Fetch XOR should return old value";
      expect(a.load() == 0b0100) << "Fetch XOR should update the value";

      expect(a &= 0b0110) << "AND assignment should return new value";
      expect(a.load() == 0b0100) << "AND assignment should update the value";

      expect(a |= 0b0011) << "OR assignment should return new value";
      expect(a.load() == 0b0111) << "OR assignment should update the value";

      expect(a ^= 0b0101) << "XOR assignment should return new value";
      expect(a.load() == 0b0010) << "XOR assignment should update the value";
   };

   "thread_safety"_test = []() mutable {
      glz::guard<int> counter(0);

      std::deque<std::thread> threads;
      for (int i = 0; i < 10; ++i) {
         threads.emplace_back([&counter]() {
            for (int j = 0; j < 1000; ++j) {
               counter++;
            }
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      expect(counter.load() == 10000) << "Concurrent increments should result in correct count";
   };

   "complex_type"_test = [] {
      struct Point
      {
         int x = 0;
         int y = 0;
         constexpr auto operator<=>(const Point&) const = default;
      };

      Point p1{1, 2};
      Point p2{1, 2};
      Point p3{3, 4};

      glz::guard<Point> a(p1);
      glz::guard<Point> b(p2);
      glz::guard<Point> c(p3);

      expect(a == b) << "Atoms with structs should compare correctly";
      expect(a != c) << "Atoms with structs should compare correctly";
      expect(a == p1) << "Atom should compare with raw struct value";
   };

   "memory_order"_test = [] {
      glz::guard<int> a(42);

      int v1 = a.load(std::memory_order_relaxed);
      expect(v1 == 42) << "Load with relaxed memory order should work";

      a.store(100, std::memory_order_release);
      int v2 = a.load(std::memory_order_acquire);
      expect(v2 == 100) << "Store with release and load with acquire should work";

      int old = a.exchange(200, std::memory_order_acq_rel);
      expect(old == 100) << "Exchange with acq_rel memory order should work";
      expect(a.load() == 200) << "Value should be updated";
   };

   "json read/write"_test = [] {
      glz::guard<int> a(42);

      std::string buffer{};
      expect(not glz::write_json(a, buffer));
      expect(buffer == "42");

      a = 100;
      expect(not glz::read_json(a, buffer));
      expect(a == 42);
   };
};

suite async_string_tests = [] {
   "async_string default constructor"_test = [] {
      glz::async_string s;
      expect(s.empty());
      expect(s.size() == 0);
      expect(s.length() == 0);
   };

   "async_string param constructors"_test = [] {
      glz::async_string s1("Hello");
      expect(s1.size() == 5) << "s1.size()";
      expect(s1 == "Hello");

      std::string st = "World";
      glz::async_string s2(st);
      expect(s2 == "World");

      std::string_view sv("View me");
      glz::async_string s3(sv);
      expect(s3 == "View me");

      // Move construct
      glz::async_string s4(std::move(s2));
      expect(s4 == "World");
      expect(s2.empty()); // Moved-from string should be empty
   };

   "async_string copy constructor"_test = [] {
      glz::async_string original("Copy me");
      glz::async_string copy(original);
      expect(copy == "Copy me");
      expect(copy == original);
   };

   "async_string move constructor"_test = [] {
      glz::async_string original("Move me");
      glz::async_string moved(std::move(original));
      expect(moved == "Move me");
      expect(original.empty());
   };

   "async_string copy assignment"_test = [] {
      glz::async_string s1("First");
      glz::async_string s2("Second");
      s1 = s2;
      expect(s1 == s2);
      expect(s1 == "Second");
   };

   "async_string move assignment"_test = [] {
      glz::async_string s1("First");
      glz::async_string s2("Second");
      s1 = std::move(s2);
      expect(s1 == "Second");
      expect(s2.empty());
   };

   "async_string assignment from various types"_test = [] {
      glz::async_string s;
      s = "Hello again";
      expect(s == "Hello again");
      expect(s.size() == 11);

      std::string st = "Another test";
      s = st;
      expect(s == "Another test");
      expect(s.size() == 12);

      std::string_view sv("Testing 123");
      s = sv;
      expect(s == "Testing 123");
      expect(s.size() == 11);
   };

   "async_string read/write proxy"_test = [] {
      glz::async_string s("initial");
      {
         auto writer = s.write();
         writer->append(" data");
      }
      expect(s == "initial data");

      {
         auto reader = s.read();
         expect(*reader == "initial data");
         expect(reader->size() == 12);
      }
   };

   "async_string modifiers"_test = [] {
      glz::async_string s("Hello");
      s.push_back('!');
      expect(s == "Hello!");
      expect(s.size() == 6);

      s.pop_back();
      expect(s == "Hello");
      expect(s.size() == 5);

      s.clear();
      expect(s.empty());
      expect(s.size() == 0);
   };

   "async_string append and operator+="_test = [] {
      glz::async_string s("Hello");
      s.append(", ").append("World");
      expect(s == "Hello, World");
      expect(s.size() == 12);

      s += "!!!";
      expect(s == "Hello, World!!!");
      expect(s.size() == 15);

      s += '?';
      expect(s == "Hello, World!!!?");
      expect(s.size() == 16);
   };

   "async_string element access"_test = [] {
      glz::async_string s("Test");
      expect(s.at(0) == 'T');
      expect(s[1] == 'e');
      expect(s.front() == 'T');
      expect(s.back() == 't');

      // Check out_of_range
      expect(throws([&] {
         (void)s.at(10); // out_of_range
      }));
   };

   "async_string compare"_test = [] {
      glz::async_string s1("abc");
      glz::async_string s2("abcd");
      expect(s1.compare(s2) < 0);
      expect(s2.compare(s1) > 0);

      expect(s1 < s2);
      expect(s1 != s2);
      expect(not(s1 == s2));
   };

   "async_string relational ops"_test = [] {
      glz::async_string s1("abc");
      glz::async_string s2("abc");
      expect(s1 == s2);
      expect(not(s1 < s2));
      expect(s1 >= s2);
      expect(s1 <= s2);
   };

   "async_string swap"_test = [] {
      glz::async_string s1("Hello");
      glz::async_string s2("World");
      swap(s1, s2);
      expect(s1 == "World");
      expect(s2 == "Hello");
   };

   // Demonstrate Glaze JSON serialization/deserialization
   "async_string write_json / read_json"_test = [] {
      glz::async_string s("Serialize me!");
      std::string buffer{};

      // write_json returns a status code: false means success, true means error
      expect(not glz::write_json(s, buffer)) << "Failed to serialize async_string.";
      // The JSON for a single string is just a quoted string
      expect(buffer == R"("Serialize me!")") << buffer;

      glz::async_string t;
      expect(not glz::read_json(t, buffer)) << "Failed to deserialize async_string.";
      expect(*t.read() == "Serialize me!");
   };

   // Test an empty string's serialization
   "async_string empty serialization"_test = [] {
      glz::async_string s;
      std::string buffer{};

      expect(not glz::write_json(s, buffer));
      // An empty string in JSON
      expect(buffer == R"("")") << buffer;

      glz::async_string t("placeholder");
      expect(not glz::read_json(t, buffer));
      expect(t.empty());
   };

   "async_string starts_with"_test = [] {
      glz::async_string s("Hello, World!");

      // Positive cases
      expect(s.starts_with("Hello"));
      expect(s.starts_with(std::string("Hello")));
      expect(s.starts_with(std::string_view("Hello")));

      // Negative cases
      expect(not s.starts_with("World"));
      expect(not s.starts_with("hello")); // Case-sensitive
      expect(not s.starts_with("Hello, World! And more"));

      // Edge cases
      glz::async_string empty;
      expect(empty.starts_with("")); // An empty string starts with an empty string
      expect(not empty.starts_with("Non-empty"));

      expect(s.starts_with("")); // Any string starts with an empty string
   };

   "async_string ends_with"_test = [] {
      glz::async_string s("Hello, World!");

      // Positive cases
      expect(s.ends_with("World!"));
      expect(s.ends_with(std::string("World!")));
      expect(s.ends_with(std::string_view("World!")));

      // Negative cases
      expect(not s.ends_with("Hello"));
      expect(not s.ends_with("world!")); // Case-sensitive
      expect(not s.ends_with("...World!"));

      // Edge cases
      glz::async_string empty;
      expect(empty.ends_with("")); // An empty string ends with an empty string
      expect(not empty.ends_with("Non-empty"));

      expect(s.ends_with("")); // Any string ends with an empty string
   };

   "async_string substr"_test = [] {
      glz::async_string s("Hello, World!");

      // Basic substrings
      auto sub1 = s.substr(0, 5);
      expect(sub1 == "Hello");
      expect(sub1.size() == 5);

      auto sub2 = s.substr(7, 5);
      expect(sub2 == "World");
      expect(sub2.size() == 5);

      // Substring to the end
      auto sub3 = s.substr(7);
      expect(sub3 == "World!");
      expect(sub3.size() == 6);

      // Full string
      auto sub4 = s.substr(0, s.size());
      expect(sub4 == s);

      // Empty substring
      auto sub5 = s.substr(5, 0);
      expect(sub5.empty());
      expect(sub5.size() == 0);

      // Edge cases
      glz::async_string empty;
      auto sub_empty = empty.substr(0, 1);
      expect(sub_empty.empty());

      // Out of range positions
      expect(throws([&] {
         s.substr(100, 5); // Start position out of range
      }));

      expect(not throws([&] { s.substr(5, 100); }));

      // Start position at the end of the string
      auto sub_end = s.substr(s.size(), 0);
      expect(sub_end.empty());

      // Start position just before the end
      auto sub_last = s.substr(s.size() - 1, 1);
      expect(sub_last == "!");
      expect(sub_last.size() == 1);
   };

#ifdef __cpp_lib_format
   "async_string std::format single argument"_test = [] {
      glz::async_string name("Alice");
      std::string formatted = std::format("Hello, {}!", name);
      expect(formatted == "Hello, Alice!");
   };

   "async_string std::format multiple arguments"_test = [] {
      glz::async_string name("Bob");
      glz::async_string city("New York");
      std::string formatted = std::format("{} is from {}.", name, city);
      expect(formatted == "Bob is from New York.");
   };

   "async_string std::format with empty strings"_test = [] {
      glz::async_string empty{};

      // Formatting with an empty glz::async_string as an argument
      std::string formatted_empty_arg = std::format("Hello, {}!", empty);
      expect(formatted_empty_arg == "Hello, !");
   };

   "async_string std::format numeric and other types"_test = [] {
      glz::async_string name("Diana");
      int age = 30;
      double height = 5.6;

      std::string formatted = std::format("{} is {} years old and {} feet tall.", name, age, height);
      expect(formatted == "Diana is 30 years old and 5.6 feet tall.");
   };
#endif

   "async_string concurrent reads"_test = [] {
      std::string long_string(1024, 'A');
      glz::async_string s(long_string);
      std::vector<std::thread> threads;
      std::mutex mutex;
      std::vector<std::string> results(10);

      for (int i = 0; i < 10; ++i) {
         threads.emplace_back([&, i]() {
            auto reader = s.read();
            std::lock_guard<std::mutex> lock(mutex);
            results[i] = *reader;
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      for (const auto& result : results) {
         expect(result == long_string);
      }
   };

   "async_string concurrent writes with single char"_test = [] {
      glz::async_string s;
      std::vector<std::thread> threads;
      int num_threads = 10;
      std::string expected_result;
      for (int i = 0; i < num_threads; ++i) {
         expected_result += std::string(256, char('a' + i));
      }
      std::string sorted_expected_result = expected_result;
      std::sort(sorted_expected_result.begin(), sorted_expected_result.end());

      for (int i = 0; i < num_threads; ++i) {
         threads.emplace_back([&, char_to_append = char('a' + i)]() {
            for (int j = 0; j < 256; ++j) {
               s.push_back(char_to_append);
            }
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      std::string actual_result = *s.read();
      std::string sorted_actual_result = actual_result;
      std::sort(sorted_actual_result.begin(), sorted_actual_result.end());
      expect(sorted_actual_result == sorted_expected_result);
   };

   "async_string concurrent writes with append"_test = [] {
      glz::async_string s;
      std::vector<std::thread> threads;
      int num_threads = 10;
      std::vector<std::string> to_append;
      std::string expected_result;
      for (int i = 0; i < num_threads; ++i) {
         std::string append_str(512, '0' + i);
         to_append.push_back(append_str);
         expected_result += append_str;
      }
      std::sort(expected_result.begin(), expected_result.end());

      for (int i = 0; i < num_threads; ++i) {
         threads.emplace_back([&, str_to_append = to_append[i]]() { s.append(str_to_append); });
      }

      for (auto& t : threads) {
         t.join();
      }

      std::string actual_result = *s.read();
      std::sort(actual_result.begin(), actual_result.end());
      expect(actual_result == expected_result);
   };

   "async_string concurrent reads and writes"_test = [] {
      std::string initial_string(512, 'I');
      glz::async_string s(initial_string);
      std::vector<std::thread> threads;
      int num_threads = 10;
      std::string expected_final_string = initial_string;
      std::vector<std::string> appends;
      for (int i = 0; i < num_threads; ++i) {
         std::string append_str(256, '0' + i);
         appends.push_back(append_str);
         expected_final_string += append_str;
      }
      std::string sorted_appends_expected;
      for (size_t i = initial_string.length(); i < expected_final_string.length(); ++i) {
         sorted_appends_expected += expected_final_string[i];
      }
      std::sort(sorted_appends_expected.begin(), sorted_appends_expected.end());
      expected_final_string = initial_string + sorted_appends_expected;

      for (int i = 0; i < num_threads; ++i) {
         threads.emplace_back([&, id = i]() {
            // Writer thread
            if (id == 0) {
               s.append(appends[id]);
            }
            else {
               // Reader threads
               // Just access the data, the important part is no crashes
               (void)s.size();
            }
         });
      }
      for (int i = 1; i < num_threads; ++i) {
         threads.emplace_back([&, id = i]() {
            // Writer threads (after the initial writer)
            s.append(appends[id]);
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      std::string actual_result = *s.read();
      std::string sorted_appends_actual = actual_result.substr(initial_string.length());
      std::sort(sorted_appends_actual.begin(), sorted_appends_actual.end());
      expect(initial_string + sorted_appends_actual == expected_final_string);
   };

   "async_string multiple concurrent write proxies"_test = [] {
      glz::async_string s;
      std::vector<std::thread> threads;
      int num_threads = 5;
      std::string expected_append;
      std::vector<std::string> to_append;
      for (int i = 0; i < num_threads; ++i) {
         std::string append_str(512, '0' + i);
         to_append.push_back(append_str);
         expected_append += append_str;
      }
      std::sort(expected_append.begin(), expected_append.end());

      for (int i = 0; i < num_threads; ++i) {
         threads.emplace_back([&, str_to_append = to_append[i]]() {
            auto writer = s.write();
            writer->append(str_to_append);
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      std::string actual_result = *s.read();
      std::sort(actual_result.begin(), actual_result.end());
      expect(actual_result == expected_append);
   };

   "async_string concurrent read and modify"_test = [] {
      std::string initial_value(1024, 'X');
      glz::async_string s(initial_value);
      std::vector<std::thread> threads;
      int num_threads = 10;
      std::mutex m;
      std::vector<std::string> observed_values;

      for (int i = 0; i < num_threads; ++i) {
         threads.emplace_back([&, id = i]() {
            if (id % 2 == 0) {
               // Reader thread
               auto reader = s.read();
               {
                  std::lock_guard<std::mutex> lock(m);
                  observed_values.push_back(*reader);
               }
            }
            else {
               // Modifier thread
               auto writer = s.write();
               for (int j = 0; j < 128; ++j) {
                  *writer += "a";
               }
            }
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      // It's hard to predict the exact sequence of observed values, but we can check for consistency.
      // All observed values should at least start with the initial value.
      for (const auto& val : observed_values) {
         expect(val.rfind(initial_value, 0) == 0);
      }

      // The final string should have been modified by the modifier threads.
      expect(*s.read().operator->() != initial_value);
      expect(s.read()->length() > initial_value.length());
   };

   // Tests for proxy size/capacity methods
   "proxy size and capacity methods"_test = [] {
      glz::async_string s("Hello, world!");
      auto p = s.write();

      expect(p.size() == 13);
      expect(p.length() == 13);
      expect(p.max_size() > 0);
      expect(p.capacity() >= p.size());
      expect(!p.empty());

      p.reserve(100);
      expect(p.capacity() >= 100);

      p.shrink_to_fit();
      expect(p.capacity() >= p.size());

      glz::async_string empty_str;
      auto empty_p = empty_str.write();
      expect(empty_p.empty());
      expect(empty_p.size() == 0);
   };

   // Tests for proxy element access methods
   "proxy element access methods"_test = [] {
      glz::async_string s("Test string");
      auto p = s.write();

      expect(p[0] == 'T');
      expect(p.at(1) == 'e');
      expect(p.front() == 'T');
      expect(p.back() == 'g');

      // data() and c_str() should return valid pointers
      expect(p.data() != nullptr);
      expect(p.c_str() != nullptr);

      // Content should match
      expect(std::string(p.data()) == "Test string");
      expect(std::string(p.c_str()) == "Test string");

      // Null termination for c_str()
      expect(p.c_str()[p.size()] == '\0');

      // Check out_of_range for at()
      expect(throws([&] { (void)p.at(100); }));

      // Modifying through operator[]
      p[0] = 'B';
      expect(p[0] == 'B');
      expect(*p == "Best string");
   };

   // Tests for proxy string operations
   "proxy string operations"_test = [] {
      glz::async_string s("Hello, world!");
      auto p = s.write();

      // compare
      expect(p.compare("Hello, world!") == 0);
      expect(p.compare("Hello") > 0);
      expect(p.compare("Zebra") < 0);
      expect(p.compare(std::string("Hello, world!")) == 0);
      expect(p.compare(std::string_view("Hello, world!")) == 0);
      expect(p.compare(0, 5, std::string("Hello")) == 0);

      // substr
      expect(p.substr(0, 5) == "Hello");
      expect(p.substr(7, 5) == "world");
      expect(p.substr(7) == "world!");

      // starts_with
      expect(p.starts_with("Hello"));
      expect(p.starts_with(std::string_view("Hello")));
      expect(p.starts_with('H'));
      expect(!p.starts_with("hello")); // case sensitive

      // ends_with
      expect(p.ends_with("world!"));
      expect(p.ends_with(std::string_view("world!")));
      expect(p.ends_with('!'));
      expect(!p.ends_with("World!")); // case sensitive
   };

   // Tests for proxy search operations
   "proxy search operations"_test = [] {
      glz::async_string s("Hello, world! Hello again!");
      auto p = s.write();

      // find
      expect(p.find("world") == 7);
      expect(p.find('w') == 7);
      expect(p.find("notfound") == std::string::npos);
      expect(p.find("Hello", 1) == 14);
      expect(p.find(std::string("world")) == 7);
      expect(p.find(std::string_view("world")) == 7);
      expect(p.find("o", 0, 1) == 4);

      // rfind
      expect(p.rfind("Hello") == 14);
      expect(p.rfind('!') == 25);
      expect(p.rfind("notfound") == std::string::npos);
      expect(p.rfind(std::string("Hello")) == 14);
      expect(p.rfind(std::string_view("Hello")) == 14);

      // find_first_of
      expect(p.find_first_of("aeiou") == 1); // 'e' in "Hello"
      expect(p.find_first_of('e') == 1);
      expect(p.find_first_of("xyz") == std::string::npos);
      expect(p.find_first_of(std::string("aeiou")) == 1);
      expect(p.find_first_of(std::string_view("aeiou")) == 1);
      expect(p.find_first_of("aeiou", 5) == 8); // 'o' in "world"

      // find_last_of
      expect(p.find_last_of("aeiou") == 23); // 'i' in "again"
      expect(p.find_last_of('n') == 24);
      expect(p.find_last_of("xyz") == std::string::npos);

      // find_first_not_of
      expect(p.find_first_not_of("Helo") == 5); // ',' after "Hello"
      expect(p.find_first_not_of('H') == 1);

      // find_last_not_of
      expect(p.find_last_not_of("!") == 24); // 'n' before final '!'
      expect(p.find_last_not_of(" !") == 24); // 'n' before final '!'
   };

   // Tests for proxy modifiers
   "proxy advanced modifiers"_test = [] {
      glz::async_string s("Hello, world!");

      // Testing clear
      {
         auto p = s.write();
         p.clear();
         expect(p.empty());
         expect(p.size() == 0);
      }

      // Testing resize
      {
         s = "Resize me";
         auto p = s.write();

         // Shrink
         p.resize(7);
         expect(*p == "Resize ");
         expect(p.size() == 7);

         // Expand with default char
         p.resize(10);
         expect(p.size() == 10);
         expect(p[7] == '\0');

         // Expand with specified char
         p.resize(15, '!');
         expect(p.size() == 15);
         expect(p[10] == '!');
         expect(p[14] == '!');
      }

      // Testing push_back and pop_back
      {
         s = "Test";
         auto p = s.write();

         p.push_back('!');
         expect(*p == "Test!");

         p.pop_back();
         expect(*p == "Test");

         // Multiple operations
         p.push_back('1');
         p.push_back('2');
         p.push_back('3');
         expect(*p == "Test123");

         p.pop_back();
         p.pop_back();
         expect(*p == "Test1");
      }

      // Testing append and operator+=
      {
         s = "Hello";
         auto p = s.write();

         p.append(", ");
         expect(*p == "Hello, ");

         p.append(std::string("world"));
         expect(*p == "Hello, world");

         p.append(std::string_view("!"));
         expect(*p == "Hello, world!");

         p.append(" How", 4);
         expect(*p == "Hello, world! How");

         p.append(3, '!');
         expect(*p == "Hello, world! How!!!");

         // Testing operator+=
         p += " Testing";
         expect(*p == "Hello, world! How!!! Testing");

         p += std::string(" operator");
         expect(*p == "Hello, world! How!!! Testing operator");

         p += std::string_view(" +=");
         expect(*p == "Hello, world! How!!! Testing operator +=");

         p += '!';
         expect(*p == "Hello, world! How!!! Testing operator +=!");
      }

      // Testing swap
      {
         s = "First string";
         std::string other = "Second string";
         auto p = s.write();

         p.swap(other);
         expect(*p == "Second string");
         expect(other == "First string");
      }
   };

   // Tests for const_proxy methods
   "const_proxy methods"_test = [] {
      const glz::async_string s("This is a const test string!");
      auto cp = s.read();

      // Size/capacity
      expect(cp.size() == 28);
      expect(cp.length() == 28);
      expect(cp.max_size() > 0);
      expect(cp.capacity() >= cp.size());
      expect(!cp.empty());

      // Element access
      expect(cp[0] == 'T');
      expect(cp.at(1) == 'h');
      expect(cp.front() == 'T');
      expect(cp.back() == '!');
      expect(std::string(cp.data()) == "This is a const test string!");
      expect(std::string(cp.c_str()) == "This is a const test string!");

      // String operations
      expect(cp.compare("This is a const test string!") == 0);
      expect(cp.compare("This") > 0);
      expect(cp.compare("Zebra") < 0);
      expect(cp.compare(std::string("This is a const test string!")) == 0);
      expect(cp.compare(std::string_view("This is a const test string!")) == 0);

      expect(cp.substr(0, 4) == "This");
      expect(cp.substr(10, 5) == "const");
      expect(cp.substr(10) == "const test string!");

      expect(cp.starts_with("This"));
      expect(cp.starts_with('T'));
      expect(cp.starts_with(std::string_view("This")));
      expect(!cp.starts_with("this")); // case sensitive

      expect(cp.ends_with("string!"));
      expect(cp.ends_with('!'));
      expect(cp.ends_with(std::string_view("string!")));
      expect(!cp.ends_with("String!")); // case sensitive

      // Search operations
      expect(cp.find("const") == 10);
      expect(cp.find('c') == 10);
      expect(cp.find("notfound") == std::string::npos);
      expect(cp.find(std::string("test")) == 16);
      expect(cp.find(std::string_view("string")) == 21);

      expect(cp.rfind("is") == 5);
      expect(cp.rfind('s') == 21);

      // Testing operator conversions and dereference
      std::string_view sv = cp;
      expect(sv == "This is a const test string!");

      const std::string& ref = *cp;
      expect(ref == "This is a const test string!");

      const std::string* ptr = cp.operator->();
      expect(*ptr == "This is a const test string!");

      // Test .value() method still works
      expect(cp.value() == "This is a const test string!");
   };

   // Test proxy chain operations (ensuring method chaining works)
   "proxy method chaining"_test = [] {
      glz::async_string s("Start");

      // Chain several operations
      auto p = s.write();
      p.append(" ").append("with").append(" chaining").replace(0, 5, "Begin");
      expect(*p == "Begin with chaining");
   };
};

struct TestObject
{
   int id = 0;
   std::string name = "default";

   TestObject() = default;
   TestObject(int id, std::string name) : id(id), name(std::move(name)) {}

   bool operator==(const TestObject& other) const { return id == other.id && name == other.name; }
};

suite async_vector_tests = [] {
   "construction"_test = [] {
      glz::async_vector<int> vec;
      expect(vec.size() == 0) << "Default constructor should create empty vector";
      expect(vec.empty()) << "Default constructed vector should be empty";

      // Initialize with elements
      glz::async_vector<int> vec_with_size;
      vec_with_size.resize(5, 42);
      expect(vec_with_size.size() == 5) << "Size should match requested size";
      for (size_t i = 0; i < vec_with_size.size(); ++i) {
         expect(vec_with_size.read()[i] == 42) << "All elements should be initialized with the provided value";
      }
   };

   "copy_semantics"_test = [] {
      glz::async_vector<int> original;
      original.push_back(1);
      original.push_back(2);
      original.push_back(3);

      // Test copy constructor
      glz::async_vector<int> copy_constructed = original;
      expect(copy_constructed.size() == original.size()) << "Copy constructed vector should have same size";
      for (size_t i = 0; i < original.size(); ++i) {
         expect(copy_constructed.read()[i] == original.read()[i]) << "Elements should match after copy construction";
      }

      // Modify original to verify deep copy
      original.push_back(4);
      expect(copy_constructed.size() == 3) << "Copy should not be affected by changes to original";

      // Test copy assignment
      glz::async_vector<int> copy_assigned;
      copy_assigned = original;
      expect(copy_assigned.size() == original.size()) << "Copy assigned vector should have same size";
      for (size_t i = 0; i < original.size(); ++i) {
         expect(copy_assigned.read()[i] == original.read()[i]) << "Elements should match after copy assignment";
      }

      // Modify original again to verify deep copy
      original.write()[0] = 99;
      expect(copy_assigned.read()[0] == 1) << "Copy should not be affected by changes to original values";
   };

   "move_semantics"_test = [] {
      glz::async_vector<int> original;
      original.push_back(1);
      original.push_back(2);
      original.push_back(3);

      // Test move constructor
      glz::async_vector<int> move_constructed = std::move(original);
      expect(move_constructed.size() == 3) << "Move constructed vector should have original size";
      expect(move_constructed.read()[0] == 1) << "Elements should be moved correctly";
      expect(move_constructed.read()[1] == 2) << "Elements should be moved correctly";
      expect(move_constructed.read()[2] == 3) << "Elements should be moved correctly";

      // Test move assignment
      glz::async_vector<int> move_assigned;
      move_assigned = std::move(move_constructed);
      expect(move_assigned.size() == 3) << "Move assigned vector should have original size";
      expect(move_assigned.read()[0] == 1) << "Elements should be moved correctly";
      expect(move_assigned.read()[1] == 2) << "Elements should be moved correctly";
      expect(move_assigned.read()[2] == 3) << "Elements should be moved correctly";
   };

   "compare"_test = [] {
      glz::async_vector<int> v1;
      v1.push_back(10);
      v1.push_back(20);
      v1.push_back(30);
      glz::async_vector v2 = v1;

      expect(v1 == v2);

      std::vector<int> std_vec = {10, 20, 30};
      expect(v1 == std_vec);
   };

   "element_access"_test = [] {
      glz::async_vector<int> vec;
      vec.push_back(10);
      vec.push_back(20);
      vec.push_back(30);

      // Test operator[]
      expect(vec.read()[0] == 10) << "Operator[] should return correct element";
      expect(vec.read()[1] == 20) << "Operator[] should return correct element";
      expect(vec.read()[2] == 30) << "Operator[] should return correct element";

      // Test at()
      expect(vec.read().at(0) == 10) << "at() should return correct element";
      expect(vec.read().at(1) == 20) << "at() should return correct element";
      expect(vec.read().at(2) == 30) << "at() should return correct element";

      // Test front() and back()
      expect(vec.read().front() == 10) << "front() should return first element";
      expect(vec.read().back() == 30) << "back() should return last element";

      // Test out of bounds with at()
      bool exception_thrown = false;
      try {
         vec.read().at(5);
      }
      catch (const std::out_of_range&) {
         exception_thrown = true;
      }
      expect(exception_thrown) << "at() should throw std::out_of_range for out of bounds access";

      // Test modification through element access
      vec.write()[1] = 25;
      expect(vec.read()[1] == 25) << "Element should be modifiable through operator[]";

      vec.write().at(2) = 35;
      expect(vec.read()[2] == 35) << "Element should be modifiable through at()";
   };

   "capacity"_test = [] {
      glz::async_vector<int> vec;
      expect(vec.empty()) << "New vector should be empty";

      vec.push_back(1);
      expect(!vec.empty()) << "Vector with elements should not be empty";
      expect(vec.size() == 1) << "Size should reflect number of elements";

      vec.reserve(10);
      expect(vec.capacity() >= 10) << "Capacity should be at least the reserved amount";
      expect(vec.size() == 1) << "Reserve should not change size";

      vec.resize(5);
      expect(vec.size() == 5) << "Resize should change size";

      vec.resize(3);
      expect(vec.size() == 3) << "Resize to smaller should reduce size";

      size_t cap_before = vec.capacity();
      vec.write().shrink_to_fit();
      expect(vec.capacity() <= cap_before) << "Shrink to fit should not increase capacity";
   };

   "modifiers"_test = [] {
      glz::async_vector<int> vec;

      // Test push_back
      vec.push_back(1);
      vec.push_back(2);
      expect(vec.size() == 2) << "Size should increase after push_back";
      expect(vec.read()[0] == 1 && vec.read()[1] == 2) << "Elements should be in correct order";

      // Test emplace_back
      vec.emplace_back(3);
      expect(vec.size() == 3) << "Size should increase after emplace_back";
      expect(vec.read()[2] == 3) << "Element should be constructed in place";

      // Test pop_back
      vec.pop_back();
      expect(vec.size() == 2) << "Size should decrease after pop_back";
      expect(vec.read()[1] == 2) << "Last element should be removed";

      // Test insert
      {
         auto proxy = vec.write();
         auto it = proxy.insert(proxy.begin(), 0);
         expect(*it == 0) << "Insert should return iterator to inserted element";
      }
      expect(vec.size() == 3) << "Size should increase after insert";
      expect(vec.read()[0] == 0 && vec.read()[1] == 1 && vec.read()[2] == 2)
         << "Elements should be in correct order after insert";

      // Test emplace
      {
         auto proxy = vec.write();
         auto it2 = proxy.emplace(proxy.begin() + 2, 15);
         expect(*it2 == 15) << "Emplace should return iterator to inserted element";
      }
      expect(vec.size() == 4) << "Size should increase after emplace";
      expect(vec.read()[0] == 0 && vec.read()[1] == 1 && vec.read()[2] == 15 && vec.read()[3] == 2)
         << "Elements should be in correct order after emplace";

      // Test erase
      {
         auto proxy = vec.write();
         auto it3 = proxy.erase(proxy.begin() + 1);
         expect(*it3 == 15) << "Erase should return iterator to element after erased";
      }
      expect(vec.size() == 3) << "Size should decrease after erase";
      expect(vec.read()[0] == 0 && vec.read()[1] == 15 && vec.read()[2] == 2)
         << "Elements should be in correct order after erase";

      // Test clear
      vec.clear();
      expect(vec.empty()) << "Vector should be empty after clear";
   };

   "iterators"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 5; ++i) {
         vec.push_back(i);
      }

      // Test iterator traversal
      int sum = 0;
      {
         auto proxy = vec.read();
         for (auto it = proxy.begin(); it != proxy.end(); ++it) {
            sum += *it;
         }
      }
      expect(sum == 10) << "Iterator traversal should access all elements";

      // Test const_iterator traversal
      const glz::async_vector<int>& const_vec = vec;
      sum = 0;
      {
         auto proxy = const_vec.read();
         for (auto it = proxy.begin(); it != proxy.end(); ++it) {
            sum += *it;
         }
      }
      expect(sum == 10) << "Const iterator traversal should access all elements";

      // Test iterator modification
      {
         auto proxy = vec.write();
         for (auto it = proxy.begin(); it != proxy.end(); ++it) {
            *it *= 2;
         }
      }
      expect(vec.read()[0] == 0 && vec.read()[1] == 2 && vec.read()[2] == 4 && vec.read()[3] == 6 && vec.read()[4] == 8)
         << "Elements should be modifiable through iterators";

      // Test range-based for loop
      sum = 0;
      for (const auto& val : vec.read()) {
         sum += val;
      }
      expect(sum == 20) << "Range-based for loop should access all elements";
   };

   "complex_types"_test = [] {
      glz::async_vector<TestObject> vec;

      vec.emplace_back(1, "one");
      vec.emplace_back(2, "two");
      vec.emplace_back(3, "three");

      expect(vec.size() == 3) << "Size should reflect number of complex objects";
      expect(vec.read()[0].id == 1 && vec.read()[0].name == "one") << "Complex object should be stored correctly";
      expect(vec.read()[1].id == 2 && vec.read()[1].name == "two") << "Complex object should be stored correctly";
      expect(vec.read()[2].id == 3 && vec.read()[2].name == "three") << "Complex object should be stored correctly";

      // Test copying of complex types
      glz::async_vector<TestObject> vec_copy = vec;
      vec.write()[0].id = 10;
      vec.write()[0].name = "modified";

      expect(vec_copy.read()[0].id == 1 && vec_copy.read()[0].name == "one")
         << "Copied vector should not be affected by changes to original";
   };

   "swap"_test = [] {
      glz::async_vector<int> vec1;
      vec1.push_back(1);
      vec1.push_back(2);

      glz::async_vector<int> vec2;
      vec2.push_back(3);
      vec2.push_back(4);
      vec2.push_back(5);

      vec1.swap(vec2);

      expect(vec1.size() == 3) << "First vector should have size of second vector after swap";
      expect(vec2.size() == 2) << "Second vector should have size of first vector after swap";

      expect(vec1.read()[0] == 3 && vec1.read()[1] == 4 && vec1.read()[2] == 5)
         << "First vector should have elements of second vector";
      expect(vec2.read()[0] == 1 && vec2.read()[1] == 2) << "Second vector should have elements of first vector";
   };

   "thread_safety_read"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 100; ++i) {
         vec.push_back(i);
      }

      std::deque<std::thread> threads;
      std::vector<int> sums(10, 0);

      // Create multiple threads that read from the vector
      for (int i = 0; i < 10; ++i) {
         threads.emplace_back([&vec, &sums, i]() {
            for (int j = 0; j < 100; ++j) {
               sums[i] += vec.read()[j];
            }
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      // All threads should have computed the same sum
      for (const auto& sum : sums) {
         expect(sum == 4950) << "All threads should read the same values";
      }
   };

   "thread_safety_write"_test = [] {
      glz::async_vector<int> vec;

      std::deque<std::thread> threads;

      // Create multiple threads that write to the vector
      for (int i = 0; i < 10; ++i) {
         threads.emplace_back([&vec, i]() {
            for (int j = 0; j < 100; ++j) {
               vec.push_back(i * 100 + j);
            }
         });
      }

      for (auto& t : threads) {
         t.join();
      }

      expect(vec.size() == 1000) << "Vector should contain all elements from all threads";

      // Verify that all expected values are in the vector
      std::vector<int> expected_values;
      for (int i = 0; i < 10; ++i) {
         for (int j = 0; j < 100; ++j) {
            expected_values.push_back(i * 100 + j);
         }
      }

      std::vector<int> actual_values;
      for (size_t i = 0; i < vec.size(); ++i) {
         actual_values.push_back(vec.read()[i]);
      }

      std::sort(actual_values.begin(), actual_values.end());
      std::sort(expected_values.begin(), expected_values.end());

      expect(actual_values == expected_values) << "Vector should contain all expected values";
   };

   "thread_safety_mixed"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 100; ++i) {
         vec.push_back(i);
      }

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;

      // Reader threads
      std::atomic<size_t> sum = 0;
      for (int i = 0; i < 5; ++i) {
         threads.emplace_back([&vec, &stop, &sum]() {
            while (!stop) {
               for (size_t j = 0; j < vec.size(); ++j) {
                  sum += vec.read()[j];
               }
            }
         });
      }

      // Writer threads
      for (int i = 0; i < 5; ++i) {
         threads.emplace_back([&vec, &stop, i]() {
            for (int j = 0; j < 100 && !stop; ++j) {
               vec.push_back(i * 100 + j);
               std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
         });
      }

      // Let the threads run for a short time
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }

      // We can't check exact values due to the concurrent nature, but we should have more than we started with
      expect(vec.size() > 100) << "Vector should have grown during concurrent operations";
   };
};

// Additional stress tests and edge cases for async_vector

// Complex data type with move/copy semantics verification
struct ComplexObject
{
   int id;
   std::string data;
   std::vector<double> values;
   std::unique_ptr<int> ptr;
   bool was_moved = false;
   std::atomic<int> access_count{0};

   ComplexObject(int id, std::string data, std::vector<double> values)
      : id(id), data(std::move(data)), values(std::move(values)), ptr(std::make_unique<int>(id))
   {}

   ComplexObject() : id(0), ptr(std::make_unique<int>(0)) {}

   // Copy constructor
   ComplexObject(const ComplexObject& other)
      : id(other.id),
        data(other.data),
        values(other.values),
        ptr(other.ptr ? std::make_unique<int>(*other.ptr) : nullptr),
        access_count(other.access_count.load())
   {}

   // Move constructor
   ComplexObject(ComplexObject&& other) noexcept
      : id(other.id),
        data(std::move(other.data)),
        values(std::move(other.values)),
        ptr(std::move(other.ptr)),
        was_moved(true),
        access_count(other.access_count.load())
   {}

   // Copy assignment
   ComplexObject& operator=(const ComplexObject& other)
   {
      if (this != &other) {
         id = other.id;
         data = other.data;
         values = other.values;
         ptr = other.ptr ? std::make_unique<int>(*other.ptr) : nullptr;
         access_count.store(other.access_count.load());
      }
      return *this;
   }

   // Move assignment
   ComplexObject& operator=(ComplexObject&& other) noexcept
   {
      if (this != &other) {
         id = other.id;
         data = std::move(other.data);
         values = std::move(other.values);
         ptr = std::move(other.ptr);
         was_moved = true;
         access_count.store(other.access_count.load());
      }
      return *this;
   }

   void access() { access_count++; }

   bool operator==(const ComplexObject& other) const
   {
      return id == other.id && data == other.data && values == other.values &&
             ((!ptr && !other.ptr) || (ptr && other.ptr && *ptr == *other.ptr));
   }
};

suite additional_async_vector_tests = [] {
   "concurrent_iterator_stress"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 1000; ++i) {
         vec.push_back(i);
      }

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<int> errors{0};

      // Thread that continually creates and destroys iterators
      threads.emplace_back([&]() {
         while (!stop) {
            auto proxy = vec.read();
            auto it1 = proxy.begin();
            [[maybe_unused]] auto it2 = proxy.begin();
            auto it3 = proxy.end();
            [[maybe_unused]] auto it4 = proxy.cbegin();
            [[maybe_unused]] auto it5 = proxy.cend();

            // Test iterator arithmetic and comparisons
            try {
               auto it_mid = it1 + proxy.size() / 2;
               if (!(it_mid > it1 && it_mid < it3)) {
                  errors++;
               }

               auto it_adv = it1;
               it_adv += 10;
               if (it_adv - it1 != 10) {
                  errors++;
               }

               // Create iterator and then immediately discard
               for (int i = 0; i < 50; ++i) {
                  [[maybe_unused]] auto temp_it = proxy.begin() + i;
                  [[maybe_unused]] auto temp_cit = proxy.cbegin() + i;
               }
            }
            catch (const std::exception&) {
               errors++;
            }
         }
      });

      // Thread that reads through iterators
      threads.emplace_back([&]() {
         while (!stop) {
            try {
               int64_t sum = 0; // use wider type to avoid overflow on fast machines
               {
                  auto proxy = vec.read();
                  for (auto it = proxy.begin(); it != proxy.end(); ++it) {
                     sum += static_cast<int64_t>(*it);
                  }
               }

               // Basic validation check
               if (sum < 0) {
                  errors++;
               }
            }
            catch (const std::exception&) {
               errors++;
            }
         }
      });

      // Thread that modifies through iterators
      threads.emplace_back([&]() {
         int counter = 0;
         while (!stop) {
            try {
               auto proxy = vec.write();
               auto it = proxy.begin() + (counter % proxy.size());
               *it = counter;
               counter++;
            }
            catch (const std::exception&) {
               errors++;
            }
         }
      });

      // Run for a short time
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }

      expect(errors == 0) << "Iterator operations should not produce errors";
   };

   "concurrent_insert_erase"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 100; ++i) {
         vec.push_back(i);
      }

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<int> errors{0};

      // Multiple threads inserting and erasing concurrently
      for (int t = 0; t < 5; ++t) {
         threads.emplace_back([&, t]() {
            for (int i = 0; i < 100 && !stop; ++i) {
               try {
                  // Pick a random position
                  thread_local std::mt19937 rng(std::random_device{}());
                  size_t upper = vec.size();
                  std::uniform_int_distribution<size_t> pos_dist(0, upper);
                  size_t pos = pos_dist(rng);
                  {
                     auto proxy = vec.write();
                     auto insert_pos = proxy.begin();
                     std::advance(insert_pos, (std::min)(pos, proxy.size()));

                     // Insert a new value
                     auto it = proxy.insert(insert_pos, t * 1000 + i);

                     // Verify the inserted value
                     if (*it != t * 1000 + i) {
                        errors++;
                     }
                  }

                  // Small delay to increase chance of contention
                  std::uniform_int_distribution<int> us_dist(0, 99);
                  std::this_thread::sleep_for(std::chrono::microseconds(us_dist(rng)));

                  // Pick another random position for erasure
                  if (vec.size() > 0) {
                     size_t cur = vec.size();
                     std::uniform_int_distribution<size_t> erase_dist(0, cur - 1);
                     size_t erase_pos = erase_dist(rng);
                     auto proxy = vec.write();
                     auto erase_iter = proxy.begin();
                     std::advance(erase_iter, erase_pos);
                     proxy.erase(erase_iter);
                  }
               }
               catch (const std::exception&) {
                  errors++;
               }
            }
         });
      }

      // Run for a short time
      std::this_thread::sleep_for(std::chrono::milliseconds(500));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }

      expect(errors == 0) << "Concurrent insert/erase operations should not produce errors";
   };

   "emplace_stress"_test = [] {
      glz::async_vector<ComplexObject> vec;

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<int> errors{0};

      // Multiple threads using emplace concurrently
      for (int t = 0; t < 5; ++t) {
         threads.emplace_back([&, t]() {
            for (int i = 0; i < 100 && !stop; ++i) {
               try {
                  // Pick a random position
                  thread_local std::mt19937 rng(std::random_device{}());
                  size_t upper = vec.size();
                  std::uniform_int_distribution<size_t> pos_dist(0, upper);
                  size_t pos = pos_dist(rng);
                  {
                     auto proxy = vec.write();
                     auto insert_pos = proxy.begin();
                     std::advance(insert_pos, (std::min)(pos, proxy.size()));

                     // Create a string and vector for the complex object
                     std::string data = "Thread " + std::to_string(t) + " Item " + std::to_string(i);
                     std::vector<double> values;
                     for (int j = 0; j < 5; ++j) {
                        values.push_back(t + i + j / 10.0);
                     }

                     // Emplace a new complex object
                     auto it = proxy.emplace(insert_pos, t * 1000 + i, data, values);

                     // Verify the emplaced object
                     if (it->id != t * 1000 + i || it->data != data) {
                        errors++;
                     }
                  }

                  // Small delay to increase chance of contention
                  std::uniform_int_distribution<int> us_dist(0, 99);
                  std::this_thread::sleep_for(std::chrono::microseconds(us_dist(rng)));
               }
               catch (const std::exception&) {
                  errors++;
               }
            }
         });
      }

      // Run for a short time
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }

      expect(errors == 0) << "Concurrent emplace operations should not produce errors";
      expect(vec.size() > 0) << "Vector should contain elements after emplace operations";

      // Validate all objects
      for (const auto& obj : vec.read()) {
         expect(obj.ptr != nullptr) << "Each object should have a valid unique_ptr";
         expect(*obj.ptr == obj.id) << "Each object's unique_ptr should point to correct value";
      }
   };

   "deadlock_prevention"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 1000; ++i) {
         vec.push_back(i);
      }

      // Test the most deadlock-prone operations:
      // - Getting an iterator
      // - Using that iterator to modify the container
      // - Multiple nesting levels

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<int> completed_operations{0};

      for (int t = 0; t < 5; ++t) {
         threads.emplace_back([&, t]() {
            while (!stop) {
               try {
                  // Get a const_iterator
                  auto proxy = vec.write();
                  auto it1 = proxy.begin() + (t * 100 % proxy.size());
                  int val1 = *it1;

                  // Use that iterator in an insert operation (potential deadlock scenario)
                  auto new_it = proxy.insert(it1, val1 * 2);

                  // Now use the new iterator in another operation
                  auto another_it = proxy.begin() + (proxy.size() / 2);
                  auto erased_it = proxy.erase(another_it);

                  // Try to use all three iterators
                  if (*it1 >= 0 && *new_it >= 0 && (erased_it == proxy.end() || *erased_it >= 0)) {
                     completed_operations++;
                  }
               }
               catch (const std::exception&) {
                  // Error, but not necessarily a deadlock
               }
            }
         });
      }

      // Run for enough time to detect deadlocks
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         if (t.joinable()) {
            t.join();
         }
      }

      expect(completed_operations > 0) << "Some operations should complete without deadlock";
   };

   "iterator_races"_test = [] {
      glz::async_vector<ComplexObject> vec;

      // Fill with complex objects
      for (int i = 0; i < 100; ++i) {
         std::vector<double> values{static_cast<double>(i), static_cast<double>(i * 2)};
         vec.emplace_back(i, "Object " + std::to_string(i), values);
      }

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<int> errors{0};

      // Thread that creates iterators and performs random jumps
      threads.emplace_back([&]() {
         auto proxy = vec.write();
         auto it = proxy.begin();
         while (!stop) {
            try {
               thread_local std::mt19937 rng(std::random_device{}());
               std::uniform_int_distribution<int> jump_dist(-10, 9);
               int jump = jump_dist(rng); // Random jump forward or backward
               if (it + jump >= proxy.begin() && it + jump < proxy.end()) {
                  it += jump;
                  it->access(); // Access the object to increment counter
               }
            }
            catch (const std::exception&) {
               errors++;
            }
         }
      });

      // Thread that continually modifies the vector
      threads.emplace_back([&]() {
         int counter = 0;
         while (!stop) {
            try {
               if (counter % 3 == 0 && vec.size() > 0) {
                  // Remove from beginning
                  auto proxy = vec.write();
                  proxy.erase(proxy.begin());
               }
               else if (counter % 3 == 1) {
                  // Add to end
                  std::vector<double> values{static_cast<double>(counter)};
                  vec.emplace_back(1000 + counter, "New " + std::to_string(counter), values);
               }
               else if (vec.size() > 0) {
                  // Replace middle
                  size_t mid = vec.size() / 2;
                  auto proxy = vec.write();
                  auto mid_it = proxy.begin() + mid;
                  std::vector<double> values{static_cast<double>(counter * 10)};
                  *mid_it = ComplexObject(2000 + counter, "Replaced", values);
               }
               counter++;
               std::this_thread::sleep_for(std::chrono::microseconds(100));
            }
            catch (const std::exception&) {
               errors++;
            }
         }
      });

      // Run for a short time
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }

      expect(errors < 10) << "Iterator races should be handled gracefully";
      // We expect some errors due to race conditions, but not too many
   };

   "resize_under_contention"_test = [] {
      glz::async_vector<int> vec;
      for (int i = 0; i < 1000; ++i) {
         vec.push_back(i);
      }

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<int> resize_count{0};
      std::atomic<int> errors{0};

      // Thread that continually resizes the vector
      threads.emplace_back([&]() {
         int size = 1000;
         bool growing = true;

         while (!stop) {
            try {
               if (growing) {
                  size += 100;
                  if (size > 2000) growing = false;
               }
               else {
                  size -= 100;
                  if (size < 500) growing = true;
               }

               vec.write().resize(size, 42);
               resize_count++;
               std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
            catch (const std::exception&) {
               errors++;
            }
         }
      });

      // Threads that read the vector during resizing
      std::atomic<uint64_t> sum = 0;
      for (int t = 0; t < 3; ++t) {
         threads.emplace_back([&]() {
            while (!stop) {
               try {
                  size_t current_size = vec.size();
                  auto proxy = vec.read();
                  for (size_t i = 0; i < current_size && i < proxy.size(); ++i) {
                     sum.fetch_add(static_cast<uint64_t>(proxy[i]), std::memory_order_relaxed);
                  }
               }
               catch (const std::exception&) {
                  errors++;
               }
            }
         });
      }

      // Threads that write to the vector during resizing
      for (int t = 0; t < 2; ++t) {
         threads.emplace_back([&]() {
            int counter = 0;
            while (!stop) {
               try {
                  size_t current_size = vec.size();
                  if (current_size > 0) {
                     size_t idx = counter % current_size;
                     auto proxy = vec.write();
                     if (idx < proxy.size()) {
                        proxy[idx] = counter;
                     }
                  }
                  counter++;
               }
               catch (const std::exception&) {
                  errors++;
               }
            }
         });
      }

      // Run for a short time
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }

      expect(resize_count > 0) << "Multiple resize operations should succeed";
   };

   "massive_parallel_operations"_test = [] {
      glz::async_vector<size_t> vec;

      std::atomic<bool> stop{false};
      std::deque<std::thread> threads;
      std::atomic<size_t> operation_count{0};

      // Create numerous threads performing different operations
      for (int t = 0; t < 20; ++t) {
         threads.emplace_back([&, t]() {
            std::mt19937 gen(t); // Deterministic random generator
            std::uniform_int_distribution<> dis(0, 9);

            while (!stop) {
               int op = dis(gen);
               try {
                  switch (op) {
                  case 0: { // Push back
                     vec.push_back(t * 1000 + operation_count.load());
                     break;
                  }
                  case 1: { // Pop back if not empty
                     auto proxy = vec.write();
                     if (!proxy.empty()) {
                        proxy.pop_back();
                     }
                     break;
                  }
                  case 2: { // Read random element
                     auto proxy = vec.read();
                     if (!proxy.empty()) {
                        size_t idx = gen() % proxy.size();
                        [[maybe_unused]] volatile size_t val = proxy[idx]; // Force read
                     }
                     break;
                  }
                  case 3: { // Modify random element
                     auto proxy = vec.write();
                     if (!proxy.empty()) {
                        size_t idx = gen() % proxy.size();
                        proxy[idx] = t;
                     }
                     break;
                  }
                  case 4: { // Insert at random position
                     auto proxy = vec.write();
                     size_t pos = proxy.empty() ? 0 : (gen() % proxy.size());
                     auto it = proxy.begin();
                     std::advance(it, (std::min)(pos, proxy.size()));
                     proxy.insert(it, t);
                     break;
                  }
                  case 5: { // Erase at random position
                     auto proxy = vec.write();
                     if (!proxy.empty()) {
                        size_t pos = gen() % proxy.size();
                        auto it = proxy.begin();
                        std::advance(it, pos);
                        proxy.erase(it);
                     }
                     break;
                  }
                  case 6: { // Iterate through
                     [[maybe_unused]] volatile size_t count = 0;
                     for (const auto& val : vec.read()) {
                        count += (val > 0 ? 1 : 0); // Simple operation to ensure compiler doesn't optimize away
                     }
                     break;
                  }
                  case 7: { // Resize
                     size_t new_size = 500 + (gen() % 500);
                     vec.resize(new_size, t);
                     break;
                  }
                  case 8: { // Reserve
                     size_t new_cap = 1000 + (gen() % 1000);
                     vec.reserve(new_cap);
                     break;
                  }
                  case 9: { // Clear occasionally
                     if (gen() % 100 == 0) { // Rare
                        vec.clear();
                     }
                     break;
                  }
                  }
                  operation_count++;
               }
               catch (const std::exception& e) {
                  expect(false) << e.what();
               }
            }
         });
      }

      // Run for a longer time to stress test
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
      stop = true;

      for (auto& t : threads) {
         t.join();
      }
   };
};

struct Point
{
   int x;
   int y;

   bool operator==(const Point& other) const { return x == other.x && y == other.y; }

   struct glaze
   {
      using T = Point;
      static constexpr auto value = glz::object("x", &T::x, "y", &T::y);
   };
};

struct User
{
   std::string name;
   int age;
   std::vector<std::string> hobbies;

   bool operator==(const User& other) const
   {
      return name == other.name && age == other.age && hobbies == other.hobbies;
   }

   struct glaze
   {
      using T = User;
      static constexpr auto value = glz::object("name", &T::name, "age", &T::age, "hobbies", &T::hobbies);
   };
};

suite async_vector_json_tests = [] {
   // JSON serialization/deserialization tests
   "async_vector write_json / read_json"_test = [] {
      glz::async_vector<int> v;
      v.push_back(1);
      v.push_back(2);
      v.push_back(3);
      v.push_back(4);
      v.push_back(5);

      std::string buffer{};

      // write_json returns a status code: false means success, true means error
      expect(not glz::write_json(v, buffer)) << "Failed to serialize async_vector";
      // The JSON for a vector of integers should be an array of numbers
      expect(buffer == "[1,2,3,4,5]") << buffer;

      glz::async_vector<int> result;
      expect(not glz::read_json(result, buffer)) << "Failed to deserialize async_vector";

      auto result_reader = result.read();
      expect(result_reader->size() == 5);
      expect((*result_reader)[0] == 1);
      expect((*result_reader)[1] == 2);
      expect((*result_reader)[2] == 3);
      expect((*result_reader)[3] == 4);
      expect((*result_reader)[4] == 5);
   };

   // Test an empty vector's serialization
   "async_vector empty serialization"_test = [] {
      glz::async_vector<int> v;
      std::string buffer{};

      expect(not glz::write_json(v, buffer));
      // An empty array in JSON
      expect(buffer == "[]") << buffer;

      glz::async_vector<int> result;
      result.push_back(99);
      result.push_back(100); // Non-empty to start
      expect(not glz::read_json(result, buffer));
      expect(result.empty());
   };

   // Test serialization with custom objects
   "async_vector custom object serialization"_test = [] {
      glz::async_vector<Point> points;
      points.push_back({1, 2});
      points.push_back({3, 4});
      points.push_back({5, 6});

      std::string buffer{};
      expect(not glz::write_json(points, buffer)) << "Failed to serialize custom objects in async_vector";

      glz::async_vector<Point> result;
      expect(not glz::read_json(result, buffer)) << "Failed to deserialize custom objects in async_vector";

      auto result_reader = result.read();
      expect(result_reader->size() == 3);
      expect((*result_reader)[0] == Point{1, 2});
      expect((*result_reader)[1] == Point{3, 4});
      expect((*result_reader)[2] == Point{5, 6});
   };

   // Test serialization with nested async_vector
   "async_vector nested serialization"_test = [] {
      glz::async_vector<glz::async_vector<int>> nested;

      // Create and add inner vectors
      glz::async_vector<int> inner1;
      inner1.push_back(1);
      inner1.push_back(2);
      inner1.push_back(3);

      glz::async_vector<int> inner2;
      inner2.push_back(4);
      inner2.push_back(5);

      glz::async_vector<int> inner3;
      inner3.push_back(6);

      nested.push_back(std::move(inner1));
      nested.push_back(std::move(inner2));
      nested.push_back(std::move(inner3));

      std::string buffer{};
      expect(not glz::write_json(nested, buffer)) << "Failed to serialize nested async_vector";

      // JSON should be a nested array
      expect(buffer == "[[1,2,3],[4,5],[6]]") << buffer;

      glz::async_vector<glz::async_vector<int>> result;
      expect(not glz::read_json(result, buffer)) << "Failed to deserialize nested async_vector";

      auto result_reader = result.read();
      expect(result_reader->size() == 3);

      auto inner1_reader = (*result_reader)[0].read();
      expect(inner1_reader->size() == 3);
      expect((*inner1_reader)[0] == 1);
      expect((*inner1_reader)[1] == 2);
      expect((*inner1_reader)[2] == 3);

      auto inner2_reader = (*result_reader)[1].read();
      expect(inner2_reader->size() == 2);
      expect((*inner2_reader)[0] == 4);
      expect((*inner2_reader)[1] == 5);

      auto inner3_reader = (*result_reader)[2].read();
      expect(inner3_reader->size() == 1);
      expect((*inner3_reader)[0] == 6);
   };

   // Test with more complex JSON structures
   "async_vector complex JSON structures"_test = [] {
      // Create test data
      glz::async_vector<User> users;
      users.push_back({"Alice", 30, {"reading", "hiking"}});
      users.push_back({"Bob", 25, {"gaming", "coding", "music"}});

      std::string buffer{};
      expect(not glz::write_json(users, buffer)) << "Failed to serialize complex structure";

      // Check JSON format (approximate)
      expect(buffer.find("Alice") != std::string::npos);
      expect(buffer.find("Bob") != std::string::npos);
      expect(buffer.find("reading") != std::string::npos);
      expect(buffer.find("gaming") != std::string::npos);

      // Deserialize
      glz::async_vector<User> result;
      expect(not glz::read_json(result, buffer)) << "Failed to deserialize complex structure";

      auto reader = result.read();
      expect(reader->size() == 2);
      expect((*reader)[0] == User{"Alice", 30, {"reading", "hiking"}});
      expect((*reader)[1] == User{"Bob", 25, {"gaming", "coding", "music"}});
   };

   // Test JSON serialization with pretty print
   "async_vector pretty print JSON"_test = [] {
      glz::async_vector<int> v;
      v.push_back(1);
      v.push_back(2);
      v.push_back(3);

      std::string buffer{};
      expect(not glz::write<glz::opts{.prettify = true}>(v, buffer)) << "Failed to serialize with pretty print";

      // Should include newlines and indentation
      expect(buffer.find("\n") != std::string::npos);
      expect(buffer.find(" ") != std::string::npos);

      // Should still deserialize correctly
      glz::async_vector<int> result;
      expect(not glz::read_json(result, buffer)) << "Failed to deserialize pretty-printed JSON";

      auto reader = result.read();
      expect(reader->size() == 3);
      expect((*reader)[0] == 1);
      expect((*reader)[1] == 2);
      expect((*reader)[2] == 3);
   };
};

suite async_vector_beve_tests = [] {
   "async_vector write_beve / read_beve"_test = [] {
      glz::async_vector<int> v;
      v.push_back(1);
      v.push_back(2);
      v.push_back(3);
      v.push_back(4);
      v.push_back(5);

      std::string buffer{};

      // write_json returns a status code: false means success, true means error
      expect(not glz::write_beve(v, buffer)) << "Failed to serialize async_vector";
      glz::async_vector<int> result;
      expect(not glz::read_beve(result, buffer)) << "Failed to deserialize async_vector";

      auto result_reader = result.read();
      expect(result_reader->size() == 5);
      expect((*result_reader)[0] == 1);
      expect((*result_reader)[1] == 2);
      expect((*result_reader)[2] == 3);
      expect((*result_reader)[3] == 4);
      expect((*result_reader)[4] == 5);
   };

   "async_vector custom object serialization"_test = [] {
      glz::async_vector<Point> points;
      points.push_back({1, 2});
      points.push_back({3, 4});
      points.push_back({5, 6});

      std::string buffer{};
      expect(not glz::write_beve(points, buffer)) << "Failed to serialize custom objects in async_vector";

      glz::async_vector<Point> result;
      expect(not glz::read_beve(result, buffer)) << "Failed to deserialize custom objects in async_vector";

      auto result_reader = result.read();
      expect(result_reader->size() == 3);
      expect((*result_reader)[0] == Point{1, 2});
      expect((*result_reader)[1] == Point{3, 4});
      expect((*result_reader)[2] == Point{5, 6});
   };
};

int main() {}