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
/*!
 * Thread-safe hybrid reference counting pointers
 *
 * Loosely based on the algorithm described in
 * ["Biased reference counting: minimizing atomic operations in garbage collection"][doi:10.1145/3243176.3243195]
 * by Jiho Choi et. al. but adapted to Rust's type system and its lack of a managed runtime
 * environment.
 *
 * The type `HybridRc<T, State>` provides thread-safe shared ownership of a value of type `T`
 * allocated on the heap, just like `std::sync::Arc<T>` does. The main difference is that one
 * thread at a time can use non-atomic reference counting for better performance. That means that
 * `HybridRc` is especially suited for workloads where one thread accesses the shared value
 * significantly more often than others.
 *
 * There a two variants of [`HybridRc`]:
 * - `HybridRc<T, `[`Local`]`>` (type aliased as [`Rc`]): very fast but only usable on one thread.
 * - `HybridRc<T, `[`Shared`]`>` (type aliased as [`Arc`]): slower but universally usable.
 *
 * Instances of both variants are convertible into each other. Especially, an `Rc` can always be
 * converted into an `Arc` using [`HybridRc::to_shared(&rc)`] or [`.into()`].
 *
 * An `Arc` on the other hand can only be converted into an `Rc` using [`HybridRc::to_local(&arc)`]
 * or [`.try_into()`] if no other thread has `Rc`s for the same value. The thread holding `Rc`s to
 * a value is called the "owner thread". Once all `Rc`s are dropped, the shared value becomes
 * ownerless again.
 *
 * `HybridRc` is designed as a drop-in replacement for `std::sync::Arc` and `std::rc::Rc`, so except
 * for the conversion functionality outlined above the usage is similar to these and other smart
 * pointers.
 *
 * # Thread Safety
 *
 * `HybridRc` uses two separate reference counters - one modified non-atomically and one using
 * atomic operations - and keeps track of a owner thread that is allowed to modify the "local"
 * reference counter. This means that it is thread-safe, while one thread is exempted from
 * the disadvantage of atomic operations being more expensive than ordinary memory accesses.
 *
 * # `no_std` Support
 *
 * This crate provides limited support for `no_std` environments. In this mode `Arc::to_local()` and
 * `Weak::upgrade_local()` only succeed if no `Rc` exists on *any* thread, as threads cannot be
 * reliably identified without `std`.
 *
 * To enable `no_std` mode, disable the default enabled `std` feature in Cargo.toml. A global
 * allocator is required.
 *
 * ```toml
 * [dependencies]
 * hybrid-rc = { version = "…", default-features = false }
 * ```
 *
 * # Examples
 *
 * Multiple threads need a reference to a shared value while one thread needs to clone references
 * to the value significantly more often than the others.
 * ```
 * use hybrid_rc::{Rc, Arc};
 * use std::thread;
 * use std::sync::mpsc::channel;
 *
 * # type SomeComplexType = std::collections::BinaryHeap<()>;
 * # fn expensive_computation<T>(x: impl AsRef<T>, i: i32) -> i32 { let _ = x.as_ref(); i }
 * # fn do_something<T>(x: impl AsRef<T>, _i: i32) { let _ = x.as_ref(); }
 * # fn main() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
 * let local = Rc::new(SomeComplexType::new());
 * let (sender, receiver) = channel();
 *
 * // Spawn of threads for multiple expensive computations
 * for i in 1..=4 {
 * 	let sender = sender.clone();
 * 	let shared = Rc::to_shared(&local);
 * 	thread::spawn(move || {
 * 		sender.send(expensive_computation(shared, i));
 * 	});
 * }
 *
 * // Do something that needs single-thread reference counting
 * for i in 1..=1000 {
 * 	do_something(local.clone(), i);
 * }
 *
 * // Collect expensive computation results
 * for i in 1..=4 {
 * 	println!("{:?}", receiver.recv().unwrap());
 * }
 * # Ok(())
 * # }
 * ```
 *
 * A library wants to give library consumers flexibility for multithreading but also internally
 * have the performance of `std::rc::Rc` for e.g. a complex tree structure that is mutated on
 * the main thread.
 * ```
 * use hybrid_rc::Rc;
 * use std::thread;
 *
 * # fn get_local_hybridrc_from_some_library() -> Rc<()> { Rc::default() }
 * # fn do_something(_: &()) { }
 * # fn main() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
 * let reference = get_local_hybridrc_from_some_library();
 * let shared = Rc::to_shared(&reference);
 *
 * // do the work in another thread
 * let worker = thread::spawn(move || {
 * 	do_something(&*shared);
 * });
 *
 * // Do something useful with the library
 *
 * worker.join()?;
 * # Ok(())
 * # }
 * ```
 *
 * [`HybridRc::to_shared(&rc)`]: HybridRc::to_shared
 * [`HybridRc::to_local(&arc)`]: HybridRc::to_local
 * [`.into()`]: HybridRc#impl-From<HybridRc<T%2C%20Local>>
 * [`.try_into()`]: HybridRc#impl-TryFrom<HybridRc<T%2C%20Shared>>
 * [doi:10.1145/3243176.3243195]: https://dl.acm.org/doi/10.1145/3243176.3243195
 */

#![cfg_attr(not(feature = "std"), no_std)]
#![deny(unsafe_op_in_unsafe_fn)]

extern crate alloc;
use alloc::alloc::Layout;
use alloc::borrow::{Cow, ToOwned};
use alloc::string::String;
use alloc::vec::Vec;
use core::any::Any;
use core::borrow::Borrow;
use core::cell::Cell;
use core::convert::Infallible;
use core::convert::TryFrom;
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::ops::Deref;
#[cfg(not(feature = "std"))]
use core::panic::{RefUnwindSafe, UnwindSafe};
use core::pin::Pin;
use core::ptr::NonNull;
use core::sync::atomic;
use core::sync::atomic::Ordering;
use core::{cmp, fmt, mem, ptr};
#[cfg(feature = "std")]
use std::panic::{RefUnwindSafe, UnwindSafe};

#[cfg(any(not(feature = "std"), test, doc))]
mod dummy_thread_id;
#[cfg(feature = "std")]
mod thread_id;
#[cfg(not(feature = "std"))]
pub(crate) use dummy_thread_id as thread_id;

mod atomic_thread_id;
use atomic_thread_id::{AtomicOptionThreadId, ThreadId};
mod slice_builder;
use slice_builder::SliceBuilder;
mod tests;

/// Provides a senitel pointer value for dangling `Weak`s.
///
/// This is not NULL to allow optimizations through [`NonNull`] but cannot ever be a valid pointer
/// to a [`RcBox`].
#[inline]
const fn senitel<T>() -> NonNull<T> {
	unsafe { NonNull::new_unchecked(usize::MAX as *mut T) }
}

/// Checks if the provided pointer is the [`senitel`]
#[inline]
fn is_senitel<T: ?Sized>(ptr: *const T) -> bool {
	ptr.cast::<()>() == senitel().as_ptr()
}

/// Internal module for non-public definition of `RcState`.
mod state_trait {
	use core::fmt::Debug;

	/// Internal trait for type-level enumeration of `Shared` and `Local`.
	pub trait RcState: Debug {
		const SHARED: bool;
	}
}
use state_trait::RcState;

/// Marker types for the states of a [`HybridRc`]
pub mod state {
	/// Marks a [`HybridRc`] as shared.
	///
	/// `HybridRc<_, Shared>` atomically updates the shared reference counter.
	///
	/// # See also
	/// - [`Local`]
	///
	/// [`HybridRc`]: super::HybridRc
	#[derive(Debug, Clone, Copy)]
	pub enum Shared {}
	impl super::RcState for Shared {
		const SHARED: bool = true;
	}

	/// Marks a [`HybridRc`] as local.
	///
	/// `HybridRc<_, Local>` non-atomically updates the local reference counter.
	///
	/// # See also
	/// - [`Shared`]
	///
	/// [`HybridRc`]: super::HybridRc
	#[derive(Debug, Clone, Copy)]
	pub enum Local {}
	impl super::RcState for Local {
		const SHARED: bool = false;
	}
}
use state::{Local, Shared};

/// An enumeration of possible errors when upgrading a [`Weak`].
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum UpgradeError {
	/// The referenced value was already dropped because no strong references to it exists anymore.
	ValueDropped,
	/// The requested action would have created a new [`Rc`] while at least one `Rc` still existed
	/// on another thread.
	WrongThread,
}

impl fmt::Display for UpgradeError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match *self {
			Self::ValueDropped => f.write_str("value was already dropped"),
			Self::WrongThread => {
				f.write_str("tried to get a local reference while another thread was the owner")
			}
		}
	}
}

#[cfg(feature = "std")]
impl std::error::Error for UpgradeError {}

impl From<Infallible> for UpgradeError {
	fn from(x: Infallible) -> UpgradeError {
		match x {}
	}
}

/// The `AllocError` error indicates an allocation failure when using `try_new()` etc.
///
/// Will become a type alias for [`std::alloc::AllocError`] once that is stabilized.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct AllocError;

impl fmt::Display for AllocError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str("memory allocation failed")
	}
}

#[cfg(feature = "std")]
impl std::error::Error for AllocError {}

impl From<Infallible> for AllocError {
	fn from(_: Infallible) -> AllocError {
		unreachable!();
	}
}

/// Metadata part of a shared allocation.
struct RcMeta {
	/// Id for the thread which may use local references
	owner: AtomicOptionThreadId,
	/// Strong local reference count
	strong_local: Cell<usize>,
	/// Strong shared reference count (+ 1 for all strong local references combined)
	strong_shared: atomic::AtomicUsize,

	/// Weak reference count (+ 1 for all strong references combined)
	///
	/// If `usize::MAX`, the ability to downgrade strong pointers is temporarily locked to avoid
	/// races in `get_mut()`.
	weak: atomic::AtomicUsize,
}

/// Heap struct for shared allocations of `T`.
///
/// `repr(C)` to future-proof against possible layout optimizations which could interfere with
/// `[into|from]_raw()` of transmutable data types.
#[repr(C)]
struct RcBox<T: ?Sized> {
	meta: RcMeta,
	data: T,
}

impl<T: ?Sized> RcBox<T> {
	/// Deallocates an `RcBox`
	///
	/// `meta` will be dropped, but `data` must have already been dropped in place.
	///
	/// # Safety
	/// The allocation must have been previously allocated with `RcBox::allocate_*()`.
	#[inline]
	unsafe fn dealloc(ptr: NonNull<RcBox<T>>) {
		unsafe { ptr::addr_of_mut!((*ptr.as_ptr()).meta).drop_in_place() };
		let layout = Layout::for_value(unsafe { ptr.as_ref() });
		unsafe { alloc::alloc::dealloc(ptr.as_ptr().cast(), layout) };
	}
}

impl<T> RcBox<T> {
	/// Tries to allocate an `RcBox`
	///
	/// Returns a mutable reference with arbitrary lifetime on success and the memory layout that
	/// could not be allocated if the allocation failed.
	#[inline]
	fn try_allocate<'a>(meta: RcMeta) -> Result<&'a mut RcBox<mem::MaybeUninit<T>>, Layout> {
		let layout = Layout::new::<RcBox<T>>();

		let ptr = unsafe { alloc::alloc::alloc(layout) }.cast::<RcBox<mem::MaybeUninit<T>>>();
		if ptr.is_null() {
			Err(layout)
		} else {
			unsafe { ptr::addr_of_mut!((*ptr).meta).write(meta) };
			Ok(unsafe { ptr.as_mut().unwrap() })
		}
	}

	/// Allocates an `RcBox`
	///
	/// Returns a mutable reference with arbitrary lifetime on success.
	///
	/// # Panics
	/// Panics or aborts if the allocation failed.
	#[inline]
	fn allocate<'a>(meta: RcMeta) -> &'a mut RcBox<mem::MaybeUninit<T>> {
		match Self::try_allocate(meta) {
			Ok(result) => result,
			Err(layout) => alloc::alloc::handle_alloc_error(layout),
		}
	}

	/// Tries to allocate an `RcBox` for a slice.
	///
	/// Returns a mutable reference with arbitrary lifetime on success and the memory layout that
	/// could not be allocated if the allocation failed or the layout calculation overflowed.
	#[inline]
	fn try_allocate_slice<'a>(
		meta: RcMeta,
		len: usize,
		zeroed: bool,
	) -> Result<&'a mut RcBox<[mem::MaybeUninit<T>]>, Layout> {
		// Calculate memory layout
		let layout = Layout::new::<RcBox<[T; 0]>>();
		let payload_layout = Layout::array::<T>(len).map_err(|_| layout)?;
		let layout = layout
			.extend(payload_layout)
			.map_err(|_| layout)?
			.0
			.pad_to_align();

		// Allocate memory
		let ptr = unsafe {
			if zeroed {
				alloc::alloc::alloc_zeroed(layout)
			} else {
				alloc::alloc::alloc(layout)
			}
		};

		// Build a fat pointer
		// The immediate slice reference [MaybeUninit<u8>] *should* be sound
		let ptr = ptr::slice_from_raw_parts_mut(ptr.cast::<mem::MaybeUninit<u8>>(), len)
			as *mut RcBox<[mem::MaybeUninit<T>]>;

		if ptr.is_null() {
			// Allocation failed
			Err(layout)
		} else {
			// Initialize metadata field and return result
			unsafe { ptr::addr_of_mut!((*ptr).meta).write(meta) };
			Ok(unsafe { ptr.as_mut().unwrap() })
		}
	}

	/// Allocates an `RcBox` for a slice
	///
	/// Returns a mutable reference with arbitrary lifetime on success.
	///
	/// # Panics
	/// Panics or aborts if the allocation failed or the memory layout calculation overflowed.
	#[inline]
	fn allocate_slice<'a>(
		meta: RcMeta,
		len: usize,
		zeroed: bool,
	) -> &'a mut RcBox<[mem::MaybeUninit<T>]> {
		match Self::try_allocate_slice(meta, len, zeroed) {
			Ok(result) => result,
			Err(layout) => alloc::alloc::handle_alloc_error(layout),
		}
	}
}

impl<T> RcBox<mem::MaybeUninit<T>> {
	/// Converts to a mutable reference without the `MaybeUninit` wrapper.
	///
	/// # Safety
	/// The payload must have been fully initialized or this causes immediate undefined behaviour.
	#[inline]
	unsafe fn assume_init(&mut self) -> &mut RcBox<T> {
		unsafe { (self as *mut Self).cast::<RcBox<T>>().as_mut() }.unwrap()
	}
}

impl<T> RcBox<[mem::MaybeUninit<T>]> {
	/// Converts to a mutable reference without the `MaybeUninit` wrapper.
	///
	/// # Safety
	/// The payload slice must have been fully initialized or this causes immediate undefined
	/// behaviour.
	#[inline]
	unsafe fn assume_init(&mut self) -> &mut RcBox<[T]> {
		unsafe { (self as *mut _ as *mut RcBox<[T]>).as_mut() }.unwrap()
	}
}

impl RcMeta {
	/// Increments the local reference counter unconditionally.
	///
	/// *Only safe to use on the owner thread and as long as at least one local reference exists.*
	///
	/// # Panics
	/// Panics if the counter overflowed.
	#[inline(always)]
	fn inc_strong_local(&self) {
		let counter = self.strong_local.get();

		if counter == usize::MAX {
			panic!("reference counter overflow");
		}

		self.strong_local.set(counter + 1);
	}

	/// Increment the local reference counter.
	///
	/// Also adjusts the shared reference counter if neccessary.
	///
	/// Fails if this would resurrect an already dropped
	/// value.
	///
	/// *Only safe to use on the owner thread.*
	///
	/// # Panics
	/// Panics if one of the counters overflowed.
	#[inline]
	fn try_inc_strong_local(&self) -> Result<(), ()> {
		let counter = self.strong_local.get();

		if counter == usize::MAX {
			panic!("reference counter overflow");
		} else if counter == 0 {
			self.try_inc_strong_shared()?;
		}

		self.strong_local.set(counter + 1);
		Ok(())
	}

	/// Decrements the local reference counter.
	///
	/// Also adjusts the shared reference counter and
	/// the `owner` if neccessary.
	///
	/// Returns **true** if no strong references remain at all.
	///
	/// *Only safe to use on the owner thread.*
	///
	/// # Panics
	/// Panics if the shared reference counter was already zero.
	#[inline(always)]
	fn dec_strong_local(&self) -> bool {
		let counter = self.strong_local.get();
		self.strong_local.set(counter - 1);
		if counter == 1 {
			self.remove_last_local_reference()
		} else {
			false
		}
	}

	/// Decrements the shared counter and sets the `owner` to `None`.
	///
	/// Used internally by `dec_strong_local()`
	///
	/// # Panics
	/// Panics if the counter was already zero.
	fn remove_last_local_reference(&self) -> bool {
		let old_shared = self.strong_shared.fetch_sub(1, Ordering::Release);
		if old_shared == 0 {
			panic!("reference counter underflow");
		}
		self.owner.store(None, Ordering::Release);
		old_shared == 1
	}

	/// Increments the shared reference counter unconditionally.
	///
	/// *Only safe to use as long as at least one shared reference exists.*
	///
	/// # Panics
	/// Panics if the counter overflowed.
	#[inline]
	fn inc_strong_shared(&self) {
		let old_counter = self.strong_shared.fetch_add(1, Ordering::Relaxed);
		if old_counter == usize::MAX {
			panic!("reference counter overflow");
		}
	}

	/// Increments the shared reference counter.
	///
	/// Also adjusts the shared reference counter and the `owner` if neccessary.
	///
	/// Fails if this would resurrect an already dropped value.
	///
	/// # Panics
	/// Panics if the counter overflowed.
	#[inline]
	fn try_inc_strong_shared(&self) -> Result<(), ()> {
		self.strong_shared
			.fetch_update(
				Ordering::Relaxed,
				Ordering::Relaxed,
				|old_counter| match old_counter {
					0 => None,
					usize::MAX => panic!("reference counter overflow"),
					_ => Some(old_counter + 1),
				},
			)
			.map(|_| ())
			.map_err(|_| ())
	}

	/// Decrements the shared reference counter.
	///
	/// Returns **true** if no strong references remain at all.
	///
	/// # Panics
	/// Panics if the counter was already zero.
	#[inline]
	fn dec_strong_shared(&self) -> bool {
		let old_counter = self.strong_shared.fetch_sub(1, Ordering::Release);
		if old_counter == 0 {
			panic!("reference counter underflow");
		}
		old_counter == 1 && self.owner.load(Ordering::Relaxed).is_none()
	}

	/// Increments the weak reference counter.
	///
	/// # Panics
	/// Panics if the counter overflowed or was already zero.
	#[inline]
	fn inc_weak(&self) {
		const MAX_COUNT: usize = usize::MAX - 1;
		let mut counter = self.weak.load(Ordering::Relaxed);

		// CAS loop
		loop {
			match counter {
				usize::MAX => {
					core::hint::spin_loop();
					counter = self.weak.load(Ordering::Relaxed);
					continue;
				}
				MAX_COUNT => panic!("weak counter overflow"),
				0 => panic!("BUG: weak resurrection of dead counted reference"),
				_ => {
					let result = self.weak.compare_exchange_weak(
						counter,
						counter + 1,
						Ordering::Acquire,
						Ordering::Relaxed,
					);
					match result {
						Ok(_) => break,
						Err(old) => counter = old,
					}
				}
			}
		}
	}

	/// Increments the weak reference counter (without a spin loop).
	///
	/// # Panics
	/// Panics if the counter is locked, overflowed or was already zero.
	#[inline]
	fn inc_weak_nolock(&self) {
		const MAX_COUNT: usize = usize::MAX - 1;
		match self.weak.fetch_add(1, Ordering::Relaxed) {
			usize::MAX => panic!("BUG: weak counter locked"),
			MAX_COUNT => panic!("weak counter overflow"),
			0 => panic!("BUG: weak resurrection of dead counted reference"),
			_ => (),
		}
	}

	/// Decrements the weak reference counter.
	///
	/// Returns **true** if the counter reached zero.
	///
	/// # Panics
	/// Panics if the counter was already zero.
	#[inline]
	fn dec_weak(&self) -> bool {
		let old_counter = self.weak.fetch_sub(1, Ordering::Release);
		if old_counter == 0 {
			panic!("weak counter underflow");
		}
		old_counter == 1
	}

	/// Checks if there is only one unique reference.
	///
	/// If `is_local` is true, it is assumed that we can access the local reference counter
	///
	/// Temporarily locks the weak reference counter to prevent race conditions.
	#[inline]
	fn has_unique_ref(&self, is_local: bool) -> bool {
		let result =
			self.weak
				.compare_exchange(1, usize::MAX, Ordering::Acquire, Ordering::Relaxed);
		if result.is_ok() {
			let mut count = self.strong_shared.load(Ordering::Acquire);

			if count == 1 {
				let owner = self.owner.load(Ordering::Relaxed);
				match owner {
					None => {}
					Some(tid) if is_local || tid == ThreadId::current_thread() => {
						count = self.strong_local.get();
					}
					Some(_) => {
						count = 2;
					}
				}
			}

			self.weak.store(1, Ordering::Release);

			count == 1
		} else {
			false
		}
	}
}

/// A hybrid reference-counting pointer.
///
/// - [`HybridRc<T, Shared>`][Arc] behaves mostly like [`std::sync::Arc`]
/// - [`HybridRc<T, Local>`][Rc] behaves mostly like [`std::rc::Rc`].
///
/// See the [module-level documentation][crate] for more details.
///
/// The inherent methods of `HybridRc` are all associated functions, which means that you have to
/// call them as e.g. [`HybridRc::get_mut(&mut x)`] instead of `x.get_mut()`. This avoids conflicts
/// with methods of the inner type `T`.
///
/// [`HybridRc::get_mut(&mut x)`]: Self::get_mut
#[must_use]
pub struct HybridRc<T: ?Sized, State: RcState> {
	ptr: NonNull<RcBox<T>>,
	phantom: PhantomData<State>,
	phantom2: PhantomData<RcBox<T>>,
}

/// Type alias for a local reference counting pointer.
///
/// Provided to ease migrating from [`std::rc::Rc`].
///
/// See the [module-level documentation][crate] for more details.
///
/// The inherent methods of `Rc` are all associated functions, which means that you have to call
/// them as e.g. [`Rc::to_shared(&x)`] instead of `x.to_shared()`. This avoids conflicts with
/// methods of the inner type `T`.
///
/// [`Rc::to_shared(&x)`]: Self::to_shared
pub type Rc<T> = HybridRc<T, Local>;

/// Type alias for a shared reference counting pointer.
///
/// Provided to ease migrating from [`std::sync::Arc`].
///
/// See the [module-level documentation] for more details.
///
/// The inherent methods of `Arc` are all associated functions, which means that you have to call
/// them as e.g. [`Arc::to_local(&x)`] instead of `x.to_local()`. This avoids conflicts with
/// methods of the inner type `T`.
///
/// [`Arc::to_local(&x)`]: Self::to_local
/// [module-level documentation]: crate
pub type Arc<T> = HybridRc<T, Shared>;

impl<T: ?Sized, State: RcState> HybridRc<T, State> {
	/// Creates a new `HybridRc` from a pointer to a shared allocation.
	///
	/// The reference counters must have been updated by the caller.
	#[inline(always)]
	fn from_inner(ptr: NonNull<RcBox<T>>) -> Self {
		Self {
			ptr,
			phantom: PhantomData,
			phantom2: PhantomData,
		}
	}

	/// Provides a reference to the inner value.
	#[inline(always)]
	fn data(&self) -> &T {
		// Safety: as long as one HybridRc or Weak for this item exists, the memory stays allocated.
		unsafe { &(*self.ptr.as_ptr()).data }
	}

	/// Provides a reference to the shared metadata.
	#[inline(always)]
	fn meta(&self) -> &RcMeta {
		// Safety: as long as one HybridRc or Weak for this item exists, the memory stays allocated.
		unsafe { &(*self.ptr.as_ptr()).meta }
	}

	/// Returns a mutable reference to the value, without checking for uniqueness.
	///
	/// # See also
	/// - [`get_mut()`], which is safe.
	///
	/// # Safety
	/// No other `HybridRc` or [`Weak`] for the same value must be dereferenced for the duration of
	/// the returned borrow.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let mut a = Rc::new([1, 2, 3]);
	/// // We know that there can't be any other references yet, so getting a mutable reference
	/// // is safe here:
	/// let mut_ref = unsafe { Rc::get_mut_unchecked(&mut a) };
	/// mut_ref[0] = 42;
	///
	/// assert_eq!(a[..], [42, 2, 3]);
	/// ```
	/// [`get_mut()`]: Self::get_mut
	#[must_use]
	#[inline]
	pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
		unsafe { &mut (*this.ptr.as_ptr()).data }
	}

	/// Returns a mutable reference to the value, iff the value is not shared
	/// with another `HybridRc` or [`Weak`].
	///
	/// Returns `None` otherwise.
	#[must_use]
	#[inline]
	pub fn get_mut(this: &mut Self) -> Option<&mut T> {
		if this.meta().has_unique_ref(!State::SHARED) {
			unsafe { Some(Self::get_mut_unchecked(this)) }
		} else {
			None
		}
	}

	/// Provides a raw pointer to the referenced value
	///
	/// The counts are not affected in any way and the `HybridRc` is not consumed.
	/// The pointer is valid for as long there exists at least one `HybridRc` for the value.
	#[must_use]
	#[inline]
	pub fn as_ptr(this: &Self) -> *const T {
		this.data()
	}

	/// Creates a new [`Weak`] for the referenced value.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::{Rc, Weak};
	///
	/// let strong = Rc::new(42i32);
	/// let weak = Rc::downgrade(&strong);
	///
	/// assert_eq!(Rc::as_ptr(&strong), Weak::as_ptr(&weak));
	/// ```
	#[inline]
	pub fn downgrade(this: &Self) -> Weak<T> {
		this.meta().inc_weak();
		Weak { ptr: this.ptr }
	}

	/// Checks if two `HybridRc`s point to the same allocation.
	#[inline]
	pub fn ptr_eq<S: RcState>(this: &Self, other: &HybridRc<T, S>) -> bool {
		this.ptr.as_ptr() == other.ptr.as_ptr()
	}

	/// Gets the approximate number of strong pointers to the inner value.
	///
	/// As shared pointers cannot access the local reference counter, `Arc::strong_count()` only
	/// provides a lower bound on the reference count at the moment of the call.
	///
	/// Please also understand that, if the count is greater than one, another thread might change
	/// the count at any time, including potentially between calling this method and acting on the
	/// result.
	///
	/// # Examples
	///
	/// ```
	/// use hybrid_rc::{Rc, Arc};
	///
	/// let reference = Rc::new(42);
	/// let _2nd_ref = Rc::clone(&reference);
	/// let shared_ref = Rc::to_shared(&reference);
	/// let _2nd_shared_ref = Arc::clone(&shared_ref);
	///
	/// assert_eq!(Rc::strong_count(&reference), 4);
	/// // shared_ref only knows the count of shared references and that there is at least one
	/// // local reference, so it will show 3 instead of 4:
	/// assert_eq!(Arc::strong_count(&shared_ref), 3);
	/// ```
	#[inline]
	pub fn strong_count(this: &Self) -> usize {
		let meta = this.meta();
		meta.strong_shared.load(Ordering::SeqCst)
			+ if State::SHARED {
				0
			} else {
				meta.strong_local.get() - 1
			}
	}

	/// Gets the number of [`Weak`] pointers to this allocation.
	///
	/// Please understand that another thread may change the weak count at any time, including
	/// potentially between calling this method and acting on the result.
	///
	/// # Examples
	///
	/// ```
	/// use hybrid_rc::{Rc, Weak};
	///
	/// let reference = Rc::new(42);
	/// let weak = Rc::downgrade(&reference);
	/// let _weak_2 = weak.clone();
	///
	/// assert_eq!(Rc::weak_count(&reference), 2);
	/// ```
	#[inline]
	pub fn weak_count(this: &Self) -> usize {
		match this.meta().weak.load(Ordering::SeqCst) {
			// Lock value => there were zero weak references apart from the implicit one.
			usize::MAX => 0,
			count => count - 1,
		}
	}

	// Constructs an `RcMeta` structure for a new `HybridRc` allocation
	#[inline]
	fn build_new_meta() -> RcMeta {
		RcMeta {
			owner: if State::SHARED {
				None.into()
			} else {
				ThreadId::current_thread().into()
			},
			strong_local: Cell::new(if State::SHARED { 0 } else { 1 }),
			strong_shared: 1.into(),
			weak: 1.into(),
		}
	}

	/// Drops the contained value and also drops the shared `RcBox` if there are no other `Weak`
	/// references.
	///
	/// # Safety
	/// Only safe to use in `drop()` or a consuming function after verifying that no other strong
	/// reference exists. Otherwise after calling this e.g. dereferencing the `HybridRc` WILL
	/// cause undefined behaviour and even dropping it MAY cause undefined behaviour.
	unsafe fn drop_contents_and_maybe_box(&mut self) {
		// Safety: only called if this was the last strong reference
		unsafe {
			ptr::drop_in_place(Self::get_mut_unchecked(self));
		}

		if self.meta().dec_weak() {
			// Safety: only called if this was the last (weak) reference
			unsafe {
				RcBox::dealloc(self.ptr);
			}
		}
	}
}

impl<T, State: RcState> HybridRc<T, State> {
	/// Creates a new `Rc<T>`, moving `data` into a reference counted allocation.
	///
	/// If `State` is `Local`, the shared value is initially owned by the calling thread, so
	/// for another thread to assume ownership [`to_shared()`] must be used and all `Rc`s for
	/// the value must be dropped.
	///
	/// If `State` is `Shared`, initially the shared value has no owner thread, so any thread may
	/// call [`to_local()`] to assume ownership.
	///
	/// # Examples
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let rc = Rc::new(42i32);
	/// ```
	/// ```compile_fail
	/// # let rc = hybrid_rc::Rc::new(42i32);
	/// // Cannot be used in another thread without using rc.to_shared()
	/// std::thread::spawn(move || *rc).join(); // does not compile
	/// ```
	///
	/// ```
	/// use hybrid_rc::Arc;
	/// # fn main() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
	///
	/// let arc = Arc::new(42i32);
	///
	/// std::thread::spawn(move || assert!(*arc == 42)).join()?;
	/// # Ok(())
	/// # }
	/// ```
	///
	/// [`to_shared()`]: Self::to_shared
	/// [`to_local()`]: Self::to_local
	#[inline]
	pub fn new(data: T) -> Self {
		let inner = RcBox::allocate(Self::build_new_meta());
		inner.data.write(data);
		Self::from_inner(unsafe { inner.assume_init() }.into())
	}

	/// Creates a new `HybridRc` with uninitialized contents.
	#[inline]
	pub fn new_uninit() -> HybridRc<mem::MaybeUninit<T>, State> {
		let inner = RcBox::allocate(Self::build_new_meta());
		HybridRc::from_inner(inner.into())
	}

	/// Creates a new `HybridRc` with uninitialized contents, with the memory being filled with
	/// 0 bytes.
	///
	/// See [`MaybeUninit::zeroed()`] for examples of correct and incorrect usage of this method.
	///
	/// [`MaybeUninit::zeroed()`]: mem::MaybeUninit::zeroed
	#[inline]
	pub fn new_zeroed() -> HybridRc<mem::MaybeUninit<T>, State> {
		let inner = RcBox::allocate(Self::build_new_meta());
		inner.data = mem::MaybeUninit::zeroed();
		HybridRc::from_inner(inner.into())
	}

	/// Creates a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then `data` will be pinned
	/// in memory and unable to be moved.
	#[inline]
	pub fn pin(data: T) -> Pin<Self> {
		unsafe { Pin::new_unchecked(Self::new(data)) }
	}

	/// Tries to creates a new `Rc<T>`, moving `data` into a reference counted allocation.
	///
	/// # Errors
	/// Will drop `data` and return `Err(`[`AllocError`]`)` if the allocation fails.
	///
	/// Please note that the global allocator on some systems may instead abort the process if an
	/// allocation failure happens.
	#[inline]
	pub fn try_new(data: T) -> Result<Self, AllocError> {
		let inner = RcBox::try_allocate(Self::build_new_meta()).map_err(|_| AllocError)?;
		inner.data.write(data);
		Ok(Self::from_inner(unsafe { inner.assume_init() }.into()))
	}

	/// Tries to construct a new `HybridRc` with uninitialized contents.
	///
	/// # Errors
	/// Will return `Err(`[`AllocError`]`)` if the allocation fails.
	///
	/// Please note that the global allocator on some systems may instead abort the process if an
	/// allocation failure happens.
	#[inline]
	pub fn try_new_uninit() -> Result<HybridRc<mem::MaybeUninit<T>, State>, AllocError> {
		let inner = RcBox::try_allocate(Self::build_new_meta()).map_err(|_| AllocError)?;
		Ok(HybridRc::from_inner(inner.into()))
	}

	/// Tries to construct a new `HybridRc` with uninitialized contents, with the memory being
	/// filled with 0 bytes.
	///
	/// See [`MaybeUninit::zeroed()`] for examples of correct and incorrect usage of this method.
	///
	/// # Errors
	/// Will return `Err(`[`AllocError`]`)` if the allocation fails.
	///
	/// Please note that the global allocator on some systems may instead abort the process if an
	/// allocation failure happens.
	///
	/// [`MaybeUninit::zeroed()`]: mem::MaybeUninit::zeroed
	#[inline]
	pub fn try_new_zeroed() -> Result<HybridRc<mem::MaybeUninit<T>, State>, AllocError> {
		let inner = RcBox::try_allocate(Self::build_new_meta()).map_err(|_| AllocError)?;
		inner.data = mem::MaybeUninit::zeroed();
		Ok(HybridRc::from_inner(inner.into()))
	}

	/// Returns the inner value, if this `HybridRc` is the only strong reference to it.
	///
	/// Any outstanding [`Weak`] references won't be able to upgrade anymore when this succeeds.
	///
	/// # Errors
	/// If this is not the only strong reference to the shared value, an [`Err`] is returned with
	/// the same `HybridRc` that was passed in.
	///
	/// # Examples
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let reference = Rc::new(42);
	/// let weak = Rc::downgrade(&reference);
	///
	/// let value = Rc::try_unwrap(reference).unwrap();
	/// assert_eq!(value, 42);
	/// assert!(weak.upgrade().is_err()); // Weaks cannot upgrade anymore.
	/// ```
	#[inline]
	pub fn try_unwrap(this: Self) -> Result<T, Self> {
		if State::SHARED {
			Self::try_unwrap_internal(this)
		} else {
			// If we may access the local counter, first check and decrement that one.
			let local_count = this.meta().strong_local.get();
			if local_count == 1 {
				this.meta().strong_local.set(0);
				match Self::try_unwrap_internal(this) {
					Ok(result) => Ok(result),
					Err(this) => {
						this.meta().strong_local.set(local_count);
						Err(this)
					}
				}
			} else {
				Err(this)
			}
		}
	}

	/// Returns the inner value, if this `HybridRc` is the only strong reference to it, assuming
	/// that there are no (other) local references to the value.
	///
	/// Used internally by `try_unwrap()`.
	#[inline]
	fn try_unwrap_internal(this: Self) -> Result<T, Self> {
		let meta = this.meta();
		// There is one implicit shared reference for all local references, so if there are no other
		// local references or we are a shared shared and the shared counter is 1, we are the only
		// strong reference left.
		if meta
			.strong_shared
			.compare_exchange(1, 0, Ordering::AcqRel, Ordering::Relaxed)
			.is_err()
		{
			Err(this)
		} else {
			// Relaxed should be enough, as `strong_shared` already hit 0, so no more
			// Weak upgrading is possible.
			meta.owner.store(None, Ordering::Relaxed);

			let copy = unsafe { ptr::read(Self::as_ptr(&this)) };

			// Make a weak pointer to clean up the remaining implicit weak reference
			let _weak = Weak { ptr: this.ptr };
			mem::forget(this);

			Ok(copy)
		}
	}
}

impl<T, State: RcState> HybridRc<[T], State> {
	/// Creates a new reference-counted slice with uninitialized contents.
	#[inline]
	pub fn new_uninit_slice(len: usize) -> HybridRc<[mem::MaybeUninit<T>], State> {
		let inner = RcBox::allocate_slice(Self::build_new_meta(), len, false);
		HybridRc::from_inner(inner.into())
	}

	/// Creates a new reference-counted slice with uninitialized contents, with the memory being
	/// filled with 0 bytes.
	#[inline]
	pub fn new_zeroed_slice(len: usize) -> HybridRc<[mem::MaybeUninit<T>], State> {
		let inner = RcBox::allocate_slice(Self::build_new_meta(), len, true);
		HybridRc::from_inner(inner.into())
	}

	/// Copies the contents of a slice into a new `HybridRc`
	///
	/// # Safety
	/// Either `T` is `Copy` or the caller must guarantee that the the source doesn't drop its
	/// contents.
	#[inline]
	unsafe fn copy_from_slice_unchecked(src: &[T]) -> Self {
		let len = src.len();
		let inner = RcBox::allocate_slice(Self::build_new_meta(), len, false);
		let dest = ptr::addr_of_mut!((*inner).data).cast();

		// Safety: The freshly allocated `RcBox` can't alias `src` and the payload can be fully
		// initialized by copying the slice memory. The copying is also safe as long as the safety
		// requirements for calling this are fulfilled.
		unsafe {
			src.as_ptr().copy_to_nonoverlapping(dest, src.len());
			HybridRc::from_inner(inner.assume_init().into())
		}
	}
}

impl<T: Copy, State: RcState> HybridRc<[T], State> {
	/// Copies the contents of a slice into a new `HybridRc`
	///
	/// Optimization for copyable types. Will become deprecated once specialization is stablilized.
	#[inline]
	pub fn copy_from_slice(src: &[T]) -> Self {
		// Safety: `T` is `Copy`.
		unsafe { Self::copy_from_slice_unchecked(src) }
	}
}

impl<T: ?Sized> Rc<T> {
	/// Creates a new shared reference (`Arc`) for the referenced value.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::{Rc, Arc};
	/// # fn main() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
	///
	/// let local = Rc::new(42i32);
	/// let shared = Rc::to_shared(&local);
	///
	/// // `shared` can be safely transferred to another thread
	/// std::thread::spawn(move || assert_eq!(*shared, 42i32)).join()?;
	/// # Ok(())
	/// # }
	/// ```
	#[inline]
	pub fn to_shared(this: &Self) -> Arc<T> {
		this.meta().inc_strong_shared();
		Arc::from_inner(this.ptr)
	}
}

impl<T: ?Sized> Arc<T> {
	/// Creates a new local reference (`Rc`) for the referenced value.
	///
	/// Returns `None` if at least one `Rc` already exists on another thread.
	///
	/// **Note:** In `no_std` environments `None` is returned if at least one `Rc` exists on *any*
	/// thread.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::{Rc, Arc};
	/// # fn main() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
	///
	/// let local = Rc::new(42i32);
	/// let shared = Rc::to_shared(&local);
	///
	/// // `shared` can be safely transferred to another thread
	/// std::thread::spawn(move || assert_eq!(*shared, 42i32)).join()?;
	/// # Ok(())
	/// # }
	/// ```
	#[must_use]
	#[inline]
	pub fn to_local(this: &Self) -> Option<Rc<T>> {
		let meta = this.meta();
		let current_thread = ThreadId::current_thread();
		let owner = match meta.owner.store_if_none(
			Some(current_thread),
			Ordering::Acquire,
			Ordering::Relaxed,
		) {
			Ok(_) => None,
			Err(owner) => owner,
		};

		match owner {
			None => {
				meta.try_inc_strong_local()
					.expect("inconsistent reference count (shared == 0)");
				Some(Rc::from_inner(this.ptr))
			}
			Some(v) if v == current_thread => {
				meta.inc_strong_local();
				Some(Rc::from_inner(this.ptr))
			}
			Some(_) => None,
		}
	}
}

impl<T: Clone, State: RcState> HybridRc<T, State> {
	/// Makes a mutable reference into the given `HybridRc`.
	///
	/// If there are other strong references to the same value, then `make_mut()` will [`clone`] the
	/// inner value to a new allocation to ensure unique ownership.  This is also referred to as
	/// clone-on-write.
	///
	/// However, if there are no other strong references to this allocation, but some [`Weak`]
	/// pointers, then the [`Weak`]s will be disassociated and the inner value will not be cloned.
	///
	/// See also: [`get_mut()`], which will fail rather than cloning the inner value
	/// or diassociating [`Weak`]s.
	///
	/// [`clone`]: Clone::clone
	/// [`get_mut()`]: HybridRc::get_mut
	///
	/// # Example
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let mut reference = Rc::new(42);
	///
	/// *Rc::make_mut(&mut reference) += 2;          // Won't clone anything
	/// let mut reference_2 = Rc::clone(&reference); // Won't clone inner value
	/// *Rc::make_mut(&mut reference) += 1;         // Clones inner data
	/// *Rc::make_mut(&mut reference) *= 2;        // Won't clone anything
	/// *Rc::make_mut(&mut reference_2) /= 4;       // Won't clone anything
	///
	/// // Now `reference` and `reference_2` point to different allocations.
	/// assert_eq!(*reference, 90);
	/// assert_eq!(*reference_2, 11);
	/// ```
	#[inline]
	pub fn make_mut(this: &mut Self) -> &mut T {
		let meta = this.meta();
		if State::SHARED {
			Self::make_mut_internal(this, false)
		} else {
			let local_count = meta.strong_local.get();
			Self::make_mut_internal(this, local_count > 1)
		}
	}

	/// Makes a mutable reference into the given `HybridRc`, assuming that only the shared strong
	/// counter needs to be checked.
	///
	/// If `force_clone` is true, the counters are ignored and uniqueness will always be ensured
	/// by cloning the shared allocation.
	///
	/// Used internally by `make_mut()`.
	#[inline]
	fn make_mut_internal(this: &mut Self, force_clone: bool) -> &mut T {
		let meta = this.meta();
		// There is one implicit shared reference for all local references, so if there are no other
		// local references or we are a shared shared and the shared counter is 1, we are the only
		// strong reference left.
		if force_clone
			|| meta
				.strong_shared
				.compare_exchange(1, 0, Ordering::Acquire, Ordering::Relaxed)
				.is_err()
		{
			// Clone the allocation and make `this` point to the new clone
			let mut donor = this.clone_allocation();
			mem::swap(&mut this.ptr, &mut donor.ptr);
		} else {
			// Check if there are Weak references left.
			// Relaxed suffices, as if there is a race with a dropping Weak, then it's only a
			// missing optimization, but the code keeps being sound.
			if meta.weak.load(Ordering::Relaxed) != 1 {
				// Acts as a guard to decrement the weak counter
				let _weak = Weak { ptr: this.ptr };

				// Steal the payload data
				let mut donor = Self::new_uninit();
				unsafe {
					let uninit = HybridRc::get_mut_unchecked(&mut donor);
					uninit.as_mut_ptr().copy_from_nonoverlapping(&**this, 1);
					let donor = donor.assume_init();
					this.ptr = donor.ptr;
					mem::forget(donor);
				}
			} else {
				// There were no Weak references, so we are the unique reference. Bump the counter
				// back up.
				meta.strong_shared.store(1, Ordering::Release);
			}
		}

		// Safe, because by now we are the only reference to the allocation in `this.ptr`, either
		// to begin with, by swapping or by stealing.
		unsafe { Self::get_mut_unchecked(this) }
	}

	/// Clones the shared allocation and returns a `HybridRc` pointing to the clone.
	#[inline]
	fn clone_allocation(&self) -> Self {
		let mut result = Self::new_uninit();
		let uninit = unsafe { HybridRc::get_mut_unchecked(&mut result) };
		uninit.write((*self.data()).clone());
		unsafe { result.assume_init() }
	}
}

impl<T, State: RcState> HybridRc<mem::MaybeUninit<T>, State> {
	/// Assumes the value is initialized and converts to `HybridRc<T, State>`.
	///
	/// # Safety
	///
	/// You need to provide the same guarantees as for [`MaybeUninit::assume_init()`].
	/// Calling this when the value is not yet fully initialized causes immediate undefined
	/// behavior.
	///
	/// # Examples
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let mut reference = Rc::<i64>::new_uninit();
	///
	/// let reference = unsafe {
	/// 	// Deferred initialization
	/// 	Rc::get_mut_unchecked(&mut reference).as_mut_ptr().write(1337);
	///     reference.assume_init()
	/// };
	///
	/// assert_eq!(*reference, 1337)
	/// ```
	///
	/// [`MaybeUninit::assume_init()`]: mem::MaybeUninit::assume_init
	#[inline]
	pub unsafe fn assume_init(self) -> HybridRc<T, State> {
		HybridRc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
	}
}

impl<T, State: RcState> HybridRc<[mem::MaybeUninit<T>], State> {
	/// Assumes the values are initialized and converts to `HybridRc<[T], State>`.
	///
	/// # Safety
	///
	/// You need to provide the same guarantees as for [`MaybeUninit::assume_init()`].
	/// Calling this when the whole slice is not yet fully initialized causes immediate undefined
	/// behavior.
	///
	/// [`MaybeUninit::assume_init()`]: mem::MaybeUninit::assume_init
	#[inline]
	pub unsafe fn assume_init(self) -> HybridRc<[T], State> {
		HybridRc::from_inner(unsafe {
			mem::ManuallyDrop::new(self)
				.ptr
				.as_mut()
				.assume_init()
				.into()
		})
	}
}

impl<State: RcState> HybridRc<dyn Any, State> {
	/// Tries to downcast the `HybridRc<dyn Any, _>` to a concrete type.
	///
	/// # Errors
	/// If a downcast failed, the original `HybridRc` is returned in `Err`
	///
	/// # Example
	///
	/// ```
	/// use std::any::Any;
	/// use std::mem::drop;
	/// use hybrid_rc::Rc;
	///
	/// let value = 42i32;
	/// let concrete = Rc::new(value);
	/// let any: Rc<dyn Any> = Rc::into(concrete);
	///
	/// let any = any.downcast::<String>().unwrap_err();
	///
	/// assert_eq!(*any.downcast::<i32>().unwrap(), 42);
	/// ```
	#[inline]
	pub fn downcast<T: Any>(self) -> Result<HybridRc<T, State>, Self> {
		if (*self).is::<T>() {
			let ptr = self.ptr.cast::<RcBox<T>>();
			mem::forget(self);
			Ok(HybridRc::from_inner(ptr))
		} else {
			Err(self)
		}
	}
}

impl<State: RcState> HybridRc<dyn Any + Sync + Send, State> {
	/// Tries to downcast the `HybridRc<dyn Any + Sync + Send, _>` to a concrete type.
	///
	/// # Errors
	/// If a downcast failed, the original `HybridRc` is returned in `Err`
	///
	/// # Example
	///
	/// ```
	/// use std::any::Any;
	/// use std::mem::drop;
	/// use hybrid_rc::Rc;
	///
	/// let value = 42i32;
	/// let concrete = Rc::new(value);
	/// let any: Rc<dyn Any + Sync + Send> = Rc::into(concrete);
	///
	/// let any = any.downcast::<String>().unwrap_err();
	///
	/// assert_eq!(*any.downcast::<i32>().unwrap(), 42);
	/// ```
	#[inline]
	pub fn downcast<T: Any + Sync + Send>(self) -> Result<HybridRc<T, State>, Self> {
		if (*self).is::<T>() {
			let ptr = self.ptr.cast::<RcBox<T>>();
			mem::forget(self);
			Ok(HybridRc::from_inner(ptr))
		} else {
			Err(self)
		}
	}
}

impl<T: ?Sized> Clone for HybridRc<T, Local> {
	/// Creates another `Rc` for the same value.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let first = Rc::new(42i32);
	/// let second = Rc::clone(&first);
	///
	/// assert_eq!(Rc::as_ptr(&first), Rc::as_ptr(&second));
	/// ```
	#[inline]
	fn clone(&self) -> Self {
		self.meta().inc_strong_local();
		Self::from_inner(self.ptr)
	}
}

impl<T: ?Sized> Clone for HybridRc<T, Shared> {
	/// Creates another `Arc` for the same value.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::Arc;
	/// # fn main() -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
	///
	/// let first = Arc::new(42i32);
	/// let second = Arc::clone(&first);
	///
	/// assert_eq!(Arc::as_ptr(&first), Arc::as_ptr(&second));
	///
	/// let value = std::thread::spawn(move || *second)
	///   .join()?;
	/// assert_eq!(*first, value);
	/// # Ok(())
	/// # }
	/// ```
	#[inline]
	fn clone(&self) -> Self {
		self.meta().inc_strong_shared();
		Self::from_inner(self.ptr)
	}
}

impl<T: ?Sized, State: RcState> Drop for HybridRc<T, State> {
	/// Drops the `HybridRc`.
	///
	/// This will decrement the appropriate reference count depending on `State`. If both strong
	/// reference counts reach zero then the only other references (if any) are [`Weak`]. In that
	/// case the inner value is dropped.
	#[inline]
	fn drop(&mut self) {
		let no_more_strong_refs = if State::SHARED {
			self.meta().dec_strong_shared()
		} else {
			self.meta().dec_strong_local()
		};

		if no_more_strong_refs {
			unsafe {
				self.drop_contents_and_maybe_box();
			}
		}
	}
}

// Dereferencing traits

impl<T: ?Sized, State: RcState> Deref for HybridRc<T, State> {
	type Target = T;

	#[inline]
	fn deref(&self) -> &T {
		self.data()
	}
}

impl<T: ?Sized, State: RcState> Borrow<T> for HybridRc<T, State> {
	#[inline]
	fn borrow(&self) -> &T {
		&**self
	}
}

impl<T: ?Sized, State: RcState> AsRef<T> for HybridRc<T, State> {
	#[inline]
	fn as_ref(&self) -> &T {
		&**self
	}
}

// Safety: T: Sync implies that dereferencing the Arc<T> on multiple threads is sound and T: Send
// implies that dropping T on another thread is sound. So T: Sync + Send gives all guarantees we
// need to make Arc Sync + Send.
unsafe impl<T: ?Sized + Sync + Send> Send for HybridRc<T, Shared> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for HybridRc<T, Shared> {}

// Unwind safety: A HybridRc can only be UnwindSafe if the inner type is RefUnwindSafe.
impl<T: RefUnwindSafe + ?Sized, State: RcState> UnwindSafe for HybridRc<T, State> {}

// Unwind safety: An Arc is always RefUnwindSafe because of its use of atomics.
impl<T: RefUnwindSafe> RefUnwindSafe for HybridRc<T, Shared> {}

// Conversions between different HybridRc variants

impl<T: Any + 'static, State: RcState> From<HybridRc<T, State>>
	for HybridRc<dyn Any + 'static, State>
{
	/// Upcasts a `HybridRc<T, State>` into a `HybridRc<dyn Any, State>`
	#[inline]
	fn from(src: HybridRc<T, State>) -> Self {
		let ptr = src.ptr.as_ptr() as *mut RcBox<dyn Any>;
		mem::forget(src);
		Self::from_inner(unsafe { NonNull::new_unchecked(ptr) })
	}
}

impl<T: Any + Sync + Send + 'static, State: RcState> From<HybridRc<T, State>>
	for HybridRc<dyn Any + Sync + Send + 'static, State>
{
	/// Upcasts a `HybridRc<T, State>` into a `HybridRc<dyn Any + Sync + Send, State>`
	#[inline]
	fn from(src: HybridRc<T, State>) -> Self {
		let ptr = src.ptr.as_ptr() as *mut RcBox<dyn Any + Sync + Send>;
		mem::forget(src);
		Self::from_inner(unsafe { NonNull::new_unchecked(ptr) })
	}
}

impl<T, State: RcState, const N: usize> From<HybridRc<[T; N], State>> for HybridRc<[T], State> {
	/// Converts a `HybridRc<[T; N], State>` into a `HybridRc<[T], State>`
	///
	/// Workaround for coercion as long as `CoerceUnsized` is unstable.
	#[inline]
	fn from(src: HybridRc<[T; N], State>) -> Self {
		let ptr = src.ptr.as_ptr() as *mut RcBox<[T]>;
		mem::forget(src);
		Self::from_inner(unsafe { NonNull::new_unchecked(ptr) })
	}
}

impl<T: ?Sized> From<Rc<T>> for HybridRc<T, Shared> {
	/// Converts an `Rc<T>` into an `Arc<T>`.
	///
	/// See [`to_shared()`].
	///
	/// [`to_shared()`]: HybridRc::to_shared
	#[inline]
	fn from(src: Rc<T>) -> Self {
		HybridRc::to_shared(&src)
	}
}

impl<T: ?Sized> TryFrom<Arc<T>> for HybridRc<T, Local> {
	type Error = Arc<T>;

	/// Tries to convert an `Arc<T>` into an `Rc<T>`.
	///
	/// See [`to_local()`].
	///
	/// [`to_local()`]: HybridRc::to_local
	#[inline]
	fn try_from(src: Arc<T>) -> Result<Self, Self::Error> {
		match HybridRc::to_local(&src) {
			Some(result) => Ok(result),
			None => Err(src),
		}
	}
}

impl<T, State: RcState, const N: usize> TryFrom<HybridRc<[T], State>> for HybridRc<[T; N], State> {
	type Error = HybridRc<[T], State>;

	/// Tries to convert a `HybridRc<[T], State>` into a `HybridRc<[T; N], State>`
	///
	/// Only succeeds if the length matches exactly.
	#[inline]
	fn try_from(src: HybridRc<[T], State>) -> Result<Self, Self::Error> {
		if src.len() == N {
			let ptr = src.ptr.as_ptr().cast();
			mem::forget(src);
			Ok(Self::from_inner(unsafe { NonNull::new_unchecked(ptr) }))
		} else {
			Err(src)
		}
	}
}

// Conversions into HybridRc

impl<T, State: RcState> From<T> for HybridRc<T, State> {
	/// Moves a `T` into an `HybridRc<T, State>`
	///
	/// Equivalent to calling [`HybridRc::new(src)`].
	///
	/// [`HybridRc::new(t)`]: Self::new
	#[inline]
	fn from(src: T) -> Self {
		Self::new(src)
	}
}

impl<T: Clone, State: RcState> From<&[T]> for HybridRc<[T], State> {
	/// Allocate a reference-counted slice and clone the elements of `src` into it.
	///
	/// # Example
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let vecs = [
	/// 	vec![1,2,3],
	/// 	vec![4,5,6],
	/// ];
	/// let rc: Rc<[_]> = Rc::from(&vecs[..]);
	/// assert_eq!(&rc[..], &vecs);
	/// ```
	#[inline]
	fn from(src: &[T]) -> Self {
		let mut builder = SliceBuilder::new(Self::build_new_meta(), src.len());
		for item in src {
			builder.append(Clone::clone(item));
		}
		Self::from_inner(builder.finish().into())
	}
}

impl<T, State: RcState> From<Vec<T>> for HybridRc<[T], State> {
	/// Allocate a reference-counted slice and move `src`'s items into it.
	///
	/// # Example
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let vec = vec!["a","b","c"];
	/// let rc: Rc<[_]> = Rc::from(vec);
	/// assert_eq!(&rc[..], &["a", "b", "c"]);
	/// ```
	#[inline]
	fn from(mut src: Vec<T>) -> Self {
		unsafe {
			let result = HybridRc::<_, State>::copy_from_slice_unchecked(&src[..]);

			// Set the length of `src`, so that the moved items are not dropped.
			src.set_len(0);

			result
		}
	}
}

impl<State: RcState> From<&str> for HybridRc<str, State> {
	/// Allocate a reference-counted `str` and copy `src` into it.
	///
	/// # Example
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let a: Rc<str> = Rc::from("foobar");
	/// assert_eq!(&a[..], "foobar");
	/// ```
	#[inline]
	fn from(src: &str) -> Self {
		let bytes = HybridRc::<_, State>::copy_from_slice(src.as_bytes());
		let inner = unsafe { (bytes.ptr.as_ptr() as *mut _ as *mut RcBox<str>).as_mut() }.unwrap();
		mem::forget(bytes);
		Self::from_inner(inner.into())
	}
}

impl<State: RcState> From<String> for HybridRc<str, State> {
	/// Allocate a reference-counted `str` and copy `src` into it.
	///
	/// # Example
	///
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let string: String = "foobar".to_owned();
	/// let a: Rc<str> = Rc::from(string);
	/// assert_eq!(&a[..], "foobar");
	/// ```
	#[inline]
	fn from(src: String) -> Self {
		Self::from(&src[..])
	}
}

impl<'a, T: ToOwned + ?Sized, State: RcState> From<Cow<'a, T>> for HybridRc<T, State>
where
	HybridRc<T, State>: From<&'a T> + From<T::Owned>,
{
	/// Creates a new `HybridRc<T, State>` from a clone-on-write pointer by copying its content.
	///
	/// # Example
	///
	/// ```rust
	/// use hybrid_rc::Rc;
	/// use std::borrow::Cow;
	///
	/// let cow: Cow<str> = Cow::Borrowed("foobar");
	/// let a: Rc<str> = Rc::from(cow);
	/// assert_eq!(&a[..], "foobar");
	/// ```
	#[inline]
	fn from(src: Cow<'a, T>) -> HybridRc<T, State> {
		match src {
			Cow::Borrowed(value) => HybridRc::from(value),
			Cow::Owned(value) => HybridRc::from(value),
		}
	}
}

// Propagate some useful traits implemented by the inner type

impl<T: Default, State: RcState> Default for HybridRc<T, State> {
	/// Creates a new `HybridRc`, with the `Default` value for `T`.
	#[inline]
	fn default() -> Self {
		Self::new(Default::default())
	}
}

impl<T: ?Sized + PartialEq, S1: RcState, S2: RcState> PartialEq<HybridRc<T, S2>>
	for HybridRc<T, S1>
{
	/// Equality for `HybridRc`s.
	///
	/// Two `HybridRc`s are equal if their inner values are equal, independent of if they are
	/// stored in the same allocation.
	#[inline]
	fn eq(&self, other: &HybridRc<T, S2>) -> bool {
		**self == **other
	}
}

impl<T: ?Sized + Eq, State: RcState> Eq for HybridRc<T, State> {}

impl<T: ?Sized + Hash, State: RcState> Hash for HybridRc<T, State> {
	#[inline]
	fn hash<H: Hasher>(&self, state: &mut H) {
		Self::data(self).hash(state);
	}
}

impl<T: ?Sized + PartialOrd, S1: RcState, S2: RcState> PartialOrd<HybridRc<T, S2>>
	for HybridRc<T, S1>
{
	/// Partial comparison for `HybridRc`s.
	///
	/// The two are compared by calling `partial_cmp()` on their inner values.
	#[inline]
	fn partial_cmp(&self, other: &HybridRc<T, S2>) -> Option<cmp::Ordering> {
		(**self).partial_cmp(&**other)
	}
}

impl<T: ?Sized + Ord, State: RcState> Ord for HybridRc<T, State> {
	/// Comparison for `HybridRc`s.
	///
	/// The two are compared by calling `cmp()` on their inner values.
	#[inline]
	fn cmp(&self, other: &Self) -> cmp::Ordering {
		(**self).cmp(&**other)
	}
}

impl<T: ?Sized + fmt::Display, State: RcState> fmt::Display for HybridRc<T, State> {
	#[inline]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Display::fmt(&Self::data(self), f)
	}
}

impl<T: ?Sized + fmt::Debug, State: RcState> fmt::Debug for HybridRc<T, State> {
	#[inline]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Debug::fmt(&Self::data(self), f)
	}
}

// `HybridRc` can be formatted as a pointer.
impl<T: ?Sized, State: RcState> fmt::Pointer for HybridRc<T, State> {
	/// Formats the value using the given formatter.
	///
	/// If the `#` flag is used, the state (shared/local) is written after the address.
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if f.alternate() {
			fmt::Pointer::fmt(&Self::as_ptr(self), f)?;
			f.write_str(if State::SHARED {
				" [shared]"
			} else {
				" [local]"
			})
		} else {
			fmt::Pointer::fmt(&Self::as_ptr(self), f)
		}
	}
}

/// `Weak<T>` represents a non-owning reference to a value managed by a [`HybridRc<T, _>`].
/// The value is accessed by calling [`upgrade()`] or [`upgrade_local()`] on `Weak`.
///
/// `Weak` references are typically used to prevent circular references that would keep
/// the shared value alive indefinitely.
///
/// The typical way to obtain a `Weak<T>` is to call [`HybridRc::downgrade()`].
///
/// [`upgrade()`]: Weak::upgrade
/// [`upgrade_local()`]: Weak::upgrade_local
#[must_use]
pub struct Weak<T: ?Sized> {
	ptr: NonNull<RcBox<T>>,
}

impl<T: ?Sized> Weak<T> {
	/// Accesses the metadata area of the shared allocation.
	///
	/// `None` for instances created through `Weak::new()`.
	#[inline]
	fn meta(&self) -> Option<&RcMeta> {
		if is_senitel(self.ptr.as_ptr()) {
			None
		} else {
			// Safety: as long as one Rc or Weak
			// for this item exists, the memory stays
			// allocated.
			Some(unsafe { &(*self.ptr.as_ptr()).meta })
		}
	}

	/// Returns a raw pointer to the value referenced by this `Weak<T>`.
	///
	/// The pointer is valid only if there are some strong references. It may be dangling,
	/// unaligned or even null otherwise.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::Rc;
	///
	/// let strong = Rc::new(42i32);
	/// let weak = Rc::downgrade(&strong);
	/// {
	/// 	let pointer = weak.as_ptr();
	/// 	// As long as strong is not dropped, the pointer stays valid
	/// 	assert_eq!(42, unsafe { *pointer });
	/// }
	/// drop(strong);
	/// {
	/// 	// Calling weak.as_ptr() is still safe, but dereferencing it would lead
	/// 	// to undefined behaviour.
	/// 	let pointer = weak.as_ptr();
	/// 	// assert_eq!(42, unsafe { &*pointer }); // undefined behaviour
	/// }
	#[must_use]
	#[inline]
	pub fn as_ptr(&self) -> *const T {
		let ptr: *mut RcBox<T> = self.ptr.as_ptr();

		if is_senitel(ptr) {
			// If the pointer is dangling, we return the sentinel directly. This cannot be
			// a valid payload address, as the payload is at least as aligned as ArcInner (usize).
			ptr as *const T
		} else {
			// Safety: raw pointer manipulation like in sync::Weak, as the payload may have been
			// dropped at this point and to keep provenance.
			unsafe { ptr::addr_of_mut!((*ptr).data) }
		}
	}

	/// Attempts to upgrade the Weak pointer to an [`Rc`].
	///
	/// **Note:** Only one thread can have `Rc`s for a value at any point in time.
	/// See [`upgrade()`] to upgrade to an [`Arc`].
	///
	/// In `no_std` environments this will only succeed if no `Rc` exists on *any* thread.
	///
	/// # Errors
	/// - [`ValueDropped`]: the referenced value has already been dropped.
	/// - [`WrongThread`]: another thread currently holds `Rc`s for the value.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::{Arc, Rc, Weak, UpgradeError};
	/// # fn main() -> Result<(), UpgradeError> {
	/// let strong = Arc::new(42i32);
	/// let weak = Arc::downgrade(&strong);
	///
	/// {
	/// 	let strong2 = weak.upgrade_local()?;
	/// 	assert_eq!(Arc::as_ptr(&strong), Rc::as_ptr(&strong2));
	/// }
	///
	/// std::mem::drop(strong);
	///
	/// let error = Weak::upgrade_local(&weak).unwrap_err();
	/// assert_eq!(error, UpgradeError::ValueDropped);
	/// # Ok(())
	/// # }
	/// ```
	///
	/// [`upgrade()`]: Weak::upgrade
	/// [`ValueDropped`]: UpgradeError::ValueDropped
	/// [`WrongThread`]: UpgradeError::WrongThread
	#[inline]
	pub fn upgrade_local(&self) -> Result<Rc<T>, UpgradeError> {
		let meta = self.meta().ok_or(UpgradeError::ValueDropped)?;
		let current_thread = ThreadId::current_thread();

		let owner = match meta.owner.store_if_none(
			Some(current_thread),
			Ordering::Acquire,
			Ordering::Relaxed,
		) {
			Ok(_) => None,
			Err(owner) => owner,
		};

		if owner == None || owner == Some(current_thread) {
			if meta.try_inc_strong_local().is_ok() {
				Ok(HybridRc::<T, Local>::from_inner(self.ptr))
			} else {
				meta.owner.store(None, Ordering::Relaxed);
				Err(UpgradeError::ValueDropped)
			}
		} else {
			Err(UpgradeError::WrongThread)
		}
	}

	/// Attempts to upgrade the Weak pointer to an [`Arc`].
	///
	/// Also see [`upgrade_local()`] to upgrade to an [`Rc`].
	///
	/// # Errors
	/// - [`ValueDropped`]: the referenced value has already been dropped.
	///
	/// [`upgrade_local()`]: Weak::upgrade_local
	/// [`ValueDropped`]: UpgradeError::ValueDropped
	#[inline]
	pub fn upgrade(&self) -> Result<Arc<T>, UpgradeError> {
		let meta = self.meta().ok_or(UpgradeError::ValueDropped)?;
		meta.try_inc_strong_shared()
			.map_err(|_| UpgradeError::ValueDropped)?;
		Ok(HybridRc::<T, Shared>::from_inner(self.ptr))
	}

	/// Gets a lower bound to the number of strong pointers to the inner value.
	///
	/// If `self` was created using [`Weak::new`], this will return 0.
	///
	/// Please understand that another thread might change the count at any time, including
	/// potentially between calling this method and acting on the result.
	///
	/// # Examples
	///
	/// ```
	/// use hybrid_rc::{Arc, Rc, Weak};
	///
	/// let reference = Rc::new(42);
	/// let _2nd_ref = Rc::clone(&reference);
	/// let shared_ref = Rc::to_shared(&reference);
	/// let _2nd_shared_ref = Arc::clone(&shared_ref);
	/// let weak = Rc::downgrade(&reference);
	///
	/// // shared_ref only knows the count of shared references and that there is at least one
	/// // local reference, so it will show 3 instead of 4:
	/// assert_eq!(Weak::strong_count(&weak), 3);
	/// ```
	#[inline]
	pub fn strong_count(&self) -> usize {
		if let Some(meta) = self.meta() {
			meta.strong_shared.load(Ordering::SeqCst)
		} else {
			0
		}
	}

	/// Gets the number of [`Weak`] pointers to this allocation.
	///
	/// Please understand that another thread may change the count at any time, including
	/// potentially between calling this method and acting on the result. Also there might by
	/// off-by-one errors when other threads concurrently upgrade or downgrade pointers.
	///
	/// # Examples
	///
	/// ```
	/// use hybrid_rc::{Rc, Weak};
	///
	/// let reference = Rc::new(42);
	/// let weak = Rc::downgrade(&reference);
	/// let _weak_2 = weak.clone();
	///
	/// assert_eq!(Weak::weak_count(&weak), 2);
	/// ```
	#[inline]
	pub fn weak_count(&self) -> usize {
		if let Some(meta) = self.meta() {
			let weak = meta.weak.load(Ordering::SeqCst);
			if weak == usize::MAX {
				0
			} else if meta.strong_shared.load(Ordering::SeqCst) > 0 {
				weak - 1
			} else {
				weak
			}
		} else {
			0
		}
	}
}

impl<T> Weak<T> {
	/// Constructs a dummy `Weak<T>`, without allocating any memory.
	///
	/// Trying to upgrade the result will always result in a [`ValueDropped`] error.
	///
	/// [`ValueDropped`]: UpgradeError::ValueDropped
	pub fn new() -> Weak<T> {
		Weak { ptr: senitel() }
	}
}

impl<T: ?Sized> fmt::Debug for Weak<T> {
	#[inline]
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "(Weak)")
	}
}

impl<T: ?Sized> fmt::Pointer for Weak<T> {
	/// Formats the value using the given formatter.
	///
	/// If the `#` flag is used, the state (weak) is written after the address.
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if f.alternate() {
			fmt::Pointer::fmt(&Self::as_ptr(self), f)?;
			f.write_str(" [weak]")
		} else {
			fmt::Pointer::fmt(&Self::as_ptr(self), f)
		}
	}
}

impl<T> Default for Weak<T> {
	/// Constructs a dummy `Weak<T>`, without allocating any memory.
	///
	/// See [`Weak<T>::new()`].
	#[inline]
	fn default() -> Self {
		Self::new()
	}
}

impl<T: ?Sized> Clone for Weak<T> {
	/// Creates another `Weak` reference for the same value.
	///
	/// # Example
	/// ```
	/// use hybrid_rc::{Rc, Weak};
	///
	/// let strong = Rc::new(42i32);
	/// let weak = Rc::downgrade(&strong);
	/// let weak2 = Weak::clone(&weak);
	///
	/// assert_eq!(weak.as_ptr(), weak2.as_ptr());
	/// ```
	#[inline]
	fn clone(&self) -> Self {
		if let Some(meta) = self.meta() {
			// We can ignore the lock in Weak::clone() as the counter is only locked by HybridRc
			// when there are no Weak instances/ (meta.weak == 1).
			meta.inc_weak_nolock();
		}
		Self { ptr: self.ptr }
	}
}

impl<T: ?Sized> Drop for Weak<T> {
	/// Drops the `Weak` reference.
	///
	/// Once all `HybridRc` and `Weak` references to a shared value are dropped, the shared
	/// allocation is fully released.
	#[inline]
	fn drop(&mut self) {
		if let Some(meta) = self.meta() {
			let last_reference = meta.dec_weak();
			if last_reference {
				unsafe {
					// Safety: only called if this was the last (weak) reference
					RcBox::dealloc(self.ptr);
				}
			}
		}
	}
}

// Safety: Like for Arc<T> T: Send + Sync gives all guarantees we need to make Weak Send + Sync.
unsafe impl<T: ?Sized + Sync + Send> Send for Weak<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}