signvec 0.4.1

Vector implementation for fast, sign-based manipulation of dynamic collections.
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
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
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
use crate::{Sign, Signable};
use fastset::Set;
use nanorand::WyRand;
use serde::{Deserialize, Serialize};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::{Bound, Deref, Index, RangeBounds};

const DEFAULT_SET_SIZE: usize = 1000;

/// A vector-like data structure with additional information about the sign of its elements.
///
/// This data structure holds a vector of elements of type `T`, along with sets `pos` and `neg`
/// containing the indices of positive and negative elements respectively. The `SignVec` is used
/// to efficiently store and manipulate elements based on their sign.
///
/// Compared to standard vectors, `SignVec` provides additional functionality for handling
/// elements based on their sign and maintaining sets of positive and negative indices.
///
/// # Type Parameters
///
/// * `T`: The type of elements stored in the `SignVec`, which must implement the `Signable` trait
///        and also be cloneable.
///
/// # Fields
///
/// * `vals`: A vector holding elements of type `T`.
/// * `pos`: A set containing the indices of positive elements in `vals`.
/// * `neg`: A set containing the indices of negative elements in `vals`.
/// * `_marker`: Phantom data field to maintain covariance with the type parameter `T`.
///
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SignVec<T>
where
    T: Signable + Clone,
{
    pub vals: Vec<T>,
    pub pos: Set,
    pub neg: Set,
    _marker: PhantomData<T>,
}

impl<T> SignVec<T>
where
    T: Signable + Clone,
{
    /// Appends elements from another vector to the end of this `SignVec`.
    ///
    /// This method appends each element from the provided vector `other` to the end of the `vals`
    /// vector of this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the
    /// sign of each appended element.
    ///
    /// # Arguments
    ///
    /// * `other`: A mutable reference to a vector of elements to be appended.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec, Sign};
    ///
    /// let mut sv = svec![5, -10, 15];
    /// let mut other_vec = vec![25, -30];
    /// let mut other_sv = svec![20, -35];
    ///
    /// sv.append(&mut other_vec);
    /// sv.append(&mut other_sv);
    ///
    /// assert_eq!(sv.len(), 7);
    /// assert_eq!(sv.count(Sign::Plus), 4);
    /// assert_eq!(sv.count(Sign::Minus), 3);
    /// ```
    #[inline(always)]
    pub fn append(&mut self, other: &[T])
    where
        T: Signable + Clone,
    {
        let start_len = self.vals.len();
        other.iter().enumerate().for_each(|(index, e)| {
            let vals_index = start_len + index;
            match e.sign() {
                Sign::Plus => self.pos.insert(vals_index),
                Sign::Minus => self.neg.insert(vals_index),
            };
            self.vals.push(e.clone());
        });
    }
    /// Returns a raw pointer to the underlying data of this `SignVec`.
    ///
    /// This method returns a raw pointer to the first element in the `vals` vector of this `SignVec`.
    ///
    /// # Safety
    ///
    /// The returned pointer is valid for as long as this `SignVec` is not modified or deallocated.
    /// Modifying the `SignVec` or deallocating it invalidates the pointer. It's unsafe to dereference the pointer directly.
    /// However, it can be safely passed to other functions that expect a raw pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sv = svec![5, -10, 15];
    /// let ptr = sv.as_ptr();
    ///
    /// ```
    #[inline(always)]
    pub fn as_ptr(&self) -> *const T {
        self.vals.as_ptr()
    }
    /// Returns a slice containing all elements in this `SignVec`.
    ///
    /// This method returns a slice containing all elements in the `vals` vector of this `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sv = svec![5, -10, 15];
    /// let slice = sv.as_slice();
    ///
    /// assert_eq!(slice, &[5, -10, 15]);
    /// ```
    #[inline(always)]
    pub fn as_slice(&self) -> &[T] {
        self.vals.as_slice()
    }

    /// Returns the capacity of the `vals` vector of this `SignVec`.
    ///
    /// This method returns the capacity of the `vals` vector, which is the maximum number of elements
    /// that the vector can hold without reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sv = svec![5, -10, 15];
    /// assert_eq!(sv.capacity(), 4);
    /// ```
    #[inline(always)]
    pub fn capacity(&self) -> usize {
        self.vals.capacity()
    }

    /// Clears all elements from this `SignVec`.
    ///
    /// This method removes all elements from the `vals` vector of this `SignVec`, and clears the
    /// `pos` and `neg` sets. The capacity of none of the fields are affected.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sv = svec![5, -10, 15];
    /// sv.clear();
    ///
    /// assert!(sv.is_empty());
    /// ```
    #[inline(always)]
    pub fn clear(&mut self) {
        self.vals.clear();
        self.pos.clear();
        self.neg.clear();
    }

    /// Returns the number of elements with the specified sign in this `SignVec`.
    ///
    /// This method returns the number of elements in the `pos` set if `sign` is `Sign::Plus`, or
    /// the number of elements in the `neg` set if `sign` is `Sign::Minus`.
    ///
    /// # Arguments
    ///
    /// * `sign`: The sign of the elements to count.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, Sign, svec};
    ///
    /// let sv = svec![5, -10, 15];
    ///
    /// assert_eq!(sv.count(Sign::Plus), 2);
    /// assert_eq!(sv.count(Sign::Minus), 1);
    /// ```
    #[inline(always)]
    pub fn count(&self, sign: Sign) -> usize {
        match sign {
            Sign::Plus => self.pos.len(),
            Sign::Minus => self.neg.len(),
        }
    }

    /// Returns the number of elements with a positive sign in this `SignVec`.
    ///
    /// This method directly returns the number of elements in the `pos` set,
    /// providing a more straightforward and slightly faster alternative to calling `count(Sign::Plus)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sv = svec![5, -10, 15];
    ///
    /// assert_eq!(sv.count_pos(), 2);
    /// ```
    #[inline(always)]
    pub fn count_pos(&self) -> usize {
        self.pos.len()
    }

    /// Returns the number of elements with a negative sign in this `SignVec`.
    ///
    /// This method directly returns the number of elements in the `neg` set,
    /// providing a more straightforward and slightly faster alternative to calling `count(Sign::Minus)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sv = svec![5, -10, 15];
    ///
    /// assert_eq!(sv.count_neg(), 1);
    /// ```
    #[inline(always)]
    pub fn count_neg(&self) -> usize {
        self.neg.len()
    }

    /// Removes consecutive duplicate elements from this `SignVec`.
    ///
    /// This method removes consecutive duplicate elements from the `vals` vector of this `SignVec`.
    /// Elements are considered duplicates if they are equal according to the `PartialEq` trait.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sv = svec![5, 5, -10, 15, 15];
    /// sv.dedup();
    ///
    /// assert_eq!(sv, svec![5, -10, 15]);
    /// ```
    #[inline(always)]
    pub fn dedup(&mut self)
    where
        T: PartialEq + Signable,
    {
        if self.vals.is_empty() {
            return;
        }

        let mut write = 1; // Index to write to.
        for read in 1..self.vals.len() {
            if self.vals[read] != self.vals[read - 1] {
                // Move non-duplicate to the 'write' position if necessary.
                if read != write {
                    self.vals[write] = self.vals[read].clone();

                    if self.vals[read].sign() == Sign::Plus {
                        self.pos.remove(&read);
                        self.pos.insert(write);
                    } else {
                        self.neg.remove(&read);
                        self.neg.insert(write);
                    }
                }
                write += 1;
            } else {
                // For duplicates, just remove them from pos and neg sets.
                self.pos.remove(&read);
                self.neg.remove(&read);
            }
        }
        // Truncate the vector to remove excess elements.
        self.vals.truncate(write);
    }

    /// Removes elements from this `SignVec` based on a predicate.
    ///
    /// This method removes elements from the `vals` vector of this `SignVec` based on the provided
    /// predicate `same_bucket`. Elements `x` and `y` are considered duplicates if `same_bucket(&x, &y)`
    /// returns `true`.
    ///
    /// # Arguments
    ///
    /// * `same_bucket`: A predicate used to determine whether two elements are duplicates.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, 5, -10, 15, 15];
    /// sign_vec.dedup_by(|x, y| x == y);
    ///
    /// assert_eq!(sign_vec, svec![5, -10, 15]);
    /// ```
    #[inline(always)]
    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
    where
        F: FnMut(&T, &T) -> bool,
    {
        unsafe {
            let mut len = self.vals.len();
            let mut i = 0;
            let vals_ptr = self.vals.as_mut_ptr();
            while i < len {
                let curr = vals_ptr.add(i);
                let mut j = i + 1;
                while j < len {
                    let next = vals_ptr.add(j);
                    if same_bucket(&*curr, &*next) {
                        self.vals.remove(j);
                        self.pos.remove(&j);
                        self.neg.remove(&j);
                        len -= 1;
                    } else {
                        j += 1;
                    }
                }
                i += 1;
            }
        }
    }
    /// Removes elements from this `SignVec` based on a key function.
    ///
    /// This method removes elements from the `vals` vector of this `SignVec` based on the key
    /// returned by the provided key function `key`. If the key of two consecutive elements is equal,
    /// the second element is removed.
    ///
    /// # Arguments
    ///
    /// * `key`: A function used to determine the key for each element.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec: SignVec<i32> = svec![5, 6, 10, -10];
    /// sign_vec.dedup_by_key(|x| x.abs());
    ///
    /// assert_eq!(sign_vec, svec![5, 6, 10]);
    /// ```
    #[inline(always)]
    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
    where
        F: FnMut(&T) -> K,
        K: PartialEq,
    {
        unsafe {
            let mut i = 1;
            let vals_ptr = self.vals.as_mut_ptr();
            while i < self.vals.len() {
                // Use while loop to manually control the iteration process, allowing us to adjust 'i' as needed.
                let prev = vals_ptr.add(i - 1);
                let now = vals_ptr.add(i);
                if i > 0 && key(&*prev) == key(&*now) {
                    self.vals.remove(i); // Remove the current item if its key matches the previous item's key.
                                         // Do not increment 'i' so that the next element,
                                         // which shifts into the current index, is compared next.
                    self.pos.remove(&(i));
                    self.neg.remove(&(i));
                } else {
                    i += 1; // Only increment 'i' if no removal was made.
                }
            }
        }
    }

    /// Drains elements from this `SignVec` based on a range.
    ///
    /// This method removes elements from the `vals` vector of this `SignVec` based on the provided
    /// range `range`. It returns a `SignVecDrain` iterator over the removed elements.
    ///
    /// # Arguments
    ///
    /// * `range`: The range of indices to drain elements from.
    ///
    /// # Panics
    ///
    /// Panics if the range is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use std::ops::Bound;
    ///
    /// let mut sign_vec = svec![5, -10, 15, 20];
    /// let drained: Vec<_> = sign_vec.drain(1..3).collect();
    ///
    /// assert_eq!(drained, vec![-10, 15]);
    /// assert_eq!(sign_vec, svec![5, 20]);
    /// ```
    #[inline(always)]
    pub fn drain<R>(&mut self, range: R) -> SignVecDrain<'_, T>
    where
        R: RangeBounds<usize>,
    {
        let start = match range.start_bound() {
            Bound::Included(&s) => s,
            Bound::Excluded(&s) => s + 1,
            Bound::Unbounded => 0,
        };
        let end = match range.end_bound() {
            Bound::Included(&e) => e + 1,
            Bound::Excluded(&e) => e,
            Bound::Unbounded => self.vals.len(),
        };

        // Initial validation.
        if start > end || end > self.vals.len() {
            panic!("Drain range out of bounds");
        }

        SignVecDrain {
            sign_vec: self,
            current_index: start,
            drain_end: end,
        }
    }

    /// Extends this `SignVec` with elements from a slice.
    ///
    /// This method appends each element from the provided slice `other` to the end of the `vals`
    /// vector of this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the
    /// sign of each appended element.
    ///
    /// # Arguments
    ///
    /// * `other`: A slice of elements to be appended.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.extend_from_slice(&[15, -20]);
    ///
    /// assert_eq!(sign_vec, svec![5, -10, 15, -20]);
    /// ```
    #[inline(always)]
    pub fn extend_from_slice(&mut self, other: &[T]) {
        let offset = self.vals.len();
        self.vals.extend_from_slice(other);
        for (i, e) in other.iter().enumerate() {
            match e.sign() {
                Sign::Plus => self.pos.insert(offset + i),
                Sign::Minus => self.neg.insert(offset + i),
            };
        }
    }

    /// Extends this `SignVec` with elements from within a range.
    ///
    /// This method appends elements from the range `src` within the `vals` vector of this `SignVec`
    /// to the end of the `vals` vector. It updates the `pos` and `neg` sets accordingly based on the
    /// sign of each appended element.
    ///
    /// # Arguments
    ///
    /// * `src`: The range of indices to extend elements from.
    ///
    /// # Panics
    ///
    /// Panics if the range is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use std::ops::Bound;
    ///
    /// let mut sign_vec = svec![5, -10, 15, 20];
    /// sign_vec.extend_from_within(..=2);
    ///
    /// assert_eq!(sign_vec, svec![5, -10, 15, 20, 5, -10, 15]);
    /// ```
    #[inline(always)]
    pub fn extend_from_within<R>(&mut self, src: R)
    where
        R: RangeBounds<usize>,
    {
        let start = match src.start_bound() {
            Bound::Included(&s) => s,
            Bound::Excluded(&s) => s + 1,
            Bound::Unbounded => 0,
        };
        let end = match src.end_bound() {
            Bound::Included(&e) => e + 1,
            Bound::Excluded(&e) => e,
            Bound::Unbounded => self.vals.len(),
        };
        if start > end || end > self.vals.len() {
            panic!("Invalid range for extend_from_within");
        }

        let offset = self.vals.len();
        self.vals.extend_from_within(start..end);
        for i in start..end {
            match self.vals[i].sign() {
                Sign::Plus => self.pos.insert(offset + i - start),
                Sign::Minus => self.neg.insert(offset + i - start),
            };
        }
    }
    /// Inserts an element at a specified index into this `SignVec`.
    ///
    /// This method inserts the specified `element` at the given `index` into the `vals` vector of
    /// this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the sign of the
    /// inserted element.
    ///
    /// # Arguments
    ///
    /// * `index`: The index at which to insert the element.
    /// * `element`: The element to insert.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.insert(1, 15);
    ///
    /// assert_eq!(sign_vec, svec![5, 15, -10]);
    /// ```
    #[inline(always)]
    pub fn insert(&mut self, index: usize, element: T) {
        self.pos = self
            .pos
            .iter()
            .map(|&idx| if idx >= index { idx + 1 } else { idx })
            .collect();
        self.neg = self
            .neg
            .iter()
            .map(|&idx| if idx >= index { idx + 1 } else { idx })
            .collect();
        match element.sign() {
            Sign::Plus => {
                self.pos.insert(index);
            }
            Sign::Minus => {
                self.neg.insert(index);
            }
        };
        self.vals.insert(index, element);
    }

    /// Returns a reference to the set of indices with the specified sign.
    ///
    /// This method returns a reference to the `Set` containing the indices of elements with the
    /// specified `sign` in this `SignVec`.
    ///
    /// # Arguments
    ///
    /// * `sign`: The sign of the elements whose indices are requested.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec, Sign};
    /// use fastset::Set;
    ///
    /// let sign_vec = svec![5, -10, 15, -20];
    ///
    /// assert_eq!(sign_vec.indices(Sign::Plus), &Set::from(&[0, 2]));
    /// assert_eq!(sign_vec.indices(Sign::Minus), &Set::from(&[1, 3]));
    /// ```
    #[inline(always)]
    pub fn indices(&self, sign: Sign) -> &Set {
        match sign {
            Sign::Plus => &self.pos,
            Sign::Minus => &self.neg,
        }
    }

    /// Returns a reference to the set of indices with positive signs.
    ///
    /// This method provides direct access to the `Set` containing the indices of elements
    /// with a positive sign in this `SignVec`, bypassing the need to specify the sign.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use fastset::Set;
    ///
    /// let sign_vec = svec![5, -10, 15, -20];
    ///
    /// assert_eq!(sign_vec.indices_pos(), &Set::from(&[0, 2]));
    /// ```
    #[inline(always)]
    pub fn indices_pos(&self) -> &Set {
        &self.pos
    }

    /// Returns a reference to the set of indices with negative signs.
    ///
    /// This method provides direct access to the `Set` containing the indices of elements
    /// with a negative sign in this `SignVec`, bypassing the need to specify the sign.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use fastset::Set;
    ///
    /// let sign_vec = svec![5, -10, 15, -20];
    ///
    /// assert_eq!(sign_vec.indices_neg(), &Set::from(&[1, 3]));
    /// ```
    #[inline(always)]
    pub fn indices_neg(&self) -> &Set {
        &self.neg
    }

    /// Consumes this `SignVec`, returning a boxed slice of its elements.
    ///
    /// This method consumes the `SignVec`, transforming it into a boxed slice of its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sign_vec = svec![5, -10];
    /// let boxed_slice = sign_vec.into_boxed_slice();
    ///
    /// assert_eq!(&*boxed_slice, &[5, -10]);
    /// ```
    #[inline(always)]
    pub fn into_boxed_slice(self) -> Box<[T]> {
        self.vals.into_boxed_slice()
    }

    /// Returns `true` if this `SignVec` is empty.
    ///
    /// This method returns `true` if the `vals` vector of this `SignVec` is empty, otherwise `false`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sign_vec: SignVec<i32> = svec![];
    ///
    /// assert!(sign_vec.is_empty());
    /// ```
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.vals.is_empty()
    }

    /// Converts this `SignVec` into a mutable slice without deallocating memory.
    ///
    /// This method consumes the `SignVec` and returns a mutable reference to its elements without
    /// deallocating memory. It is the caller's responsibility to ensure that the memory is properly
    /// deallocated once the reference is no longer needed.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// let slice = sign_vec.leak();
    ///
    /// assert_eq!(slice, &mut [5, -10]);
    /// ```
    #[inline(always)]
    pub fn leak<'a>(self) -> &'a mut [T] {
        let pointer = self.vals.as_ptr();
        let len = self.vals.len();
        std::mem::forget(self);
        unsafe { std::slice::from_raw_parts_mut(pointer as *mut T, len) }
    }

    /// Returns the number of elements in this `SignVec`.
    ///
    /// This method returns the number of elements stored in the `vals` vector of this `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sign_vec = svec![5, -10, 15];
    ///
    /// assert_eq!(sign_vec.len(), 3);
    /// ```
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.vals.len()
    }
    /// Creates a new `SignVec` from a slice of elements.
    ///
    /// This method constructs a new `SignVec` by iterating over the elements in the input slice `input`.
    /// It initializes the `vals` vector with the elements from the slice and populates the `pos` and
    /// `neg` sets based on the sign of each element. The maximum index value is used to initialize the sets.
    ///
    /// # Arguments
    ///
    /// * `input`: A slice containing elements to be stored in the `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec, Sign};
    ///
    /// let mut sign_vec = SignVec::new();
    /// assert_eq!(sign_vec.len(), 0);
    /// assert_eq!(sign_vec.count(Sign::Plus), 0);
    /// assert_eq!(sign_vec.count(Sign::Minus), 0);
    ///
    /// let input_slice = &[5, -10, 15];
    /// sign_vec.extend(input_slice);
    ///
    /// assert_eq!(sign_vec.len(), 3);
    /// assert_eq!(sign_vec.count(Sign::Plus), 2);
    /// assert_eq!(sign_vec.count(Sign::Minus), 1);
    /// ```
    #[inline(always)]
    pub fn new() -> Self {
        Self::default()
    }
    /// Removes and returns the last element from this `SignVec`, or `None` if it is empty.
    ///
    /// This method removes and returns the last element from the `vals` vector of this `SignVec`, if
    /// it exists. It updates the `pos` and `neg` sets accordingly based on the sign of the removed
    /// element.
    ///
    /// # Returns
    ///
    /// * `Some(T)`: The last element from the `vals` vector, if it exists.
    /// * `None`: If the `vals` vector is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    ///
    /// assert_eq!(sign_vec.pop(), Some(-10));
    /// assert_eq!(sign_vec.pop(), Some(5));
    /// assert_eq!(sign_vec.pop(), None);
    /// ```
    #[inline(always)]
    pub fn pop(&mut self) -> Option<T> {
        if let Some(topop) = self.vals.pop() {
            let idx = self.vals.len(); // Get the new length after popping.
            match topop.sign() {
                Sign::Plus => {
                    self.pos.remove(&idx);
                }
                Sign::Minus => {
                    self.neg.remove(&idx);
                }
            };
            Some(topop)
        } else {
            None
        }
    }

    /// Appends an element to the end of this `SignVec`.
    ///
    /// This method appends the specified `element` to the end of the `vals` vector of this `SignVec`.
    /// It updates the `pos` and `neg` sets accordingly based on the sign of the appended element.
    ///
    /// # Arguments
    ///
    /// * `element`: The element to append.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.push(15);
    ///
    /// assert_eq!(sign_vec, svec![5, -10, 15]);
    /// ```
    #[inline(always)]
    pub fn push(&mut self, element: T) {
        let index = self.vals.len();
        match element.sign() {
            Sign::Plus => self.pos.insert(index),
            Sign::Minus => self.neg.insert(index),
        };
        self.vals.push(element);
    }

    /// Removes and returns the element at the specified index from this `SignVec`.
    ///
    /// This method removes and returns the element at the specified `index` from the `vals` vector of
    /// this `SignVec`. It updates the `pos` and `neg` sets accordingly based on the sign of the
    /// removed element.
    ///
    /// # Arguments
    ///
    /// * `index`: The index of the element to remove.
    ///
    /// # Returns
    ///
    /// * `T`: The element removed from the `vals` vector.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// let removed = sign_vec.remove(1);
    ///
    /// assert_eq!(removed, -10);
    /// assert_eq!(sign_vec, svec![5, 15]);
    /// ```
    #[inline(always)]
    pub fn remove(&mut self, index: usize) -> T {
        self.pos = self
            .pos
            .iter()
            .map(|&idx| if idx > index { idx - 1 } else { idx })
            .collect();
        self.neg = self
            .neg
            .iter()
            .map(|&idx| if idx > index { idx - 1 } else { idx })
            .collect();
        let removed = self.vals.remove(index);
        match removed.sign() {
            Sign::Plus => self.pos.remove(&index),
            Sign::Minus => self.neg.remove(&index),
        };
        removed
    }
    /// Reserves capacity for at least `additional` more elements in `vals`.
    ///
    /// This method reserves capacity for at least `additional` more elements in the `vals` vector of
    /// this `SignVec`. It also reserves capacity in the `pos` and `neg` sets accordingly based on the
    /// new capacity of the `vals` vector.
    ///
    /// # Arguments
    ///
    /// * `additional`: The number of additional elements to reserve capacity for.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.reserve(3);
    ///
    /// assert!(sign_vec.capacity() >= 5);
    /// ```
    #[inline(always)]
    pub fn reserve(&mut self, additional: usize) {
        let new_capacity = self.vals.len() + additional;
        self.vals.reserve(additional);
        self.pos.reserve(new_capacity);
        self.neg.reserve(new_capacity);
    }

    /// Reserves the exact capacity for `additional` more elements in `vals`.
    ///
    /// This method reserves the exact capacity for `additional` more elements in the `vals` vector of
    /// this `SignVec`. It also reserves capacity in the `pos` and `neg` sets accordingly based on the
    /// new capacity of the `vals` vector.
    ///
    /// # Arguments
    ///
    /// * `additional`: The exact number of additional elements to reserve capacity for.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.reserve_exact(3);
    ///
    /// assert_eq!(sign_vec.capacity(), 5);
    /// ```
    #[inline(always)]
    pub fn reserve_exact(&mut self, additional: usize) {
        let new_capacity = self.vals.len() + additional;
        self.vals.reserve_exact(additional);
        self.pos.reserve(new_capacity);
        self.neg.reserve(new_capacity);
    }

    /// Resizes the `SignVec` in place to a new length.
    ///
    /// This method changes the `len` field of the `vals` vector of this `SignVec`, and adjusts the
    /// elements, `pos`, and `neg` sets accordingly based on the new length and the specified `value`.
    ///
    /// # Arguments
    ///
    /// * `new_len`: The new length of the `SignVec`.
    /// * `value`: The value to initialize new elements with, if `new_len` is greater than the current
    ///            length.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.resize(5, 0);
    ///
    /// assert_eq!(sign_vec, svec![5, -10, 0, 0, 0]);
    /// ```
    #[inline(always)]
    pub fn resize(&mut self, new_len: usize, value: T) {
        let old_len = self.vals.len();
        match new_len > old_len {
            true => {
                self.vals.resize(new_len, value.clone());
                match value.sign() {
                    Sign::Plus => (old_len..new_len).for_each(|i| {
                        self.pos.insert(i);
                    }),
                    Sign::Minus => (old_len..new_len).for_each(|i| {
                        self.neg.insert(i);
                    }),
                };
            }
            false => {
                (new_len..old_len).for_each(|i| {
                    self.pos.remove(&i);
                    self.neg.remove(&i);
                });
                self.vals.truncate(new_len);
            }
        }
    }

    /// Resizes the `SignVec` in place to a new length, using a closure to create new values.
    ///
    /// This method changes the `len` field of the `vals` vector of this `SignVec`, and adjusts the
    /// elements, `pos`, and `neg` sets accordingly based on the new length and values generated by the
    /// closure `f`.
    ///
    /// # Arguments
    ///
    /// * `new_len`: The new length of the `SignVec`.
    /// * `f`: A closure that creates new values for elements beyond the current length.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10];
    /// sign_vec.resize_with(5, || 0);
    ///
    /// assert_eq!(sign_vec, svec![5, -10, 0, 0, 0]);
    /// ```
    #[inline(always)]
    pub fn resize_with<F>(&mut self, new_len: usize, mut f: F)
    where
        F: FnMut() -> T,
    {
        let old_len = self.vals.len();
        match new_len > old_len {
            true => {
                (old_len..new_len).for_each(|i| {
                    let value = f();
                    match value.sign() {
                        Sign::Plus => self.pos.insert(i),
                        Sign::Minus => self.neg.insert(i),
                    };
                    self.vals.push(value);
                });
            }
            false => {
                (new_len..old_len).for_each(|i| {
                    self.pos.remove(&i);
                    self.neg.remove(&i);
                });
                self.vals.truncate(new_len);
            }
        }
    }
    /// Retains only the elements specified by the predicate `f`.
    ///
    /// This method retains only the elements specified by the predicate `f` in the `vals` vector of
    /// this `SignVec`. It also adjusts the `pos` and `neg` sets accordingly based on the retained
    /// elements.
    ///
    /// # Arguments
    ///
    /// * `f`: A closure that takes a reference to an element and returns `true` if the element should
    ///        be retained, or `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.retain(|&x| x >= 0);
    ///
    /// assert_eq!(sign_vec, svec![5, 15]);
    /// ```
    #[inline(always)]
    pub fn retain<F>(&mut self, f: F)
    where
        F: FnMut(&T) -> bool,
    {
        self.vals.retain(f);
        self.sync();
    }

    /// Retains only the elements specified by the mutable predicate `f`.
    ///
    /// This method retains only the elements specified by the mutable predicate `f` in the `vals`
    /// vector of this `SignVec`. It also adjusts the `pos` and `neg` sets accordingly based on the
    /// retained elements.
    ///
    /// # Arguments
    ///
    /// * `f`: A closure that takes a mutable reference to an element and returns `true` if the
    ///        element should be retained, or `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.retain_mut(|x| *x >= 0);
    ///
    /// assert_eq!(sign_vec, svec![5, 15]);
    /// ```
    #[inline(always)]
    pub fn retain_mut<F>(&mut self, f: F)
    where
        F: FnMut(&mut T) -> bool,
    {
        self.vals.retain_mut(f);
        self.sync();
    }

    /// Returns a random index of an element with the specified sign.
    ///
    /// This method returns a random index of an element with the specified sign (`Sign::Plus` or
    /// `Sign::Minus`) in the `SignVec`. If no elements with the specified sign exist, `None` is
    /// returned.
    ///
    /// # Arguments
    ///
    /// * `sign`: The sign of the element to search for.
    /// * `rng`: A mutable reference to a random number generator implementing the `WyRand` trait.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, Sign, svec};
    /// use nanorand::WyRand;
    ///
    /// let sign_vec = svec![5, -10, 15];
    /// let mut rng = WyRand::new();
    /// let random_index = sign_vec.random(Sign::Plus, &mut rng);
    ///
    /// assert!(random_index.is_some());
    /// ```
    #[inline(always)]
    pub fn random(&self, sign: Sign, rng: &mut WyRand) -> Option<usize> {
        match sign {
            Sign::Plus => self.pos.random(rng),
            Sign::Minus => self.neg.random(rng),
        }
    }

    /// Returns a random index of an element with a positive sign.
    ///
    /// This method is a specializion of the `random` function, for situations
    /// where the desired sign (positive, in this case) is known at compile time.
    /// Approximately 25 % faster than calling `random` with `Sign::Plus`
    ///
    /// If no elements with a positive sign exist in the `SignVec`, `None` is returned.
    ///
    /// # Arguments
    ///
    /// * `rng`: A mutable reference to a random number generator implementing the `WyRand` trait.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use nanorand::WyRand;
    ///
    /// let sv = svec![-5, 10, -15];
    /// let mut rng = WyRand::new();
    /// let idx = sv.random_pos(&mut rng).unwrap();
    ///
    /// assert_eq!(sv[idx], 10); // Assumes that `svec!` macro creates a vector where the index of 10 is accessible.
    /// ```
    ///

    #[inline(always)]
    pub fn random_pos(&self, rng: &mut WyRand) -> Option<usize> {
        self.pos.random(rng)
    }

    /// Returns a random index of an element with a positive sign.
    ///
    /// This method is a specializion of the `random` function, for situations
    /// where the desired sign (negative, in this case) is known at compile time.
    /// Approximately 25 % faster than calling `random` with `Sign::Minus`
    ///
    /// # Arguments
    ///
    /// * `rng`: A mutable reference to a random number generator implementing the `WyRand` trait.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use nanorand::WyRand;
    ///
    /// let sv = svec![5, -10, 15];
    /// let mut rng = WyRand::new();
    /// let idx = sv.random_neg(&mut rng).unwrap();
    ///
    /// assert_eq!(sv[idx], -10);
    /// ```
    #[inline(always)]
    pub fn random_neg(&self, rng: &mut WyRand) -> Option<usize> {
        self.neg.random(rng)
    }

    /// Sets the length of the vector.
    ///
    /// This method sets the length of the vector to `new_len`. If `new_len` is greater than the current
    /// length, additional elements are added and initialized with their default values. If `new_len` is
    /// less than the current length, the excess elements are removed from the vector.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `new_len` is within the bounds of the vector's capacity and that
    /// the elements at indices `old_len..new_len` are properly initialized.
    ///
    /// # Panics
    ///
    /// Panics if `new_len` is greater than the vector's capacity.
    ///
    /// # Examples
    ///
    ///```
    /// use signvec::SignVec;
    ///
    /// unsafe {
    /// let mut sign_vec = SignVec::from(vec![5, -10, 15]);
    ///
    /// sign_vec.resize(5, 0);
    ///
    /// sign_vec.set_len(5);
    ///
    /// assert_eq!(sign_vec.len(), 5);
    /// }
    /// ```
    pub unsafe fn set_len(&mut self, new_len: usize) {
        // Check that new_len is within the bounds of the vector's capacity to avoid out-of-bounds access.
        if new_len > self.vals.capacity() {
            panic!("new_len out of bounds: new_len must be less than or equal to capacity()");
        }

        let old_len = self.vals.len();
        match new_len.cmp(&old_len) {
            std::cmp::Ordering::Greater => {
                // SAFETY: The caller must ensure that the elements at old_len..new_len are properly initialized.
                self.vals.set_len(new_len);
                let vals_ptr = self.vals.as_mut_ptr();
                (old_len..new_len).for_each(|i| {
                    // SAFETY: This dereference is safe under the assumption that elements at old_len..new_len are initialized.
                    match unsafe { &*vals_ptr.add(i) }.sign() {
                        Sign::Plus => {
                            self.pos.insert(i);
                        }
                        Sign::Minus => {
                            self.neg.insert(i);
                        }
                    }
                });
            }
            std::cmp::Ordering::Less => {
                // If the new length is less than the old length, remove indices that are no longer valid.
                (new_len..old_len).for_each(|i| {
                    self.pos.remove(&i);
                    self.neg.remove(&i);
                });
                // SAFETY: This is safe as we're only reducing the vector's length, not accessing any elements.
                self.vals.set_len(new_len);
            }
            std::cmp::Ordering::Equal => {
                // If new_len == old_len, there's no need to do anything.
            }
        }
    }

    /// Sets the value at the specified index.
    ///
    /// This method sets the value at the specified index to the given value. It also updates the
    /// positive (`pos`) and negative (`neg`) sets accordingly based on the sign change of the new
    /// value compared to the old value.
    ///
    /// # Arguments
    ///
    /// * `idx`: The index at which to set the value.
    /// * `val`: The new value to set.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.set(1, 20);
    ///
    /// assert_eq!(sign_vec, svec![5, 20, 15]);
    /// ```
    #[inline(always)]
    pub fn set(&mut self, idx: usize, val: T) {
        if idx >= self.vals.len() {
            panic!(
                "Index out of bounds: index {} length {}",
                idx,
                self.vals.len()
            );
        }
        // Safety: We've verified that idx is within bounds above
        unsafe {
            self.set_unchecked(idx, val);
        }
    }

    /// Sets the value at the specified index without bounds checking.
    ///
    /// This method sets the value at the specified index to the given value without performing any
    /// bounds checking. It also updates the positive (`pos`) and negative (`neg`) sets accordingly
    /// based on the sign change of the new value compared to the old value.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `idx` is within the bounds of the vector. Failure to do so may
    /// result in undefined behavior, memory corruption, or program crashes due to dereferencing
    /// out-of-bounds memory and corruption of the internal `pos` and `neg` sets.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// unsafe {
    ///     sign_vec.set_unchecked(1, 20);
    /// }
    ///
    /// assert_eq!(sign_vec, svec![5, 20, 15]);
    /// ```
    #[inline(always)]
    pub unsafe fn set_unchecked(&mut self, idx: usize, mut val: T) {
        let old_val = &mut *self.vals.as_mut_ptr().add(idx);
        let old_sign = old_val.sign();
        let new_sign = val.sign();
        std::mem::swap(old_val, &mut val);
        if old_sign != new_sign {
            match new_sign {
                Sign::Plus => {
                    self.neg.remove(&idx);
                    self.pos.insert(idx);
                }
                Sign::Minus => {
                    self.pos.remove(&idx);
                    self.neg.insert(idx);
                }
            }
        }
    }
    /// Shrinks the capacity of the vector to at least `min_capacity`.
    ///
    /// This method reduces the capacity of the vector to at least `min_capacity` while maintaining
    /// its length. If the current capacity is already less than or equal to `min_capacity`, this
    /// method does nothing.
    ///
    /// # Arguments
    ///
    /// * `min_capacity`: The minimum capacity to which the vector should be shrunk.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let mut sign_vec = SignVec::<f64>::with_capacity(10);
    /// sign_vec.extend(&[5.0, -10.0, 15.0]);
    /// assert!(sign_vec.capacity() >= 10);
    /// sign_vec.shrink_to(2);
    /// assert!(sign_vec.capacity() >= 3);
    ///
    /// ```
    #[inline(always)]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.vals.shrink_to(min_capacity);
        self.pos.shrink_to(min_capacity);
        self.neg.shrink_to(min_capacity);
    }

    /// Shrinks the capacity of the vector to fit its current length.
    ///
    /// This method reduces the capacity of the vector to fit its current length. If the current
    /// capacity is already equal to the length of the vector, this method does nothing.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.push(20);
    /// sign_vec.shrink_to_fit();
    ///
    /// assert_eq!(sign_vec.capacity(), 4); // Assuming the default capacity increase strategy
    /// ```
    #[inline(always)]
    pub fn shrink_to_fit(&mut self) {
        self.vals.shrink_to_fit();
        self.pos.shrink_to_fit();
        self.neg.shrink_to_fit();
    }

    /// Returns a mutable slice of the unused capacity of the vector.
    ///
    /// This method returns a mutable slice of the uninitialized memory in the vector's capacity.
    /// Modifying the elements in this slice is safe, but reading from them may lead to undefined
    /// behavior.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    /// use std::mem::MaybeUninit;
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// let unused_capacity = sign_vec.spare_capacity_mut();
    ///
    /// // Fill the spare capacity with new values
    /// for val in unused_capacity.iter_mut() {
    ///     *val = MaybeUninit::new(0);
    /// }
    ///
    /// // Now the spare capacity is filled with zeros
    /// ```
    #[inline(always)]
    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
        let len = self.vals.len();
        let capacity = self.vals.capacity();
        unsafe {
            // SAFETY: The following is safe because MaybeUninit<T> can be uninitialized,
            // and we're only exposing the uninitialized part of the allocated memory.
            std::slice::from_raw_parts_mut(
                self.vals.as_mut_ptr().add(len) as *mut MaybeUninit<T>,
                capacity - len,
            )
        }
    }

    /// Splits the vector into two at the given index.
    ///
    /// This method splits the vector into two at the given index `at`, returning a new vector
    /// containing the elements from index `at` onwards. The original vector will contain the
    /// elements up to but not including `at`. The positive (`pos`) and negative (`neg`) sets
    /// are updated accordingly for both vectors.
    ///
    /// # Arguments
    ///
    /// * `at`: The index at which to split the vector.
    ///
    /// # Panics
    ///
    /// Panics if `at` is greater than the length of the vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15, -20];
    /// let new_vec = sign_vec.split_off(2);
    ///
    /// assert_eq!(sign_vec, svec![5, -10]);
    /// assert_eq!(new_vec, svec![15, -20]);
    /// ```
    pub fn split_off(&mut self, at: usize) -> SignVec<T> {
        // Ensure 'at' is within bounds to prevent out-of-bounds access.
        if at > self.vals.len() {
            panic!(
                "split_off at index out of bounds: the length is {} but the split index is {}",
                self.vals.len(),
                at
            );
        }
        let new_vals = self.vals.split_off(at);
        let mut new_pos = Set::with_max(new_vals.len());
        let mut new_neg = Set::with_max(new_vals.len());
        (0..new_vals.len()).for_each(|i| {
            if self.pos.contains(&(at + i)) {
                self.pos.remove(&(at + i));
                new_pos.insert(i);
            } else if self.neg.remove(&(at + i)) {
                // This also acts as a check, removing the item if present.
                new_neg.insert(i);
            }
        });
        SignVec {
            vals: new_vals,
            pos: new_pos,
            neg: new_neg,
            _marker: PhantomData,
        }
    }
    /// Removes and returns the element at the specified index, replacing it with the last element.
    ///
    /// This method removes and returns the element at the specified `index`, replacing it with the
    /// last element in the vector. The positive (`pos`) and negative (`neg`) sets are updated accordingly.
    ///
    /// # Arguments
    ///
    /// * `index`: The index of the element to be removed.
    ///
    /// # Returns
    ///
    /// The removed element.
    ///
    /// # Panics
    ///
    /// Panics if the `index` is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// let removed = sign_vec.swap_remove(1);
    ///
    /// assert_eq!(removed, -10);
    /// assert_eq!(sign_vec, svec![5, 15]);
    /// ```
    #[inline(always)]
    pub fn swap_remove(&mut self, index: usize) -> T {
        let removed_element = self.vals.swap_remove(index);
        let sign = removed_element.sign();
        match sign {
            Sign::Plus => self.pos.remove(&index),
            Sign::Minus => self.neg.remove(&index),
        };

        if index < self.vals.len() {
            let swapped_element_sign = self.vals[index].sign();
            match swapped_element_sign {
                Sign::Plus => {
                    self.pos.remove(&self.vals.len());
                    self.pos.insert(index);
                }
                Sign::Minus => {
                    self.neg.remove(&self.vals.len());
                    self.neg.insert(index);
                }
            }
        }
        removed_element
    }

    /// Synchronizes the positive and negative sets with the vector's elements.
    ///
    /// This method clears the positive (`pos`) and negative (`neg`) sets, and then re-inserts the
    /// indices of the elements in the vector according to their signs.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.retain(|&x| x >= 0);
    /// sign_vec.sync();
    ///
    /// assert_eq!(sign_vec, svec![5, 15]);
    /// ```
    #[inline(always)]
    pub fn sync(&mut self) {
        self.pos.clear();
        self.neg.clear();
        self.vals.iter().enumerate().for_each(|(idx, val)| {
            match val.sign() {
                Sign::Plus => self.pos.insert(idx),
                Sign::Minus => self.neg.insert(idx),
            };
        });
    }
    /// Truncates the `SignVec` to the specified length.
    ///
    /// This method truncates the `SignVec`, keeping only the first `len` elements. It updates the
    /// positive (`pos`) and negative (`neg`) sets accordingly.
    ///
    /// # Arguments
    ///
    /// * `len`: The new length of the `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.truncate(2);
    ///
    /// assert_eq!(sign_vec, svec![5, -10]);
    /// ```
    #[inline(always)]
    pub fn truncate(&mut self, len: usize) {
        if len < self.vals.len() {
            let old_len = self.vals.len();
            unsafe {
                let vals_ptr = self.vals.as_ptr();
                for i in len..old_len {
                    let val = &*vals_ptr.add(i);
                    match val.sign() {
                        Sign::Plus => self.pos.remove(&i),
                        Sign::Minus => self.neg.remove(&i),
                    };
                }
            }
            self.vals.truncate(len);
        }
    }

    /// Tries to reserve capacity for at least `additional` more elements to be inserted in the vector.
    ///
    /// This method tries to reserve capacity for at least `additional` more elements to be inserted
    /// in the vector. It updates the capacity of the positive (`pos`) and negative (`neg`) sets
    /// accordingly.
    ///
    /// # Arguments
    ///
    /// * `additional`: The number of additional elements to reserve capacity for.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the capacity was successfully reserved, or an error if the allocation failed.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.try_reserve(5).unwrap();
    /// ```
    pub fn try_reserve(
        &mut self,
        additional: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.vals.try_reserve(additional)?;
        self.pos.reserve(self.vals.len() + additional);
        self.neg.reserve(self.vals.len() + additional);
        Ok(())
    }

    /// Tries to reserve the exact capacity for the vector to hold `additional` more elements.
    ///
    /// This method tries to reserve the exact capacity for the vector to hold `additional` more
    /// elements. It updates the capacity of the positive (`pos`) and negative (`neg`) sets
    /// accordingly.
    ///
    /// # Arguments
    ///
    /// * `additional`: The number of additional elements to reserve capacity for.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the capacity was successfully reserved, or an error if the allocation failed.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = svec![5, -10, 15];
    /// sign_vec.try_reserve_exact(5).unwrap();
    /// ```
    pub fn try_reserve_exact(
        &mut self,
        additional: usize,
    ) -> Result<(), std::collections::TryReserveError> {
        self.vals.try_reserve_exact(additional)?;
        self.pos.reserve(self.vals.len() + additional);
        self.neg.reserve(self.vals.len() + additional);
        Ok(())
    }

    /// Returns an iterator over the values with the specified sign.
    ///
    /// This method returns an iterator over the values in the `SignVec` with the specified `sign`.
    ///
    /// # Arguments
    ///
    /// * `sign`: The sign of the values to iterate over.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, Sign, svec};
    ///
    /// let sign_vec = svec![5, -10, 15];
    /// let positive_values: Vec<&i32> = sign_vec.values(Sign::Plus).collect();
    ///
    /// assert_eq!(positive_values, vec![&5, &15]);
    /// ```
    #[inline(always)]
    pub fn values(&self, sign: Sign) -> SignVecValues<T> {
        SignVecValues::new(self, sign)
    }

    /// Creates a new empty `SignVec` with the specified capacity.
    ///
    /// This method creates a new empty `SignVec` with the specified `capacity`.
    ///
    /// # Arguments
    ///
    /// * `capacity`: The capacity of the new `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let sign_vec: SignVec<f64> = SignVec::with_capacity(10);
    /// assert!(sign_vec.is_empty());
    /// ```
    #[inline(always)]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            vals: Vec::with_capacity(capacity),
            pos: Set::with_max(capacity),
            neg: Set::with_max(capacity),
            _marker: PhantomData,
        }
    }
}

/// An iterator that drains elements from a `SignVec`.
///
/// This iterator yields elements from a `SignVec`, removing them and adjusting the
/// internal positive and negative sets accordingly.
pub struct SignVecDrain<'a, T: 'a + Clone + Signable> {
    /// A mutable reference to the `SignVec` being drained.
    sign_vec: &'a mut SignVec<T>,
    /// The current index being processed during draining.
    current_index: usize,
    /// The end index of the drain operation.
    drain_end: usize,
}

impl<'a, T> Iterator for SignVecDrain<'a, T>
where
    T: Signable + Clone,
{
    type Item = T;

    /// Advances the iterator and returns the next item.
    ///
    /// This method returns `Some(item)` if there are more items to process,
    /// otherwise it returns `None`.
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index >= self.drain_end {
            return None;
        }

        // Perform the actual removal.
        let result = self.sign_vec.vals.remove(self.current_index);
        // No need to adjust self.current_index as we always remove the current element.

        // Update pos and neg to reflect the removal.
        // Since we are always removing the current element, we just need to update subsequent indices.
        // Remove the current index from pos or neg if present.
        self.sign_vec.pos.remove(&self.current_index);
        self.sign_vec.neg.remove(&self.current_index);

        // Adjust indices for remaining elements in pos and neg.
        self.sign_vec.pos = self
            .sign_vec
            .pos
            .iter()
            .map(|&i| if i > self.current_index { i - 1 } else { i })
            .collect();
        self.sign_vec.neg = self
            .sign_vec
            .neg
            .iter()
            .map(|&i| if i > self.current_index { i - 1 } else { i })
            .collect();

        // Adjust the drain_end since the vector's length has decreased by one.
        self.drain_end -= 1;

        Some(result)
    }
}

#[derive(Debug)]
pub struct SignVecValues<'a, T>
where
    T: 'a + Signable + Clone,
{
    // Store a raw pointer to the vector's data.
    vals_ptr: *const T,
    indices_iter: std::slice::Iter<'a, usize>,
}

impl<'a, T> SignVecValues<'a, T>
where
    T: Signable + Clone,
{
    #[inline(always)]
    pub fn new(sign_vec: &'a SignVec<T>, sign: Sign) -> Self {
        // Obtain a raw pointer to the data of the `vals` vector.
        let vals_ptr = sign_vec.vals.as_ptr();
        let indices_iter = match sign {
            Sign::Plus => (&sign_vec.pos).into_iter(),
            Sign::Minus => (&sign_vec.neg).into_iter(),
        };
        SignVecValues {
            vals_ptr,
            indices_iter,
        }
    }
}

impl<'a, T> Iterator for SignVecValues<'a, T>
where
    T: 'a + Signable + Clone,
{
    type Item = &'a T;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        self.indices_iter.next().map(|&idx|
            // Safety: The index is assumed to be within bounds, as indices are managed internally
            // and should be valid for the `vals` vector. Accessing the vector's elements
            // via a raw pointer obtained from `as_ptr` assumes that no concurrent modifications
            // occur, and the vector's length does not change during iteration.
            unsafe { &*self.vals_ptr.add(idx) })
    }
}

/// Allows accessing the underlying vector reference of a `SignVec`.
impl<T> AsRef<Vec<T>> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Returns a reference to the underlying vector.
    fn as_ref(&self) -> &Vec<T> {
        &self.vals
    }
}

/// Implements the default trait for `SignVec`.
///
/// This allows creating a new empty `SignVec` with a default capacity.
impl<T> Default for SignVec<T>
where
    T: Signable + Clone,
{
    /// Creates a new empty `SignVec` with a default capacity.
    ///
    /// The default capacity is determined by the `DEFAULT_SET_SIZE` constant.
    fn default() -> Self {
        Self {
            vals: Vec::default(),
            pos: Set::with_max(DEFAULT_SET_SIZE),
            neg: Set::with_max(DEFAULT_SET_SIZE),
            _marker: PhantomData,
        }
    }
}

/// Implements extending functionality for references to items.
impl<'a, T> Extend<&'a T> for SignVec<T>
where
    T: Signable + Clone + 'a,
{
    /// Extends the `SignVec` with items from an iterator over references to items.
    ///
    /// This method clones each item from the iterator and appends it to the `SignVec`,
    /// adjusting the positive and negative sets accordingly based on the sign of each item.
    ///
    /// # Arguments
    ///
    /// * `iter`: An iterator over references to items to be extended into the `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, Sign, svec};
    ///
    /// let mut sign_vec: SignVec<i32> = svec![-5, 10, -15];
    /// assert_eq!(sign_vec.len(), 3);
    /// assert_eq!(sign_vec.count(Sign::Plus), 1);
    /// assert_eq!(sign_vec.count(Sign::Minus), 2);
    ///
    /// let items: Vec<i32> = vec![5, -10, 15];
    /// sign_vec.extend(items.iter());
    /// assert_eq!(sign_vec.len(), 6);
    ///
    /// assert_eq!(sign_vec.count(Sign::Plus), 3);
    /// assert_eq!(sign_vec.count(Sign::Minus), 3);
    /// ```
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = &'a T>,
    {
        for item in iter {
            let index = self.vals.len(); // Get the current length before pushing
            self.vals.push(item.clone()); // Clone the item and push it onto vals
            match item.sign() {
                Sign::Plus => {
                    self.pos.insert(index);
                }
                Sign::Minus => {
                    self.neg.insert(index);
                }
            }
        }
    }
}

/// Implements extending functionality for owned items.
impl<T> Extend<T> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Extends the `SignVec` with items from an iterator over owned items.
    ///
    /// This method appends each item from the iterator to the `SignVec`,
    /// adjusting the positive and negative sets accordingly based on the sign of each item.
    ///
    /// # Arguments
    ///
    /// * `iter`: An iterator over owned items to be extended into the `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{svec, Sign, SignVec};
    ///
    /// let mut sign_vec = svec![-15, 10, -5];
    ///
    /// assert_eq!(sign_vec.len(), 3);
    /// assert_eq!(sign_vec.count(Sign::Plus), 1);
    /// assert_eq!(sign_vec.count(Sign::Minus), 2);
    ///
    /// let items = vec![5, -10, 15];
    /// sign_vec.extend(items.into_iter());
    ///
    /// assert_eq!(sign_vec.len(), 6);
    /// assert_eq!(sign_vec.count(Sign::Plus), 3);
    /// assert_eq!(sign_vec.count(Sign::Minus), 3);
    /// ```
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        for item in iter {
            let index = self.vals.len(); // Get the current length before pushing
            match item.sign() {
                Sign::Plus => {
                    self.pos.insert(index);
                }
                Sign::Minus => {
                    self.neg.insert(index);
                }
            }
            self.vals.push(item); // Push the item onto vals
        }
    }
}

impl<T> From<&[T]> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts a slice reference into a `SignVec` by cloning its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let slice = &[1, 2, 3, 4, 5];
    /// let sign_vec: SignVec<_> = slice.into();
    /// ```
    fn from(slice: &[T]) -> Self {
        slice.iter().cloned().collect()
    }
}

impl<T, const N: usize> From<&[T; N]> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts a shared reference to an array into a `SignVec` by cloning its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let array = &[1, 2, 3, 4, 5];
    /// let sign_vec: SignVec<_> = array.into();
    /// ```
    fn from(array: &[T; N]) -> Self {
        array.iter().cloned().collect()
    }
}

impl<T> From<&mut [T]> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts a mutable slice reference into a `SignVec` by cloning its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let mut mutable_slice = &mut [1, -5, 7];
    /// let sign_vec: SignVec<_> = mutable_slice.into();
    /// ```
    fn from(slice: &mut [T]) -> Self {
        slice.iter().cloned().collect()
    }
}

impl<T, const N: usize> From<&mut [T; N]> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts a mutable reference to an array into a `SignVec` by cloning its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let mut mutable_array = &mut [1.0, 2.0, 3.0];
    /// let sign_vec: SignVec<_> = mutable_array.into();
    /// ```
    fn from(array: &mut [T; N]) -> Self {
        array.iter().cloned().collect()
    }
}

impl<T> From<&Vec<T>> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts a vector reference into a `SignVec` by cloning its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec = vec![1, 2, 3, 4, 5];
    /// let sign_vec: SignVec<_> = (&vec).into();
    /// ```
    fn from(vec: &Vec<T>) -> Self {
        vec.iter().cloned().collect()
    }
}

impl<T> From<Vec<T>> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts a vector into a `SignVec`, moving its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec = vec![1, 2, 3, 4, 5];
    /// let sign_vec: SignVec<_> = vec.into();
    /// ```
    fn from(vec: Vec<T>) -> Self {
        vec.into_iter().collect()
    }
}

impl<T> From<SignVec<T>> for Vec<T>
where
    T: Signable + Clone,
{
    /// Converts a `SignVec` into a `Vec`, moving its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sv = svec![1, 2, 3, 4, 5];
    /// let vec: Vec<_> = Vec::from(&sv);
    /// ```
    fn from(sign_vec: SignVec<T>) -> Self {
        sign_vec.vals.clone()
    }
}

impl<T> From<&SignVec<T>> for Vec<T>
where
    T: Signable + Clone,
{
    /// Converts a reference to `SignVec` into a `Vec`, cloning its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let sign_vec: SignVec<i32> = svec![1, 2, 3, 4, 5];
    /// let vec: Vec<i32> = Vec::from(&sign_vec);
    ///
    /// ```
    fn from(sign_vec: &SignVec<T>) -> Self {
        sign_vec.vals.clone()
    }
}

impl<T, const N: usize> From<[T; N]> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Converts an owned array into a `SignVec`, moving its elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let array = [1, 2, 3, 4, 5];
    /// let sign_vec: SignVec<_> = array.into();
    /// ```
    fn from(array: [T; N]) -> Self {
        array.into_iter().collect()
    }
}

impl<T> FromIterator<T> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Constructs a `SignVec` from an iterator, cloning each element.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let iter = vec![1, -2, 3, -4, 5].into_iter();
    /// let sign_vec: SignVec<_> = iter.collect();
    /// ```
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut vec = Vec::new();
        let mut pos = Set::with_max(DEFAULT_SET_SIZE);
        let mut neg = Set::with_max(DEFAULT_SET_SIZE);

        for (i, item) in iter.into_iter().enumerate() {
            if item.sign() == Sign::Plus {
                pos.insert(i);
            } else {
                neg.insert(i);
            }
            vec.push(item);
        }

        SignVec {
            vals: vec,
            pos,
            neg,
            _marker: PhantomData,
        }
    }
}

impl<'a, T> FromIterator<&'a T> for SignVec<T>
where
    T: 'a + Signable + Clone,
{
    /// Constructs a `SignVec` from an iterator of references, cloning each element.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let iter = vec![&1, &-2, &3, &-4, &5].into_iter();
    /// let sign_vec: SignVec<_> = iter.collect();
    /// ```
    fn from_iter<I: IntoIterator<Item = &'a T>>(iter: I) -> Self {
        let mut vec = Vec::new();
        let mut pos = Set::with_max(DEFAULT_SET_SIZE);
        let mut neg = Set::with_max(DEFAULT_SET_SIZE);

        for (i, item) in iter.into_iter().enumerate() {
            let cloned_item = item.clone();
            if cloned_item.sign() == Sign::Plus {
                pos.insert(i);
            } else {
                neg.insert(i);
            }
            vec.push(cloned_item);
        }

        SignVec {
            vals: vec,
            pos,
            neg,
            _marker: PhantomData,
        }
    }
}

impl<T> IntoIterator for SignVec<T>
where
    T: Signable + Clone,
{
    type Item = T;
    type IntoIter = ::std::vec::IntoIter<T>;

    /// Converts the `SignVec` into an iterator consuming the original `SignVec`.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
    /// let mut iter = sign_vec.into_iter();
    /// assert_eq!(iter.next(), Some(1));
    /// assert_eq!(iter.next(), Some(-2));
    /// assert_eq!(iter.next(), Some(3));
    /// assert_eq!(iter.next(), None);
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        self.vals.into_iter()
    }
}

impl<'a, T> IntoIterator for &'a SignVec<T>
where
    T: Signable + Clone,
{
    type Item = &'a T;
    type IntoIter = ::std::slice::Iter<'a, T>;

    /// Converts the `SignVec` into an iterator yielding references to elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
    /// let mut iter = sign_vec.iter();
    /// assert_eq!(iter.next(), Some(&1));
    /// assert_eq!(iter.next(), Some(&-2));
    /// assert_eq!(iter.next(), Some(&3));
    /// assert_eq!(iter.next(), None);
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        self.vals.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut SignVec<T>
where
    T: Signable + Clone,
{
    type Item = &'a mut T;
    type IntoIter = ::std::slice::IterMut<'a, T>;

    /// Converts the `SignVec` into an iterator yielding mutable references to elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::{SignVec, svec};
    ///
    /// let mut sign_vec = SignVec::from(vec![1, -2, 3]);
    /// for elem in &mut sign_vec {
    ///    *elem += 1;
    /// }
    /// assert_eq!(sign_vec, svec![2, -1, 4]);
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        self.vals.iter_mut()
    }
}

// Allowing indexing into SignVec to get a reference to an element
impl<T> Index<usize> for SignVec<T>
where
    T: Signable + Clone,
{
    type Output = T;

    /// Returns a reference to the element at the given index.
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
    /// assert_eq!(sign_vec[0], 1);
    /// assert_eq!(sign_vec[1], -2);
    /// assert_eq!(sign_vec[2], 3);
    /// ```
    fn index(&self, index: usize) -> &Self::Output {
        &self.vals[index]
    }
}

// Allowing dereferencing to a slice of SignVec values
impl<T> Deref for SignVec<T>
where
    T: Signable + Clone,
{
    type Target = [T];

    /// Dereferences the SignVec to a slice of its values.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
    /// assert_eq!(&*sign_vec, &[1, -2, 3]);
    /// ```
    fn deref(&self) -> &Self::Target {
        &self.vals
    }
}

impl<T> Borrow<[T]> for SignVec<T>
where
    T: Signable + Clone,
{
    /// Borrows the SignVec as a slice of its values.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    /// use std::borrow::Borrow;
    ///
    /// let sign_vec = SignVec::<i32>::from(vec![1, -2, 3]);
    /// assert_eq!(<SignVec<i32> as std::borrow::Borrow<[i32]>>::borrow(&sign_vec), &[1, -2, 3]);
    /// ```
    fn borrow(&self) -> &[T] {
        &self.vals
    }
}

impl<T> Hash for SignVec<T>
where
    T: Signable + Clone + Hash,
{
    /// Computes the hash value for the SignVec.
    ///
    /// The hash value includes the length of the SignVec and the hash value of each element.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    /// use std::hash::{Hash, Hasher};
    ///
    /// let mut hasher = std::collections::hash_map::DefaultHasher::new();
    /// let sign_vec = SignVec::from(vec![1, -2, 3]);
    /// sign_vec.hash(&mut hasher);
    /// let hash_value = hasher.finish();
    /// ```
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.vals.len().hash(state);
        for item in &self.vals {
            item.hash(state);
        }
    }
}

impl<T> Ord for SignVec<T>
where
    T: Signable + Clone + Ord,
{
    /// Compares two SignVecs lexicographically.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec1 = SignVec::from(vec![1, -2, 3]);
    /// let vec2 = SignVec::from(vec![1, -3, 4]);
    ///
    /// assert!(vec1 > vec2);
    /// ```
    fn cmp(&self, other: &Self) -> Ordering {
        self.vals.cmp(&other.vals)
    }
}

impl<T> PartialOrd for SignVec<T>
where
    T: Signable + Clone + PartialOrd,
{
    /// Compares two SignVecs lexicographically.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec1 = SignVec::from(vec![1, -2, 3]);
    /// let vec2 = SignVec::from(vec![1, -3, 4]);
    ///
    /// assert!(vec1 > vec2);
    /// ```
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.vals.partial_cmp(&other.vals)
    }
}

impl<T> Eq for SignVec<T> where T: Signable + Clone + Eq {}

impl<T> PartialEq for SignVec<T>
where
    T: Signable + Clone + PartialEq,
{
    /// Checks if two SignVecs are equal.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec1 = SignVec::from(vec![1, -2, 3]);
    /// let vec2 = SignVec::from(vec![1, -2, 3]);
    ///
    /// assert_eq!(vec1, vec2);
    /// ```
    fn eq(&self, other: &Self) -> bool {
        self.vals.eq(&other.vals)
    }
}

// Implementations for comparisons between SignVec and slices, mutable slices, arrays, and vectors

impl<T, U> PartialEq<&[U]> for SignVec<T>
where
    T: PartialEq<U> + Signable + Clone,
{
    /// Checks if a SignVec is equal to a slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec = SignVec::<i32>::from(vec![1, -2, 3]);
    ///
    /// assert_eq!(vec, &[1, -2, 3] as &[i32]);
    /// ```
    fn eq(&self, other: &&[U]) -> bool {
        self.vals.eq(other)
    }
}

impl<T, U> PartialEq<&mut [U]> for SignVec<T>
where
    T: PartialEq<U> + Signable + Clone,
{
    /// Checks if a SignVec is equal to a mutable slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec = SignVec::<f64>::from(vec![1.0, -2.0, 3.0]);
    ///
    /// assert_eq!(vec, &[1.0, -2.0, 3.0] as &[f64]);
    /// ```

    fn eq(&self, other: &&mut [U]) -> bool {
        self.vals.eq(*other)
    }
}

impl<T, U, const N: usize> PartialEq<[U; N]> for SignVec<T>
where
    T: PartialEq<U> + Signable + Clone,
{
    /// Checks if a SignVec is equal to an array.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec = SignVec::from(vec![1, -2, 3]);
    ///
    /// assert_eq!(vec, [1, -2, 3]);
    /// ```
    fn eq(&self, other: &[U; N]) -> bool {
        self.vals.eq(other)
    }
}

impl<T, U> PartialEq<Vec<U>> for SignVec<T>
where
    T: PartialEq<U> + Signable + Clone,
{
    /// Checks if a SignVec is equal to a vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use signvec::SignVec;
    ///
    /// let vec = SignVec::from(vec![1, -2, 3]);
    ///
    /// assert_eq!(vec, vec![1, -2, 3]);
    /// ```
    fn eq(&self, other: &Vec<U>) -> bool {
        self.vals.eq(other)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::svec;
    use fastset::set;
    use std::collections::HashSet;

    #[derive(Clone, Eq, PartialEq, Default)]
    struct Account {
        balance: i32, // Assuming balance can be positive or negative
    }

    impl Account {
        fn new(balance: i32) -> Self {
            Account { balance }
        }

        fn balance(&self) -> i32 {
            self.balance
        }
    }

    impl Signable for Account {
        fn sign(&self) -> Sign {
            if self.balance >= 0 {
                Sign::Plus
            } else {
                Sign::Minus
            }
        }
    }

    #[test]
    fn test_append() {
        // Test appending positive elements
        let mut vec = svec![-1];
        let other = vec![2, -3];
        vec.append(&other);
        assert_eq!(vec.as_slice(), &[-1, 2, -3]);
        assert_eq!(vec.count(Sign::Plus), 1);
        assert_eq!(vec.count(Sign::Minus), 2);

        // Test appending negative elements
        let mut vec = svec![];
        let other = vec![-2, 3];
        vec.append(&other);
        assert_eq!(vec.as_slice(), &[-2, 3]);
        assert_eq!(vec.count(Sign::Plus), 1);
        assert_eq!(vec.count(Sign::Minus), 1);
    }

    #[test]
    fn test_as_ptr() {
        let vec: SignVec<i32> = svec![1, -2, 3];
        let ptr = vec.as_ptr();
        unsafe {
            assert_eq!(*ptr, 1); // First element
            assert_eq!(*ptr.offset(1), -2); // Second element
            assert_eq!(*ptr.offset(2), 3); // Third element
        }
    }
    #[test]
    fn test_as_slice() {
        let vec = svec![1, -2, 3];
        let slice = vec.as_slice();
        assert_eq!(slice, &[1, -2, 3]);
    }

    #[test]
    fn test_capacity() {
        let vec = SignVec::<i32>::with_capacity(10);
        assert_eq!(vec.capacity(), 10);
    }

    #[test]
    fn test_clear() {
        let mut vec = svec![1, -2, 3];
        vec.clear();
        assert!(vec.is_empty());
        assert_eq!(vec.capacity(), 4);
    }
    #[test]
    fn test_count() {
        let mut vec = svec![1, -2, 3, -4];
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 2);

        vec.push(5);
        assert_eq!(vec.count(Sign::Plus), 3);
        assert_eq!(vec.count(Sign::Minus), 2);
    }

    #[test]
    fn test_dedup() {
        // Test deduplication of positive elements
        let mut vec = svec![1, 2, 2, -3, -3, 4];
        vec.dedup();
        assert_eq!(vec.as_slice(), &[1, 2, -3, 4]);

        // Test deduplication of negative elements
        let mut vec = svec![1, 2, -2, -3, -3, 4];
        vec.dedup();
        assert_eq!(vec.as_slice(), &[1, 2, -2, -3, 4]);
    }

    #[test]
    fn test_dedup_by() {
        // Test deduplication using a custom equality function
        let mut vec = svec![10, -5, 10, -5];
        vec.dedup_by(|a, b| a == b);
        assert_eq!(vec.as_slice(), &[10, -5]);

        // Test deduplication of complex objects based on a specific property
        let mut vec = svec![
            Account::new(100),
            Account::new(-50),
            Account::new(100),
            Account::new(-50),
        ];
        vec.dedup_by(|a, b| a.balance() == b.balance());
        assert_eq!(vec.as_slice().len(), 2);
    }

    #[test]
    fn test_dedup_by_key() {
        // Test deduplication based on a derived property
        let mut vec = svec![
            Account::new(100),
            Account::new(100),
            Account::new(-50),
            Account::new(-50),
        ];
        vec.dedup_by_key(|a| a.balance());
        assert_eq!(vec.as_slice().len(), 2);
    }

    #[test]
    fn test_drain() {
        // Test draining a range from the middle
        let mut vec = svec![1, 2, 3, 4, 5];
        let drained_elements: Vec<_> = vec.drain(1..4).collect();
        assert_eq!(drained_elements, vec![2, 3, 4]);
        assert_eq!(vec.as_slice(), &[1, 5]);

        // Test draining the entire vector
        let mut vec = svec![1, 2, 3, 4, 5];
        let drained_elements: Vec<_> = vec.drain(..).collect();
        assert_eq!(drained_elements, vec![1, 2, 3, 4, 5]);
        assert!(vec.is_empty());

        // Test draining an empty range
        let mut vec = svec![1, 2, 3, 4, 5];
        let drained_elements: Vec<_> = vec.drain(5..5).collect();
        assert!(drained_elements.is_empty());
        assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5]);

        // Test draining with excluded end bound
        let mut vec = svec![1, 2, 3, 4, 5];
        let drained_elements: Vec<_> = vec.drain(..=2).collect();
        assert_eq!(drained_elements, vec![1, 2, 3]);
        assert_eq!(vec.as_slice(), &[4, 5]);
    }
    #[test]
    fn test_extend_from_slice() {
        let mut vec = svec![];
        let other = vec![1, 2, 3];
        vec.extend_from_slice(&other);
        assert_eq!(vec.as_slice(), &[1, 2, 3]);
    }

    #[test]
    fn test_extend_from_within() {
        let mut vec = svec![0, 1, 2, 3, 4];
        vec.extend_from_within(2..);
        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4, 2, 3, 4]);
        vec.extend_from_within(5..);
        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4, 2, 3, 4, 2, 3, 4]);
    }
    #[test]
    fn test_insert() {
        let mut vec = svec![1, 2, 3];
        vec.insert(1, 4);
        assert_eq!(vec.as_slice(), &[1, 4, 2, 3]);
        assert_eq!(vec.count(Sign::Plus), 4);
    }

    #[test]
    fn test_indices() {
        let vec = svec![1, -2, 3, -4, 5];
        assert_eq!(vec.indices(Sign::Plus), &Set::from(vec![0, 2, 4]));
        assert_eq!(vec.indices(Sign::Minus), &Set::from(vec![1, 3]));
    }

    #[test]
    fn test_into_boxed_slice() {
        let vec = svec![1, 2, 3];
        let boxed_slice: Box<[i32]> = vec.into_boxed_slice();
        assert_eq!(&*boxed_slice, &[1, 2, 3]);
    }

    #[test]
    fn test_is_empty() {
        let vec = SignVec::<i32>::new();
        assert!(vec.is_empty());
    }

    #[test]
    fn test_leak() {
        let vec = svec![1, 2, 3];
        let leaked_slice = vec.leak();
        assert_eq!(leaked_slice, &[1, 2, 3]);
    }

    #[test]
    fn test_len() {
        let vec = svec![1, 2, 3];
        assert_eq!(vec.len(), 3);
    }
    #[test]
    fn test_new() {
        let mut sv: SignVec<i32> = SignVec::new();
        let input = vec![1, -2, 3, -4, 5];
        input.iter().for_each(|&i| {
            sv.push(i);
        });
        assert_eq!(sv.vals, input);
        assert_eq!(sv.as_slice(), &[1, -2, 3, -4, 5]);
        assert_eq!(sv.count(Sign::Plus), 3);
        assert_eq!(sv.count(Sign::Minus), 2);
    }

    #[test]
    fn test_pop() {
        let mut vec = svec![1, 2, -3, 4];
        assert_eq!(vec.len(), 4);
        assert!(vec.indices(Sign::Plus).contains(&3));
        assert_eq!(vec.pop(), Some(4));
        assert_eq!(vec.len(), 3);
        assert!(!vec.indices(Sign::Plus).contains(&3));
        assert_eq!(vec.indices(Sign::Plus), &set![0, 1]);
        assert_eq!(vec.indices(Sign::Minus), &set![2]);
        assert_eq!(vec.pop(), Some(-3));
        assert_eq!(vec.len(), 2);
        assert!(!vec.indices(Sign::Minus).contains(&2));
        assert_eq!(vec.indices(Sign::Plus), &set![0, 1]);
        assert_eq!(vec.indices(Sign::Minus), &set![]);
    }
    #[test]
    fn test_push() {
        let mut vec = svec![];
        vec.push(1);
        vec.push(-2);
        vec.push(3);
        assert_eq!(vec.as_slice(), &[1, -2, 3]);
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 1);
    }

    #[test]
    fn test_remove() {
        let mut vec = svec![1, -2, 3];
        vec.remove(1);
        assert_eq!(vec.as_slice(), &[1, 3]);
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 0);
    }
    #[test]
    fn test_reserve() {
        let mut vec = svec![1, -2, 3];
        vec.reserve(5);
        assert!(vec.capacity() >= 5);
    }

    #[test]
    fn test_reserve_exact() {
        let mut vec = svec![1, -2, 3];
        vec.reserve_exact(5);
        assert!(vec.capacity() >= 8);
    }

    #[test]
    fn test_resize() {
        let mut vec = svec![1, -2, 3];
        vec.resize(5, 0);
        assert_eq!(vec.as_slice(), &[1, -2, 3, 0, 0]);
        assert_eq!(vec.count(Sign::Plus), 4);
        assert_eq!(vec.count(Sign::Minus), 1);
    }

    #[test]
    fn test_resize_with() {
        let mut vec = svec![1, -2, 3];
        vec.resize_with(5, || -1);
        assert_eq!(vec.as_slice(), &[1, -2, 3, -1, -1]);
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 3);
    }

    #[test]
    fn test_retain() {
        let mut vec = svec![1, -2, 3];
        vec.retain(|&x| x > 0);
        assert_eq!(vec.as_slice(), &[1, 3]);
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 0);
    }

    #[test]
    fn test_retain_mut() {
        let mut vec = svec![1, -2, 3];
        vec.retain_mut(|x| *x > 0);
        assert_eq!(vec.as_slice(), &[1, 3]);
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 0);
    }

    #[test]
    fn test_random() {
        let mut svec = svec![1, -1, 2, -2, 3];
        let mut rng = WyRand::new();
        let mut observed_values = HashSet::new();
        for _ in 0..100 {
            if let Some(value) = svec.random(Sign::Plus, &mut rng) {
                assert!(
                    svec.pos.contains(&value),
                    "Randomly selected value should be in the set"
                );
                observed_values.insert(value);
            }
        }
        // Check that multiple distinct values are observed
        assert!(
            observed_values.len() > 1,
            "Random should return different values over multiple calls"
        );
        // Test with empty set
        svec.clear();
        assert!(
            svec.random(Sign::Minus, &mut rng).is_none(),
            "Random should return None for an empty set"
        );
        assert!(
            svec.random(Sign::Plus, &mut rng).is_none(),
            "Random should return None for an empty set"
        );
    }

    #[test]
    fn test_set_len() {
        let mut vec = svec![1, -2, 3];
        vec.resize(5, 0); // Reserve extra capacity
        unsafe {
            vec.set_len(5);
        }
        assert_eq!(vec.as_slice(), &[1, -2, 3, 0, 0]);
        assert_eq!(vec.count(Sign::Plus), 4);
        assert_eq!(vec.count(Sign::Minus), 1);

        unsafe {
            vec.set_len(2);
        }
        assert_eq!(vec.as_slice(), &[1, -2]);
        assert_eq!(vec.count(Sign::Plus), 1);
        assert_eq!(vec.count(Sign::Minus), 1);
    }

    #[test]
    #[should_panic(expected = "new_len out of bounds")]
    fn test_set_len_out_of_bounds() {
        let mut vec = svec![1, -2, 3];
        unsafe {
            vec.set_len(10);
        } // Attempt to set length beyond capacity, should panic
    }

    #[test]
    fn test_set_unchecked() {
        let mut vec = svec![1, -2, 3];
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 1);
        unsafe {
            vec.set_unchecked(1, 5); // Change -2 to 5
        }
        assert_eq!(vec.as_slice(), &[1, 5, 3]);
        assert_eq!(vec.count(Sign::Plus), 3);
        assert_eq!(vec.count(Sign::Minus), 0);
    }

    #[test]
    #[should_panic(expected = "Index out of bounds")]
    fn test_set_out_of_bounds() {
        let mut vec = svec![1, -2, 3];
        vec.set(10, 5); // Attempt to set element at index 10, should panic
    }

    #[test]
    fn test_shrink_to() {
        let mut vec = SignVec::<i32>::with_capacity(10);
        vec.extend_from_slice(&[1, -2, 3]);
        assert!(vec.capacity() >= 10);
        vec.shrink_to(5);
        assert!(vec.capacity() >= 5);
        vec.shrink_to(0);
        assert!(vec.capacity() >= 3);
    }

    #[test]
    fn test_shrink_to_fit() {
        let mut vec = svec![1, -2, 3];
        vec.reserve(10); // Reserve extra capacity
        vec.shrink_to_fit();
        assert_eq!(vec.capacity(), 3);
    }

    #[test]
    fn test_spare_capacity_mut() {
        let mut vec = svec![1, -2, 3];
        vec.reserve(10); // Reserve extra capacity
        let expected_spare_capacity = vec.capacity() - vec.len();
        let spare_capacity = vec.spare_capacity_mut();
        assert_eq!(spare_capacity.len(), expected_spare_capacity); // Adjusted expectation
    }

    #[test]
    fn test_split_off() {
        let mut vec = svec![1, -2, 3];
        vec.push(4);
        let new_vec = vec.split_off(2);
        assert_eq!(vec.len(), 2);
        assert_eq!(new_vec.len(), 2);
        assert_eq!(vec.as_slice(), &[1, -2]);
        assert_eq!(new_vec.as_slice(), &[3, 4]);
    }

    #[test]
    fn test_swap_remove() {
        let mut vec = svec![1, -2, 3];
        let removed = vec.swap_remove(1);
        assert_eq!(removed, -2);
        assert_eq!(vec.len(), 2);
        assert_eq!(vec.as_slice(), &[1, 3]);
    }

    #[test]
    fn test_sync() {
        let mut vec = svec![1, -2, 3];
        vec.remove(1); // Remove an element to make the sync necessary
        vec.sync();
        assert_eq!(vec.count(Sign::Plus), 2);
        assert_eq!(vec.count(Sign::Minus), 0);

        let mut vec2 = svec![1, -1, 2];
        vec2.vals[0] = -3; // Manually change a value to test sync
        vec2.sync();
        assert!(vec2.indices(Sign::Plus).contains(&2));
        assert!(vec2.indices(Sign::Minus).contains(&0));
    }

    #[test]
    fn test_truncate() {
        let mut vec = svec![1, -2, 3];
        vec.truncate(2);
        assert_eq!(vec.len(), 2);
        assert_eq!(vec.as_slice(), &[1, -2]);
    }

    #[test]
    fn test_try_reserve() {
        let mut vec = svec![1, -2, 3];
        vec.try_reserve(2).unwrap();
        assert!(vec.capacity() >= 5); // Original capacity + 2

        // Try reserving exact additional capacity
        vec.try_reserve_exact(3).unwrap();
        assert!(vec.capacity() >= 6); // Original capacity + 3
    }

    #[test]
    fn test_values() {
        let vec = svec![1, -2, 3];
        assert_eq!(vec.values(Sign::Plus).collect::<Vec<_>>(), vec![&1, &3]);
        assert_eq!(vec.values(Sign::Minus).collect::<Vec<_>>(), vec![&-2]);
    }

    #[test]
    fn test_with_capacity() {
        let vec = SignVec::<i32>::with_capacity(5);
        assert_eq!(vec.capacity(), 5);
        assert_eq!(vec.len(), 0);
    }

    #[test]
    fn test_set_and_set_unchecked() {
        let mut sign_vec = svec![1, -1, 2];
        sign_vec.set(1, 3); // Changing -1 to 3
        assert_eq!(sign_vec.vals[1], 3);
        // Assertions to ensure `pos` and `neg` are correctly updated
    }

    #[test]
    fn test_len_and_is_empty() {
        let vec = SignVec::<i32>::new();
        assert_eq!(vec.len(), 0);
        assert!(vec.is_empty());

        let vec = svec![1, -1];
        assert_eq!(vec.len(), 2);
        assert!(!vec.is_empty());
    }

    #[test]
    fn test_indices_values_count() {
        let vec = svec![1, -1, 2, -2, 3];
        assert_eq!(vec.count(Sign::Plus), 3);
        assert_eq!(vec.count(Sign::Minus), 2);

        let plus_indices: Vec<usize> = vec.indices(Sign::Plus).iter().copied().collect();
        assert_eq!(plus_indices, vec![0, 2, 4]);

        let minus_values: Vec<&i32> = vec.values(Sign::Minus).collect();
        assert_eq!(minus_values, vec![&-1, &-2]);
    }

    #[test]
    fn test_capacity_and_with_capacity() {
        let vec = SignVec::<isize>::with_capacity(10);
        assert!(vec.capacity() >= 10);
    }

    #[test]
    fn test_reserve_and_reserve_exact() {
        let mut vec = svec![1, -1, 2];
        vec.reserve(8);
        assert!(vec.capacity() >= 10);
        vec.reserve_exact(20);
        assert!(vec.capacity() >= 20);
    }
    #[test]
    fn test_shrink_to_fit_and_shrink_to() {
        let mut vec = SignVec::with_capacity(10);
        vec.push(1);
        vec.push(-1);
        vec.shrink_to_fit();
        assert_eq!(vec.capacity(), 2);

        vec.shrink_to(10);
        assert!(vec.capacity() >= 2);
    }
    #[test]
    fn test_into_boxed_slice_and_truncate() {
        let mut vec = svec![1, -1, 2, -2, 3];
        vec.truncate(3);
        assert_eq!(vec.len(), 3);

        let boxed_slice = vec.into_boxed_slice();
        assert_eq!(boxed_slice.len(), 3);
    }
    #[test]
    fn test_as_slice_and_as_ptr() {
        let vec = svec![1, -1, 2];
        let slice = vec.as_slice();
        assert_eq!(slice, &[1, -1, 2]);

        let ptr = vec.as_ptr();
        unsafe {
            assert_eq!(*ptr, 1);
        }
    }
    #[test]
    fn test_swap_remove_and_remove() {
        let mut vec = svec![1, -1, 2];
        assert_eq!(vec.swap_remove(1), -1);
        assert_eq!(vec.len(), 2);

        assert_eq!(vec.remove(0), 1);
        assert_eq!(vec.len(), 1);
    }
    #[test]
    fn test_push_and_append() {
        let mut vec = svec![1, 2];
        vec.push(-1);
        assert_eq!(vec.len(), 3);
        assert!(vec.indices(Sign::Minus).contains(&2));

        let other = vec![3, -2];
        vec.append(&other);
        assert_eq!(vec.len(), 5);
        assert!(vec.indices(Sign::Plus).contains(&3));
        assert!(vec.indices(Sign::Minus).contains(&4));
    }
    #[test]
    fn test_insert_and_retain() {
        let mut vec = svec![1, 2, 3, 2];
        vec.insert(1, -1);
        assert_eq!(vec.len(), 5);
        assert_eq!(*vec.values(Sign::Minus).next().unwrap(), -1);
        assert_eq!(vec.indices(Sign::Plus), &set![0, 2, 3, 4]);
        assert_eq!(vec.indices(Sign::Minus), &set![1]);
        vec.retain(|&x| x != -1);
        assert_eq!(vec.len(), 4);
        assert!(!vec.indices(Sign::Minus).contains(&1));
        assert_eq!(vec.indices(Sign::Plus), &set![0, 1, 2, 3]);
        assert_eq!(vec.indices(Sign::Minus), &set![]);
    }

    // Helper function to create a SignVec and verify its contents
    fn check_signvec_contents(vec: SignVec<i32>, expected_vals: &[i32]) {
        assert_eq!(vec.vals, expected_vals);
    }

    #[test]
    fn from_slice() {
        let slice: &[i32] = &[1, -2, 3];
        let sign_vec = SignVec::from(slice);
        check_signvec_contents(sign_vec, slice);
    }

    #[test]
    fn from_array() {
        let array: &[i32; 3] = &[1, -2, 3];
        let sign_vec = SignVec::from(array);
        check_signvec_contents(sign_vec, array);
    }

    #[test]
    fn from_owned_array() {
        let array = [1, -2, 3]; // Owned array
        let sign_vec = SignVec::from(array);
        check_signvec_contents(sign_vec, &array);
    }

    // Tests for AsRef<Vec<T>> for SignVec<T>
    #[test]
    fn test_as_ref() {
        let sign_vec = SignVec::from(&[1, -2, 3][..]);
        assert_eq!(sign_vec.as_ref(), &vec![1, -2, 3]);
    }

    // Tests for Default for SignVec<T>
    #[test]
    fn test_default() {
        let sign_vec: SignVec<i32> = SignVec::default();
        assert!(sign_vec.vals.is_empty());
        // Further checks can include testing the default state of pos and neg if applicable.
    }

    // Tests for Extend<&T> for SignVec<T>
    #[test]
    fn test_extend_ref() {
        let mut sign_vec = SignVec::default();
        sign_vec.extend(&[1, -2, 3]);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
        // Additional checks can verify the correct state of pos and neg.
    }

    // Tests for Extend<T> for SignVec<T>
    #[test]
    fn test_extend_owned() {
        let mut sign_vec = SignVec::default();
        sign_vec.extend(vec![1, -2, 3]);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
        // Additional checks can verify the correct state of pos and neg.
    }

    // Tests for From<&[T]> for SignVec<T>
    #[test]
    fn test_from_slice() {
        let sign_vec = SignVec::from(&[1, -2, 3][..]);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }

    // Tests for From<&[T; N]> for SignVec<T>
    #[test]
    fn test_from_array_ref() {
        let sign_vec = SignVec::from(&[1, -2, 3]);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }

    // Tests for From<&mut [T]> for SignVec<T>
    #[test]
    fn test_from_mut_slice() {
        let sign_vec = SignVec::from(&mut [1, -2, 3][..]);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }

    // Tests for From<&mut [T; N]> for SignVec<T>
    #[test]
    fn test_from_mut_array_ref() {
        let mut array = [1, -2, 3];
        let sign_vec = SignVec::from(&mut array);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }

    // Tests for From<&Vec<T>> for SignVec<T>
    #[test]
    fn test_from_vec_ref() {
        let vec = vec![1, -2, 3];
        let sign_vec = SignVec::from(&vec);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }

    // Tests for From<Vec<T>> for SignVec<T>
    #[test]
    fn test_from_vec() {
        let vec = vec![1, -2, 3];
        let sign_vec = SignVec::from(vec);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }

    // Tests for From<[T; N]> for SignVec<T>
    #[test]
    fn test_from_array() {
        let array = [1, -2, 3];
        let sign_vec = SignVec::from(array);
        assert_eq!(sign_vec.vals, vec![1, -2, 3]);
    }
    // Test FromIterator<T> for SignVec<T>
    #[test]
    fn from_iterator_owned() {
        let items = vec![1, -1, 2, -2];
        let sign_vec: SignVec<i32> = items.into_iter().collect();
        assert_eq!(sign_vec.vals, vec![1, -1, 2, -2]);
        // Additional checks can be added for pos and neg sets.
    }

    // Test FromIterator<&T> for SignVec<T>
    #[test]
    fn from_iterator_ref() {
        let items = [1, -1, 2, -2];
        let sign_vec: SignVec<i32> = items.iter().collect();
        assert_eq!(sign_vec.vals, vec![1, -1, 2, -2]);
        // Additional checks can be added for pos and neg sets.
    }

    // Test IntoIterator for SignVec<T> (owned iteration)
    #[test]
    fn into_iterator_owned() {
        let sign_vec = SignVec::from(&[1, -1, 2, -2][..]);
        let collected: Vec<i32> = sign_vec.into_iter().collect();
        assert_eq!(collected, vec![1, -1, 2, -2]);
    }

    // Test IntoIterator for &SignVec<T> (immutable reference iteration)
    #[test]
    fn into_iterator_ref() {
        let sign_vec = SignVec::from(&[1, -1, 2, -2][..]);
        let collected: Vec<&i32> = (&sign_vec).into_iter().collect();
        assert_eq!(collected, vec![&1, &-1, &2, &-2]);
    }

    // Test IntoIterator for &mut SignVec<T> (mutable reference iteration)
    #[test]
    fn into_iterator_mut_ref() {
        let mut sign_vec = SignVec::from(&[1, -1, 2, -2][..]);
        let mut collected: Vec<&mut i32> = (&mut sign_vec).into_iter().collect();
        // Perform a mutation as a demonstration.
        collected.iter_mut().for_each(|x| **x *= 2);
        assert_eq!(sign_vec.vals, vec![2, -2, 4, -4]);
    }
    // Test for Index trait implementation
    #[test]
    fn index_test() {
        let sv = SignVec::from(vec![1, -2, 3]);
        assert_eq!(sv[0], 1);
        assert_eq!(sv[1], -2);
        assert_eq!(sv[2], 3);
    }

    // Correction for the Deref test to properly use slicing
    #[test]
    fn deref_test() {
        let sv = SignVec::from(vec![1, -2, 3]);
        let slice: &[i32] = &sv; // Directly use Deref to get a slice
        assert_eq!(slice, &[1, -2, 3]);
    }

    // Test for Borrow trait implementation
    #[test]
    fn borrow_test() {
        let sv = SignVec::from(vec![1, -2, 3]);
        let slice: &[i32] = sv.borrow();
        assert_eq!(slice, &[1, -2, 3]);
    }

    // Test for Hash trait implementation
    #[test]
    fn hash_test() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::Hasher;

        let sv = SignVec::from(vec![1, -2, 3]);
        let mut hasher = DefaultHasher::new();
        sv.hash(&mut hasher);
        let hash = hasher.finish();

        let mut hasher_vec = DefaultHasher::new();
        vec![1, -2, 3].hash(&mut hasher_vec);
        let hash_vec = hasher_vec.finish();

        assert_eq!(hash, hash_vec);
    }

    // Test for Ord and PartialOrd trait implementations
    #[test]
    fn ord_partial_ord_test() {
        let sv1 = SignVec::from(vec![1, 2, 3]);
        let sv2 = SignVec::from(vec![1, 2, 4]);
        assert!(sv1 < sv2);
        assert!(sv2 > sv1);
    }

    // Test for Eq and PartialEq trait implementations
    #[test]
    fn eq_partial_eq_test() {
        let sv1 = SignVec::from(vec![1, 2, 3]);
        let sv2 = SignVec::from(vec![1, 2, 3]);
        let sv3 = SignVec::from(vec![1, 2, 4]);
        assert_eq!(sv1, sv2);
        assert_ne!(sv1, sv3);
    }

    #[test]
    fn partial_eq_with_others_test() {
        let sv = SignVec::from(vec![1, 2, 3]);

        // When comparing SignVec with a slice, ensure you're passing a reference to the slice,
        // not a double reference. The trait implementation expects a single reference.
        let slice: &[i32] = &[1, 2, 3];
        assert_eq!(sv, slice); // Use sv directly without an additional &, since PartialEq<&[U]> is implemented

        // Similarly, for a mutable slice, pass it as a single reference.
        let mut_slice: &mut [i32] = &mut [1, 2, 3];
        assert_eq!(sv, mut_slice); // Same as above, no double referencing

        // For comparing with a Vec<U>, the implementation should already handle it correctly.
        assert_eq!(sv, vec![1, 2, 3]); // Direct comparison with Vec<U> is supported
    }
}