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
use core::fmt::{self, Display, Debug, Pointer, Formatter};
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::mem;
use core::ptr::{self, NonNull};
use core::sync::atomic::{self, AtomicUsize};
use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};
use crate::block::{self, Block, Layout};
use crate::alloc::{AllocTag, Hold, Holder, HoldError, Stow, TryClone};
use crate::lease::{arc, ArcHeader, ArcError, Lease, Mut, Ref, Soft};
use crate::resident::{Resident, ResidentFromValue, ResidentFromClone,
                      ResidentFromCloneUnchecked, ResidentFromCopy,
                      ResidentFromCopyUnchecked, ResidentFromEmpty,
                      ResidentWithCapacity, ResidentUnwrap, ResidentHash,
                      ResidentDisplay, ResidentDebug, ResidentStow};

/// A thread-safe, atomically counted, undereferenceable hard reference to a
/// `Resident` occuping a shared, `Hold`-allocated memory block.
pub struct Hard<'a, R: Resident> {
    /// Pointer to the resident memory block.
    data: NonNull<R::Data>,
    /// Variant over R::Data, with drop check.
    data_lifetime: PhantomData<R::Data>,
    /// Variant over ArcHeader<R::Meta>, with drop check.
    meta_lifetime: PhantomData<ArcHeader<R::Meta>>,
    /// Variant over 'a.
    hold_lifetime: PhantomData<&'a ()>,
}

unsafe impl<'a, R: Resident> Send for Hard<'a, R> where R::Data: Send, R::Meta: Send {
}

unsafe impl<'a, R: Resident> Sync for Hard<'a, R> where R::Data: Sync, R::Meta: Sync {
}

impl<'a, R: Resident> Hard<'a, R> {
    #[inline]
    pub fn try_hold_new_meta<T, M>(hold: &dyn Hold<'a>, data: T, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromValue<Hard<'a, R>, T, M>
    {
        unsafe {
            // Allocate a new arc structure.
            let resident = arc::alloc_new::<R, Hard<'a, R>, T, M>(hold, &data, &meta, arc::HARD_STATUS_INIT)?;
            // Construct a new Hard lease.
            let mut lease = Hard::from_raw(resident);
            // Initialize the new resident.
            R::new_resident(&mut lease, data, meta);
            // Return the new lease.
            Ok(lease)
        }
    }

    #[inline]
    pub fn try_hold_clone_meta<T: ?Sized, M>(hold: &dyn Hold<'a>, data: &T, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromClone<Hard<'a, R>, T, M>
    {
        unsafe {
            // Allocate a new arc structure.
            let resident = arc::alloc_clone::<R, Hard<'a, R>, T, M>(hold, &data, &meta, arc::HARD_STATUS_INIT)?;
            // Construct a new Hard lease.
            let mut lease = Hard::from_raw(resident);
            // Initialize the new resident.
            R::new_resident(&mut lease, data, meta);
            // Return the new lease.
            Ok(lease)
        }
    }

    #[inline]
    pub unsafe fn try_hold_clone_unchecked_meta<T: ?Sized, M>(hold: &dyn Hold<'a>, data: &T, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromCloneUnchecked<Hard<'a, R>, T, M>
    {
        // Allocate a new arc structure.
        let resident = arc::alloc_clone_unchecked::<R, Hard<'a, R>, T, M>(hold, &data, &meta, arc::HARD_STATUS_INIT)?;
        // Construct a new Hard lease.
        let mut lease = Hard::from_raw(resident);
        // Initialize the new resident.
        R::new_resident(&mut lease, data, meta);
        // Return the new lease.
        Ok(lease)
    }

    #[inline]
    pub fn try_hold_copy_meta<T: ?Sized, M>(hold: &dyn Hold<'a>, data: &T, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromCopy<Hard<'a, R>, T, M>
    {
        unsafe {
            // Allocate a new arc structure.
            let resident = arc::alloc_copy::<R, Hard<'a, R>, T, M>(hold, &data, &meta, arc::HARD_STATUS_INIT)?;
            // Construct a new Hard lease.
            let mut lease = Hard::from_raw(resident);
            // Initialize the new resident.
            R::new_resident(&mut lease, data, meta);
            // Return the new lease.
            Ok(lease)
        }
    }

    #[inline]
    pub unsafe fn try_hold_copy_unchecked_meta<T: ?Sized, M>(hold: &dyn Hold<'a>, data: &T, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromCopyUnchecked<Hard<'a, R>, T, M>
    {
        // Allocate a new arc structure.
        let resident = arc::alloc_copy_unchecked::<R, Hard<'a, R>, T, M>(hold, &data, &meta, arc::HARD_STATUS_INIT)?;
        // Construct a new Hard lease.
        let mut lease = Hard::from_raw(resident);
        // Initialize the new resident.
        R::new_resident(&mut lease, data, meta);
        // Return the new lease.
        Ok(lease)
    }

    #[inline]
    pub fn try_hold_empty_meta<M>(hold: &dyn Hold<'a>, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromEmpty<Hard<'a, R>, M>
    {
        unsafe {
            // Allocate a new arc structure.
            let resident = arc::alloc_empty::<R, Hard<'a, R>, M>(hold, &meta, arc::HARD_STATUS_INIT)?;
            // Construct a new Hard lease.
            let mut lease = Hard::from_raw(resident);
            // Initialize the new resident.
            R::new_resident(&mut lease, meta);
            // Return the new lease.
            Ok(lease)
        }
    }

    #[inline]
    pub fn try_hold_cap_meta<M>(hold: &dyn Hold<'a>, cap: usize, meta: M)
        -> Result<Hard<'a, R>, HoldError>
        where R: ResidentWithCapacity<Hard<'a, R>, M>
    {
        unsafe {
            // Allocate a new arc structure.
            let resident = arc::alloc_cap::<R, Hard<'a, R>, M>(hold, cap, &meta, arc::HARD_STATUS_INIT)?;
            // Construct a new Hard lease.
            let mut lease = Hard::from_raw(resident);
            // Initialize the new resident.
            R::new_resident(&mut lease, cap, meta);
            // Return the new lease.
            Ok(lease)
        }
    }

    #[inline]
    pub fn try_hold_new<T>(hold: &dyn Hold<'a>, data: T) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromValue<Hard<'a, R>, T>
    {
        Hard::try_hold_new_meta(hold, data, ())
    }

    #[inline]
    pub fn try_hold_clone<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromClone<Hard<'a, R>, T>
    {
        Hard::try_hold_clone_meta(hold, data, ())
    }

    #[inline]
    pub unsafe fn try_hold_clone_unchecked<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromCloneUnchecked<Hard<'a, R>, T>
    {
        Hard::try_hold_clone_unchecked_meta(hold, data, ())
    }

    #[inline]
    pub fn try_hold_copy<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromCopy<Hard<'a, R>, T>
    {
        Hard::try_hold_copy_meta(hold, data, ())
    }

    #[inline]
    pub unsafe fn try_hold_copy_unchecked<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromCopyUnchecked<Hard<'a, R>, T>
    {
        Hard::try_hold_copy_unchecked_meta(hold, data, ())
    }

    #[inline]
    pub fn try_hold_empty(hold: &dyn Hold<'a>) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentFromEmpty<Hard<'a, R>>
    {
        Hard::try_hold_empty_meta(hold, ())
    }

    #[inline]
    pub fn try_hold_cap(hold: &dyn Hold<'a>, cap: usize) -> Result<Hard<'a, R>, HoldError>
        where R: ResidentWithCapacity<Hard<'a, R>>
    {
        Hard::try_hold_cap_meta(hold, cap, ())
    }

    #[inline]
    pub fn hold_new<T>(hold: &dyn Hold<'a>, data: T) -> Hard<'a, R>
        where R: ResidentFromValue<Hard<'a, R>, T>
    {
        Hard::try_hold_new(hold, data).unwrap()
    }

    #[inline]
    pub fn hold_clone<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Hard<'a, R>
        where R: ResidentFromClone<Hard<'a, R>, T>
    {
        Hard::try_hold_clone(hold, data).unwrap()
    }

    #[inline]
    pub unsafe fn hold_clone_unchecked<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Hard<'a, R>
        where R: ResidentFromCloneUnchecked<Hard<'a, R>, T>
    {
        Hard::try_hold_clone_unchecked(hold, data).unwrap()
    }

    #[inline]
    pub fn hold_copy<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Hard<'a, R>
        where R: ResidentFromCopy<Hard<'a, R>, T>
    {
        Hard::try_hold_copy(hold, data).unwrap()
    }

    #[inline]
    pub unsafe fn hold_copy_unchecked<T: ?Sized>(hold: &dyn Hold<'a>, data: &T) -> Hard<'a, R>
        where R: ResidentFromCopyUnchecked<Hard<'a, R>, T>
    {
        Hard::try_hold_copy_unchecked(hold, data).unwrap()
    }

    #[inline]
    pub fn hold_empty(hold: &dyn Hold<'a>) -> Hard<'a, R>
        where R: ResidentFromEmpty<Hard<'a, R>>
    {
        Hard::try_hold_empty(hold).unwrap()
    }

    #[inline]
    pub fn hold_cap(hold: &dyn Hold<'a>, cap: usize) -> Hard<'a, R>
        where R: ResidentWithCapacity<Hard<'a, R>>
    {
        Hard::try_hold_cap(hold, cap).unwrap()
    }

    #[inline]
    pub fn new<T>(data: T) -> Hard<'a, R>
        where R: ResidentFromValue<Hard<'a, R>, T>
    {
        Hard::hold_new(Hold::global(), data)
    }

    #[inline]
    pub fn from_clone<T: ?Sized>(data: &T) -> Hard<'a, R>
        where R: ResidentFromClone<Hard<'a, R>, T>
    {
        Hard::hold_clone(Hold::global(), data)
    }

    #[inline]
    pub unsafe fn from_clone_unchecked<T: ?Sized>(data: &T) -> Hard<'a, R>
        where R: ResidentFromCloneUnchecked<Hard<'a, R>, T>
    {
        Hard::hold_clone_unchecked(Hold::global(), data)
    }

    #[inline]
    pub fn from_copy<T: ?Sized>(data: &T) -> Hard<'a, R>
        where R: ResidentFromCopy<Hard<'a, R>, T>
    {
        Hard::hold_copy(Hold::global(), data)
    }

    #[inline]
    pub unsafe fn from_copy_unchecked<T: ?Sized>(data: &T) -> Hard<'a, R>
        where R: ResidentFromCopyUnchecked<Hard<'a, R>, T>
    {
        Hard::hold_copy_unchecked(Hold::global(), data)
    }

    #[inline]
    pub fn empty() -> Hard<'a, R>
        where R: ResidentFromEmpty<Hard<'a, R>>
    {
        Hard::hold_empty(Hold::global())
    }

    #[inline]
    pub fn with_cap(cap: usize) -> Hard<'a, R>
        where R: ResidentWithCapacity<Hard<'a, R>>
    {
        Hard::hold_cap(Hold::global(), cap)
    }

    /// Constructs a `Hard` lease from a raw pointer returned by `Hard::into_raw`.
    #[inline]
    pub unsafe fn from_raw(data: *mut R::Data) -> Hard<'a, R> {
        Hard {
            data: NonNull::new_unchecked(data),
            data_lifetime: PhantomData,
            meta_lifetime: PhantomData,
            hold_lifetime: PhantomData,
        }
    }

    /// Returns a pointer to the `ArcHeader` preceding the shared resident.
    #[inline]
    fn header(&self) -> *mut ArcHeader<R::Meta> {
        arc::header::<R>(self.data.as_ptr())
    }

    /// Returns the number of hard references to the shared resident.
    /// Does not traverse relocations.
    #[inline]
    pub fn hard_count(&self) -> usize {
        unsafe { (*self.header()).hard_count() }
    }

    /// Returns the number of soft references to the shared resident.
    /// Does not traverse relocations.
    #[inline]
    pub fn soft_count(&self) -> usize {
        unsafe { (*self.header()).soft_count() }
    }

    /// Returns the number of immutable references to the shared resident.
    /// Does not traverse relocations.
    #[inline]
    pub fn ref_count(&self) -> usize {
        unsafe { (*self.header()).ref_count() }
    }

    /// Returns `true` if the shared resident is mutably referenced.
    /// Does not traverse relocations.
    #[inline]
    pub fn is_mut(&self) -> bool {
        unsafe { (*self.header()).is_mut() }
    }

    /// Returns `true` if the shared resident has relocated to a new arc.
    #[inline]
    pub fn is_relocated(&self) -> bool {
        unsafe { (*self.header()).is_relocated() }
    }

    /// Returns `true` if the shared resident is immutably or mutably referenced.
    /// Does not traverse relocations.
    #[inline]
    pub fn is_aliased(&self) -> bool {
        unsafe { (*self.header()).is_aliased() }
    }

    /// Returns a mutable lease to the resident, traversing any completed
    /// relocations, cloning the resident if there are any outstanding leases,
    /// and returning an error if there is an outstanding mutable lease, if
    /// the resident is currently being relocated, or on allocation failure.
    pub fn poll_unique(&self) -> Result<Mut<'a, R>, ArcError>
        where R::Data: TryClone,
              R::Meta: TryClone,
    {
        unsafe {
            // Get a pointer to the shared resident.
            let mut data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let mut header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Check if unique, and traverse relocations.
            loop {
                // Check if the resident is uniquely referenced.
                if old_status == arc::UNIQUE_STATUS {
                    // Set the mut flag in the status field.
                    let new_status = old_status | arc::MUT_FLAG;
                    // Atomically update the status field, synchronizing with reference releases.
                    match (*header).status.compare_exchange(old_status, new_status, Acquire, Relaxed) {
                        // CAS succeeded; return a new mutable lease.
                        Ok(_) => return Ok(Mut::from_raw(data)),
                        // CAS failed.
                        Err(_) => (),
                    }
                } else if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Recurse into the relocated lease.
                        data = relocation;
                        // Get a pointer to the relocated header.
                        header = arc::header::<R>(data);
                        // Reload the status field.
                        old_status = (*header).status.load(Relaxed);
                        // Try to make the relocated resident unique.
                        continue;
                    }
                } else {
                    // Temporarily reify the arc's relocation lease.
                    let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(data);
                    // Get an immutable lease to the relocated resident.
                    let lease = relocation.poll_ref();
                    // Discard the borrowed relocation lease.
                    mem::forget(relocation);
                    // Make the relocated lease unique, and return it.
                    return Ref::try_into_unique(lease?);
                }
                // Unable to acquire a mutable lease at this time.
                return Err(ArcError::Contended);
            }
        }
    }

    /// Returns a mutable lease to the resident, traversing any completed
    /// relocations, waiting for any concurrent relocation to complete,
    /// cloning the resident if there are any outstanding leases, and
    /// returning an error on allocation failure or hard refcount overflow.
    pub fn try_to_unique(&self) -> Result<Mut<'a, R>, ArcError>
        where R::Data: TryClone,
              R::Meta: TryClone,
    {
        unsafe {
            // Get a pointer to the shared resident.
            let mut data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let mut header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Check if unique, and traverse relocations.
            loop {
                // Check if the resident is uniquely referenced.
                if old_status == arc::UNIQUE_STATUS {
                    // Extract the hard reference count from the status field.
                    let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                    // Increment the hard reference count.
                    let new_hard_count = old_hard_count.wrapping_add(1);
                    // Check if the incremented hard reference count overflows its bit field.
                    if new_hard_count > arc::HARD_COUNT_MAX {
                        return Err(ArcError::HardCountOverflow);
                    }
                    // Clear the hard reference count bit field.
                    let new_status = old_status & !arc::HARD_COUNT_MASK;
                    // Splice the incremented hard reference count into the status field, and set the mut flag.
                    let new_status = new_status | new_hard_count | arc::MUT_FLAG;
                    // Atomically update the status field, synchronizing with reference releases.
                    match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                        // CAS succeeded; return a new mutable lease.
                        Ok(_) => return Ok(Mut::from_raw(data)),
                        // CAS failed; update the status field and try again.
                        Err(status) => old_status = status,
                    }
                } else if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Recurse into the relocated lease.
                        data = relocation;
                        // Get a pointer to the relocated header.
                        header = arc::header::<R>(data);
                    }
                    // Reload the status field and spin.
                    old_status = (*header).status.load(Relaxed);
                } else {
                    // Temporarily reify the arc's relocation lease.
                    let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(data);
                    // Get an immutable lease to the relocated resident.
                    let lease = relocation.poll_ref();
                    // Discard the borrowed relocation lease.
                    mem::forget(relocation);
                    // Make the relocated lease unique, and return it.
                    return Ref::try_into_unique(lease?);
                }
            }
        }
    }

    /// Returns a mutable lease to the resident, traversing any completed
    /// relocations, waiting for any concurrent relocation to complete,
    /// and cloning the resident if there are any outstanding leases.
    ///
    /// # Panics
    ///
    /// Panics on allocation failure or hard refcount overflow.
    pub fn to_unique(&self) -> Mut<'a, R>
        where R::Data: TryClone,
              R::Meta: TryClone,
    {
        self.try_to_unique().unwrap()
    }

    /// Converts this hard lease into a mutable lease to the resident,
    /// traversing any completed relocations, waiting for any concurrent
    /// relocations to complete, cloning the resident if there are any
    /// outstanding leases, and returning an error on allocation failure.
    ///
    /// # Panics
    ///
    /// Panics if the incremented hard reference count overflows `HARD_COUNT_MAX`,
    /// or if the incremented reference count overflows `REF_COUNT_MAX`.
    pub fn try_into_unique(mut self) -> Result<Mut<'a, R>, ArcError>
        where R::Data: TryClone,
              R::Meta: TryClone,
    {
        unsafe {
            // Get a pointer to the shared resident.
            let mut data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let mut header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Check if unique, and traverse relocations.
            loop {
                // Check if the resident is uniquely referenced.
                if old_status == arc::UNIQUE_STATUS {
                    // Set the mut flag in the status field.
                    let new_status = old_status | arc::MUT_FLAG;
                    // Atomically update the status field, synchronizing with reference releases.
                    match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                        // CAS succeeded; return a new mutable lease.
                        Ok(_) => return Ok(Mut::from_raw(data)),
                        // CAS failed; update the status field and try again.
                        Err(status) => old_status = status,
                    }
                } else if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Temporarily reify the arc's relocation lease.
                        let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(data);
                        // Recurse into the relocated lease.
                        self = relocation.clone();
                        // Discard the borrowed relocation lease.
                        mem::forget(relocation);
                        // Get a pointer to the relocated resident.
                        data = self.data.as_ptr();
                        // Get a pointer to the relocated header.
                        header = arc::header::<R>(data);
                    }
                    // Reload the status field and spin.
                    old_status = (*header).status.load(Relaxed);
                } else {
                    // Get an immutable lease to the resident, bailing on failure.
                    let lease = self.into_ref();
                    // Make the immutable lease unique, and return it.
                    return Ref::try_into_unique(lease);
                }
            }
        }
    }

    /// Converts this hard lease into a mutable lease to the resident,
    /// traversing any completed relocations, waiting for any concurrent
    /// relocations to complete, and cloning the resident if there are any
    /// outstanding leases.
    ///
    /// # Panics
    ///
    /// Panics on allocation failure.
    pub fn into_unique(self) -> Mut<'a, R>
        where R::Data: TryClone,
              R::Meta: TryClone,
    {
        self.try_into_unique().unwrap()
    }

    /// Returns a new mutable lease to the shared resident, traversing any
    /// complered relocations, and returning an error if the resident is
    /// currently being relocated, if there is an outstanding mutable lease,
    /// or if there is atomic operation contention.
    ///
    /// # Safety
    ///
    /// Mutable leases can coexist with hard and soft leases to the same
    /// resident. This can cause a future deadlock if a thread holding a
    /// mutable lease to a resident attempts to convert another hard or soft
    /// lease to the same resident into a mutable or immutable lease.
    pub unsafe fn poll_mut(&self) -> Result<Mut<'a, R>, ArcError> {
        // Get a pointer to the shared resident.
        let mut data = self.data.as_ptr();
        // Get a pointer to the arc header preceding the resident.
        let mut header = arc::header::<R>(data);
        // Load the status field; synchronized by subsequent CAS.
        let mut old_status = (*header).status.load(Relaxed);
        // Traverse relocations.
        loop {
            // Check if the shared resident can be mutably referenced.
            if old_status & arc::READ_LOCKED_MASK == 0 {
                // Set the mut flag in the status field.
                let new_status = old_status | arc::MUT_FLAG;
                // Atomically update the status field, synchronizing with reference releases.
                match (*header).status.compare_exchange(old_status, new_status, Acquire, Relaxed) {
                    // CAS succeeded; return a new mutable lease.
                    Ok(_) => return Ok(Mut::from_raw(data)),
                    // CAS failed.
                    Err(_) => return Err(ArcError::Contended),
                }
            } else if old_status & arc::RELOCATED_FLAG != 0 {
                // Synchronize with relocation initiation.
                atomic::fence(Release);
                // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                // Check if the relocation has completed.
                if !relocation.is_null() {
                    // Recurse into the relocated lease.
                    data = relocation;
                    // Get a pointer to the relocated header.
                    header = arc::header::<R>(data);
                    // Load the relocated status field and repeat.
                    old_status = (*header).status.load(Relaxed);
                } else {
                    return Err(ArcError::Relocating);
                }
            } else {
                return Err(ArcError::Aliased);
            }
        }
    }

    /// Returns a new mutable lease to the shared resident, traversing any
    /// completed relocations, waiting for any concurrent relocation to
    /// complete and for any outstanding mutable or immutable leases to drop,
    /// and returning an error if the incremented hard reference count
    /// overflows `HARD_COUNT_MAX`.
    ///
    /// # Safety
    ///
    /// Deadlocks if the current thread already holds a mutable or immutable
    /// lease to the shared resident. Can cause a future deadlock if a thread
    /// holding a mutable lease to a resident attempts to convert another hard
    /// or soft lease to the same resident into a mutable or immutable lease.
    pub unsafe fn try_to_mut(&self) -> Result<Mut<'a, R>, ArcError> {
        // Get a pointer to the shared resident.
        let mut data = self.data.as_ptr();
        // Get a pointer to the arc header preceding the resident.
        let mut header = arc::header::<R>(data);
        // Load the status field; synchronized by subsequent CAS.
        let mut old_status = (*header).status.load(Relaxed);
        // Traverse relocations, and spin until a mutable reference is acquired.
        loop {
            // Check if the shared resident can be mutably referenced.
            if old_status & arc::READ_LOCKED_MASK == 0 {
                // Extract the hard reference count from the status field.
                let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                // Increment the hard reference count.
                let new_hard_count = old_hard_count.wrapping_add(1);
                // Check if the incremented hard reference count overflows its bit field.
                if new_hard_count > arc::HARD_COUNT_MAX {
                    return Err(ArcError::HardCountOverflow);
                }
                // Clear the hard reference count bit field.
                let new_status = old_status & !arc::HARD_COUNT_MASK;
                // Splice the incremented hard reference count into the status field, and set the mut flag.
                let new_status = new_status | new_hard_count | arc::MUT_FLAG;
                // Atomically update the status field, synchronizing with reference releases.
                match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                    // CAS succeeded; return a new mutable lease.
                    Ok(_) => return Ok(Mut::from_raw(data)),
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            } else {
                // Check if the shared resident is concurrently relocating.
                if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Recurse into the relocated lease.
                        data = relocation;
                        // Get a pointer to the relocated header.
                        header = arc::header::<R>(data);
                    }
                }
                // Concurrently relocating; reload the status field and spin.
                old_status = (*header).status.load(Relaxed);
            }
        }
    }

    /// Returns a new mutable lease to the shared resident, traversing any
    /// completed relocations, and waiting for any concurrent relocation to
    /// complete and for any outstanding mutable or immutable leases to drop.
    ///
    /// # Safety
    ///
    /// Deadlocks if the current thread already holds a mutable or immutable
    /// lease to the shared resident. Can cause a future deadlock if a thread
    /// holding a mutable lease to a resident attempts to convert another hard
    /// or soft lease to the same resident into a mutable or immutable lease.
    ///
    /// # Panics
    ///
    /// Panics if the incremented hard reference count overflows `HARD_COUNT_MAX`.
    pub unsafe fn to_mut(&self) -> Mut<'a, R> {
        self.try_to_mut().unwrap()
    }

    /// Converts this hard lease into a mutable lease to the shared resident,
    /// traversing any completed relocations, waiting for any concurrent
    /// relocations to complete and for any outstanding mutable or immutable
    /// leases to drop, and returning an error if an incremented hard reference
    /// count overflows `HARD_COUNT_MAX`.
    ///
    /// # Safety
    ///
    /// Deadlocks if the current thread already holds a mutable or immutable
    /// lease to the shared resident. Can cause a future deadlock if a thread
    /// holding a mutable lease to a resident attempts to convert another hard
    /// or soft lease to the same resident into a mutable or immutable lease.
    pub unsafe fn try_into_mut(self) -> Result<Mut<'a, R>, ArcError> {
        // Get a pointer to the shared resident.
        let data = self.data.as_ptr();
        // Get a pointer to the arc header preceding the resident.
        let header = arc::header::<R>(data);
        // Load the status field; synchronized by subsequent CAS.
        let mut old_status = (*header).status.load(Relaxed);
        // Spin until a mutable reference is acquired.
        loop {
            // Check if the shared resident can be mutably referenced.
            if old_status & arc::READ_LOCKED_MASK == 0 {
                // Set the mut flag in the status field.
                let new_status = old_status | arc::MUT_FLAG;
                // Atomically update the status field, synchronizing with reference releases.
                match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                    // CAS succeeded.
                    Ok(_) => {
                        // Discard the original lease, whose hard reference we took.
                        mem::forget(self);
                        // Return a new mutable lease.
                        return Ok(Mut::from_raw(data));
                    },
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            } else {
                // Check if the shared resident is concurrently relocating.
                if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Temporarily reify the arc's relocation lease.
                        let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation);
                        // Recurse into the relocated lease.
                        let lease = relocation.try_to_mut();
                        // Discard the borrowed relocation lease.
                        mem::forget(relocation);
                        // Return the newly acquired lease.
                        return lease;
                    }
                }
                // Concurrently relocating; reload the status field and spin.
                old_status = (*header).status.load(Relaxed);
            }
        }
    }

    /// Converts this hard lease into a mutable lease to the shared resident,
    /// traversing any completed relocations, and waiting for any concurrent
    /// relocations to complete and for any outstanding mutable or immutable
    /// leases to drop.
    ///
    /// # Safety
    ///
    /// Deadlocks if the current thread already holds a mutable or immutable
    /// lease to the shared resident. Can cause a future deadlock if a thread
    /// holding a mutable lease to a resident attempts to convert another hard
    /// or soft lease to the same resident into a mutable or immutable lease.
    ///
    /// # Panics
    ///
    /// Panics if an incremented hard reference count overflows `HARD_COUNT_MAX`.
    pub unsafe fn into_mut(self) -> Mut<'a, R> {
        self.try_into_mut().unwrap()
    }

    /// Returns a new immutable lease to the shared resident, traversing any
    /// completed relocations, and returning an error if the reisdent is
    /// currently being relocated, or if there is an outstanding mutable lease,
    /// or if there is atomic operation contention, or if obtaining the lease
    /// would cause a reference count overflow.
    pub fn poll_ref(&self) -> Result<Ref<'a, R>, ArcError> {
        unsafe {
            // Get a pointer to the shared resident.
            let mut data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let mut header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Traverse relocations.
            loop {
                // Check if the shared resident is not mutably referenced, and is not concurrently relocating.
                if old_status & arc::WRITE_LOCKED_MASK == 0 {
                    // Extract the hard reference count from the status field.
                    let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                    // Increment the hard reference count.
                    let new_hard_count = old_hard_count.wrapping_add(1);
                    // Check if the incremented hard reference count overflows its bit field.
                    if new_hard_count > arc::HARD_COUNT_MAX {
                        return Err(ArcError::HardCountOverflow);
                    }
                    // Extract the immutable reference count from the status field.
                    let old_ref_count = (old_status & arc::REF_COUNT_MASK) >> arc::REF_COUNT_SHIFT;
                    // Increment the immutable reference count.
                    let new_ref_count = old_ref_count.wrapping_add(1);
                    // Check if the incremented shared reference count overflows its bit field.
                    if new_ref_count > arc::REF_COUNT_MAX {
                        return Err(ArcError::RefCountOverflow);
                    }
                    // Clear the hard and immutable reference count bit fields.
                    let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::REF_COUNT_MASK);
                    // Splice the incremented hard and immutable reference counts into the status field.
                    let new_status = new_status | new_hard_count | new_ref_count << arc::REF_COUNT_SHIFT;
                    // Atomically update the status field, synchronizing with reference releases.
                    match (*header).status.compare_exchange(old_status, new_status, Acquire, Relaxed) {
                        // CAS succeeded; return a new immutable lease.
                        Ok(_) => return Ok(Ref::from_raw(data)),
                        // CAS failed; abort.
                        Err(_) => return Err(ArcError::Contended),
                    }
                } else if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Recurse into the relocated lease.
                        data = relocation;
                        // Get a pointer to the relocated header.
                        header = arc::header::<R>(data);
                        // Load the relocated status field and repeat.
                        old_status = (*header).status.load(Relaxed);
                    } else {
                        return Err(ArcError::Relocating);
                    }
                } else {
                    return Err(ArcError::Aliased);
                }
            }
        }
    }

    /// Returns a new immutable lease to the shared resident, traversing any
    /// completed relocations, waiting for any concurrent relocation to
    /// complete and for any outstanding mutable lease to drop, and returning
    /// an error if the incremented hard reference count overflows `HARD_COUNT_MAX`,
    /// or if the incremented reference count overflows `REF_COUNT_MAX`.
    pub fn try_to_ref(&self) -> Result<Ref<'a, R>, ArcError> {
        unsafe {
            // Get a pointer to the shared resident.
            let mut data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let mut header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Traverse relocations, and spin until an immutable reference is acquired.
            loop {
                // Check if the shared resident is not mutably referenced, and is not concurrently relocating.
                if old_status & arc::WRITE_LOCKED_MASK == 0 {
                    // Extract the hard reference count from the status field.
                    let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                    // Increment the hard reference count.
                    let new_hard_count = old_hard_count.wrapping_add(1);
                    // Check if the incremented hard reference count overflows its bit field.
                    if new_hard_count > arc::HARD_COUNT_MAX {
                        return Err(ArcError::HardCountOverflow);
                    }
                    // Extract the immutable reference count from the status field.
                    let old_ref_count = (old_status & arc::REF_COUNT_MASK) >> arc::REF_COUNT_SHIFT;
                    // Increment the immutable reference count.
                    let new_ref_count = old_ref_count.wrapping_add(1);
                    // Check if the incremented shared reference count overflows its bit field.
                    if new_ref_count > arc::REF_COUNT_MAX {
                        return Err(ArcError::RefCountOverflow);
                    }
                    // Clear the hard and immutable reference count bit fields.
                    let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::REF_COUNT_MASK);
                    // Splice the incremented hard and immutable reference counts into the status field.
                    let new_status = new_status | new_hard_count | new_ref_count << arc::REF_COUNT_SHIFT;
                    // Atomically update the status field, synchronizing with reference releases.
                    match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                        // CAS succeeded; return a new immutable lease.
                        Ok(_) => return Ok(Ref::from_raw(data)),
                        // CAS failed; update the status field and try again.
                        Err(status) => old_status = status,
                    }
                } else {
                    // Check if the shared resident is concurrently relocating.
                    if old_status & arc::RELOCATED_FLAG != 0 {
                        // Synchronize with relocation initiation.
                        atomic::fence(Release);
                        // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                        let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                        // Check if the relocation has completed.
                        if !relocation.is_null() {
                            // Recurse into the relocated lease.
                            data = relocation;
                            // Get a pointer to the relocated header.
                            header = arc::header::<R>(data);
                        }
                    }
                    // Concurrently relocating; reload the status field and spin.
                    old_status = (*header).status.load(Relaxed);
                }
            }
        }
    }

    /// Returns a new immutable lease to the shared resident, traversing any
    /// completed relocations, waiting for any concurrent relocation to
    /// complete, and for any outstanding mutable lease to drop.
    ///
    /// # Panics
    ///
    /// Panics if the incremented hard reference count overflows `HARD_COUNT_MAX`,
    /// or if the incremented reference count overflows `REF_COUNT_MAX`.
    pub fn to_ref(&self) -> Ref<'a, R> {
        self.try_to_ref().unwrap()
    }

    /// Converts this hard lease into an immutable lease to the shared
    /// resident, traversing any completed relocations, waiting for any
    /// concurrent relocation to complete and for any outstanding mutable
    /// leases to drop, and returning an error if the incremented hard
    /// reference count overflows `HARD_COUNT_MAX`, or if the incremented
    /// immutable reference count overflows `REF_COUNT_MAX`.
    pub fn try_into_ref(self) -> Result<Ref<'a, R>, ArcError> {
        unsafe {
            // Get a pointer to the shared resident.
            let data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Traverse relocations, and spin until an immutable reference is acquired.
            loop {
                // Check if the shared resident is not mutably referenced, and is not concurrently relocating.
                if old_status & arc::WRITE_LOCKED_MASK == 0 {
                    // Extract the immutable reference count from the status field.
                    let old_ref_count = (old_status & arc::REF_COUNT_MASK) >> arc::REF_COUNT_SHIFT;
                    // Increment the immutable reference count.
                    let new_ref_count = old_ref_count.wrapping_add(1);
                    // Check if the incremented shared reference count overflows its bit field.
                    if new_ref_count > arc::REF_COUNT_MAX {
                        return Err(ArcError::RefCountOverflow);
                    }
                    // Clear the immutable reference count bit field.
                    let new_status = old_status & !arc::REF_COUNT_MASK;
                    // Splice the incremented immutable reference count into the status field.
                    let new_status = new_status | new_ref_count << arc::REF_COUNT_SHIFT;
                    // Atomically update the status field, synchronizing with reference releases.
                    match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                        // CAS succeeded.
                        Ok(_) => {
                            // Discard the original lease, whose hard reference we took.
                            mem::forget(self);
                            // Return a new immutable lease.
                            return Ok(Ref::from_raw(data));
                        },
                        // CAS failed; update the status field and try again.
                        Err(status) => old_status = status,
                    }
                } else {
                    // Check if the shared resident is concurrently relocating.
                    if old_status & arc::RELOCATED_FLAG != 0 {
                        // Synchronize with relocation initiation.
                        atomic::fence(Release);
                        // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                        let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                        // Check if the relocation has completed.
                        if !relocation.is_null() {
                            // Temporarily reify the arc's relocation lease.
                            let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation);
                            // Recurse into the relocated lease.
                            let lease = relocation.try_to_ref();
                            // Discard the borrowed relocation lease.
                            mem::forget(relocation);
                            // Return the newly acquired lease.
                            return lease;
                        }
                    }
                    // Concurrently relocating; reload the status field and spin.
                    old_status = (*header).status.load(Relaxed);
                }
            }
        }
    }

    /// Converts this hard lease into an immutable lease to the shared
    /// resident, traversing any completed relocations, and waiting for any
    /// concurrent relocation to complete and for any outstanding mutable
    /// leases to drop.
    ///
    /// # Panics
    ///
    /// Panics if the incremented hard reference count overflows `HARD_COUNT_MAX`,
    /// or if the incremented reference count overflows `REF_COUNT_MAX`.
    pub fn into_ref(self) -> Ref<'a, R> {
        self.try_into_ref().unwrap()
    }

    /// Returns a new soft lease to the shared resident, without traversing any
    /// relocations, returning an error if the incremented soft reference count
    /// overflows `SOFT_COUNT_MAX`.
    pub fn try_to_soft(&self) -> Result<Soft<'a, R>, ArcError> {
        unsafe {
            // Get a pointer to the shared resident.
            let data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Spin until a soft reference is acquired.
            loop {
                // Extract the soft reference count from the status field.
                let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT;
                // Increment the soft reference count.
                let new_soft_count = old_soft_count.wrapping_add(1);
                // Check if the incremented soft reference count overflows its bit field.
                if new_soft_count > arc::SOFT_COUNT_MAX {
                    return Err(ArcError::SoftCountOverflow);
                }
                // Clear the soft reference count bit field.
                let new_status = old_status & !arc::SOFT_COUNT_MASK;
                // Splice the incremented soft reference count into the status field.
                let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT;
                // Atomically update the status field, synchronizing with reference releases.
                match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                    // CAS succeeded; return a new Soft lease.
                    Ok(_) => return Ok(Soft::from_raw(data)),
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            }
        }
    }

    /// Returns a new soft lease to the shared resident, without traversing any
    /// relocations.
    ///
    /// # Panics
    ///
    /// Panics if the incremented soft reference count overflows `SOFT_COUNT_MAX`.
    pub fn to_soft(&self) -> Soft<'a, R> {
        self.try_to_soft().unwrap()
    }

    /// Converts this hard lease into a soft lease to the shared resident,
    /// without traversing any relocations, returning an error if the
    /// incremented soft reference count overflows `SOFT_COUNT_MAX`.
    pub fn try_into_soft(self) -> Result<Soft<'a, R>, ArcError> {
        unsafe {
            // Get a pointer to the shared resident.
            let data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Spin until a soft reference is acquired.
            loop {
                // Extract the hard reference count from the status field.
                let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                // Decrement the hard reference count, checking for underflow.
                let new_hard_count = match old_hard_count.checked_sub(1) {
                    Some(hard_count) => hard_count,
                    None => panic!("hard count underflow"),
                };
                // Extract the soft reference count from the status field.
                let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT;
                // Increment the soft reference count.
                let new_soft_count = old_soft_count.wrapping_add(1);
                // Check if the incremented soft reference count overflows its bit field.
                if new_soft_count > arc::SOFT_COUNT_MAX {
                    return Err(ArcError::SoftCountOverflow);
                }
                // Clear the hard and soft reference count bit fields.
                let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::SOFT_COUNT_MASK);
                // Splice the decremented hard and incremented soft reference counts into the status field.
                let new_status = new_status | new_hard_count | new_soft_count << arc::SOFT_COUNT_SHIFT;
                // Atomically update the status field, synchronizing with reference acquires and releases.
                match (*header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) {
                    // CAS succeeded.
                    Ok(_) => {
                        // Check if the hard count dropped to zero.
                        if new_hard_count == 0 {
                            // Drop the shared resident.
                            R::resident_drop(data, &mut (*header).meta);
                        }
                        // Discard the original lease, whose hard reference we released.
                        mem::forget(self);
                        // Return a new Soft lease.
                        return Ok(Soft::from_raw(data));
                    },
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            }
        }
    }

    /// Converts this hard lease into a soft lease to the shared resident,
    /// without traversing any relocations.
    ///
    /// # Panics
    ///
    /// Panics if the incremented soft reference count overflows `SOFT_COUNT_MAX`.
    pub fn into_soft(self) -> Soft<'a, R> {
        self.try_into_soft().unwrap()
    }

    /// Converts this hard lease into a raw pointer to the shared resident.
    /// Use `Hard::from_raw` to reconstitute the returned pointer back into
    /// a hard lease.
    ///
    /// # Safety
    ///
    /// The shared resident is not pinned to the returned memory address, and
    /// may be concurrently relocated at any time. A memory leak will occur
    /// unless the returned pointer is eventually converted back into a hard
    /// lease and dropped.
    #[inline]
    pub unsafe fn into_raw(self) -> *mut R::Data {
        let data = self.data.as_ptr();
        mem::forget(self);
        data
    }

    /// Returns an immutable lease to the shared resident, traversing any
    /// completed moves, without waiting.
    ///
    /// # Panics
    ///
    /// Panics if the the shared resident is mutably aliased.
    pub fn borrow(&self) -> Ref<'a, R> {
        loop {
            // Try to acquire an immutable reference.
            match self.poll_ref() {
                // Immutable lease acquired.
                Ok(lease) => return lease,
                // Concurrently relocating, try again.
                Err(ArcError::Relocating) => (),
                // Lock contention encountered, try again.
                Err(ArcError::Contended) => (),
                // Immutable reference unavailable.
                Err(error) => panic!("{:?}", error),
            }
        }
    }

    /// Returns a raw pointer to the shared resident.
    ///
    /// # Safety
    ///
    /// The shared resident may be uninitialized, or mutably aliased,
    /// or may have been have relocated.
    #[inline]
    pub unsafe fn as_ptr_unchecked(&self) -> *mut R::Data {
        self.data.as_ptr()
    }

    /// Consumes this hard lease, traversing any completed relocations,
    /// and returns the shared resident; returns an error if there are
    /// any outstanding hard, mutable, or immutable leases.
    pub fn try_unwrap(mut self) -> Result<R::Target, Hard<'a, R>> where R: ResidentUnwrap<Hard<'a, R>> {
        unsafe {
            // Get a pointer to the shared resident.
            let mut data = self.data.as_ptr();
            // Get the alignment of the resident.
            let align = mem::align_of_val(&*data);
            // Get the offset of the resident in the arc structure by rounding up
            // the size of the arc header to the alignment of the resident.
            let offset = mem::size_of::<ArcHeader<R::Meta>>()
                .wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
            // Get a pointer to the arc header by subtracting the resident's
            // offset in the arc structure.
            let mut header = (data as *mut u8).wrapping_sub(offset) as *mut ArcHeader<R::Meta>;
            // Compute the total size of the arc structure.
            let size = offset.wrapping_add(R::resident_size(data, &mut (*header).meta));
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Spin until the hard reference is released.
            loop {
                // Check if the shared resident hasn't relocated.
                if old_status & arc::RELOCATED_FLAG == 0 {
                    // Extract the hard reference count from the status field.
                    let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                    // Check if the resident has multiple hard references.
                    if old_hard_count != 1 {
                        // Can't unwrap an aliased resident.
                        return Err(self);
                    }
                    // Clear the hard reference count bit field.
                    let new_status = old_status & !arc::HARD_COUNT_MASK;
                    // Extract the soft reference count from the status field.
                    let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT;
                    // Check if all soft references have dropped.
                    if old_soft_count == 0 {
                        // Store the new status field; can't fail because we're the last reference of any kind.
                        (*header).status.store(new_status, Relaxed);
                        // Read the resident out of the arc structure.
                        let resident = R::resident_unwrap(&self);
                        // Drop the arc header.
                        (*header).drop::<R>(data);
                        // Get the block of memory containing the arc structure.
                        let block = Block::from_raw_parts(header as *mut u8, size);
                        // Deallocate the block.
                        AllocTag::from_ptr(header as *mut u8).dealloc(block);
                        // Discard the original lease, whose hard reference we released.
                        mem::forget(self);
                        // Return the unwrapped resident.
                        return Ok(resident);
                    } else {
                        // Convert our hard reference into a soft reference to avoid racing with other soft refs.
                        let new_soft_count = old_soft_count.wrapping_add(1);
                        // Check if the incremented soft reference count overflows its bit field.
                        if new_soft_count > arc::SOFT_COUNT_MAX {
                            return Err(self);
                        }
                        // Clear the soft reference count bit field.
                        let new_status = new_status & !arc::SOFT_COUNT_MASK;
                        // Splice the incremented soft reference count into the status field.
                        let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT;
                        // Atomically update the status field, synchronizing with reference releases.
                        match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                            // CAS succeeded; the last hard reference has been released.
                            Ok(_) => {
                                // Read the resident out of the arc structure.
                                let resident = R::resident_unwrap(&self);
                                // Update the status field.
                                old_status = new_status;
                                // Spin until the soft reference has been released.
                                loop {
                                    // Extract the soft reference count from the status field.
                                    let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT;
                                    // Decrement the soft reference count, checking for underflow.
                                    let new_soft_count = match old_soft_count.checked_sub(1) {
                                        Some(soft_count) => soft_count,
                                        None => panic!("soft count underflow"),
                                    };
                                    // Clear the soft reference count bit field.
                                    let new_status = old_status & !arc::SOFT_COUNT_MASK;
                                    // Splice the decremented soft reference count into the status field.
                                    let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT;
                                    // Atomically update the status field, synchronizing with reference acquires.
                                    match (*header).status.compare_exchange_weak(old_status, new_status, Release, Relaxed) {
                                        // CAS succeeded.
                                        Ok(_) => {
                                            // Check if all soft references have been released.
                                            if new_soft_count == 0 {
                                                // Drop the arc header.
                                                (*header).drop::<R>(data);
                                                // Get the block of memory containing the arc structure.
                                                let block = Block::from_raw_parts(header as *mut u8, size);
                                                // Deallocate the block.
                                                AllocTag::from_ptr(header as *mut u8).dealloc(block);
                                            }
                                            // Return the unwrapped resident.
                                            return Ok(resident);
                                        },
                                        // CAS failed; update the status field and try again.
                                        Err(status) => old_status = status,
                                    }
                                }
                            },
                            // CAS failed; update the status field and try again.
                            Err(status) => old_status = status,
                        }
                    }
                } else {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the relocated resident, synchronizing with relocation completion.
                    let relocation = block::set_address(data, (*header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Temporarily reify the arc's relocation lease.
                        let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation);
                        // Recurse into the relocated lease.
                        self = relocation.clone();
                        // Discard the borrowed relocation lease.
                        mem::forget(relocation);
                        // Get a pointer to the relocated resident.
                        data = self.data.as_ptr();
                        // Get a pointer to the relocated header.
                        header = (data as *mut u8).wrapping_sub(offset) as *mut ArcHeader<R::Meta>;
                        // Load the relocated status field and try again.
                        old_status = (*header).status.load(Relaxed);
                    } else {
                        // Can't unwrap a relocating resident.
                        return Err(self);
                    }
                }
            }
        }
    }

    /// Consumes this hard lease, traversing any completed relocations,
    /// and returns the shared resident.
    ///
    /// # Panics
    ///
    /// Panics if there are any outstanding hard, mutable, or immutable leases.
    pub fn unwrap(self) -> R::Target where R: ResidentUnwrap<Hard<'a, R>> {
        match self.try_unwrap() {
            Ok(resident) => resident,
            Err(_) => panic!("aliased resident"),
        }
    }
}

impl<'a, R: Resident> Holder<'a> for Hard<'a, R> {
    #[inline]
    fn holder(&self) -> &'a dyn Hold<'a> {
        AllocTag::from_ptr(self.header() as *mut u8).holder()
    }
}

impl<'a, R: Resident> Lease for Hard<'a, R> {
    type Data = R::Data;

    type Meta = R::Meta;

    #[inline]
    fn data(&self) -> *mut R::Data {
        self.data.as_ptr()
    }

    #[inline]
    fn meta(&self) -> *mut R::Meta {
        unsafe { &mut (*self.header()).meta }
    }
}

impl<'a, R: ResidentHash<Ref<'a, R>>> Hash for Hard<'a, R> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        Hash::hash(&self.borrow(), state);
    }
}

impl<'a, R: ResidentDisplay<Ref<'a, R>>> Display for Hard<'a, R> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(&self.borrow(), f)
    }
}

impl<'a, R: ResidentDebug<Ref<'a, R>>> Debug for Hard<'a, R> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Debug::fmt(&self.borrow(), f)
    }
}

impl<'a, R: Resident> Pointer for Hard<'a, R> {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Pointer::fmt(&self.data.as_ptr(), f)
    }
}

impl<'a, R: Resident> TryClone for Hard<'a, R> {
    fn try_clone(&self) -> Result<Hard<'a, R>, HoldError> {
        unsafe {
            // Get a pointer to the shared resident.
            let data = self.data.as_ptr();
            // Get a pointer to the arc header preceding the resident.
            let header = arc::header::<R>(data);
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Spin until a hard reference is acquired.
            loop {
                // Extract the hard reference count from the status field.
                let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                // Increment the hard reference count.
                let new_hard_count = old_hard_count.wrapping_add(1);
                // Check if the incremented hard reference count overflows its bit field.
                if new_hard_count > arc::HARD_COUNT_MAX {
                    return Err(HoldError::Unsupported("hard count overflow"));
                }
                // Clear the hard reference count bit field.
                let new_status = old_status & !arc::HARD_COUNT_MASK;
                // Splice the incremented hard reference count into the status field.
                let new_status = new_status | new_hard_count;
                // Atomically update the status field, synchronizing with reference releases.
                match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) {
                    // CAS succeeded; return a new hard lease.
                    Ok(_) => return Ok(Hard::from_raw(data)),
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            }
        }
    }
}

impl<'a, R: Resident> Clone for Hard<'a, R> {
    fn clone(&self) -> Hard<'a, R> {
        self.try_clone().unwrap()
    }
}

impl<'a, 'b, R: ResidentStow<'b, Hard<'a, R>, Hard<'b, R>>> Stow<'b, Hard<'b, R>> for Hard<'a, R> {
    unsafe fn stow(src: *mut Hard<'a, R>, dst: *mut Hard<'b, R>, hold: &Hold<'b>) -> Result<(), HoldError> {
        // Get a pointer to the source resident.
        let src_data = (*src).data.as_ptr();
        // Get the alignment of the resident.
        let src_align = mem::align_of_val(&*src_data);
        // Get the offset of the resident in the arc structure by rounding up
        // the size of the arc header to the alignment of the resident.
        let src_offset = mem::size_of::<ArcHeader<R::Meta>>()
            .wrapping_add(src_align).wrapping_sub(1) & !src_align.wrapping_sub(1);
        // Get a pointer to the source header by subtracting the resident's
        // offset in the arc structure.
        let src_header = (src_data as *mut u8).wrapping_sub(src_offset) as *mut ArcHeader<R::Meta>;
        // Load the status field; synchronized by subsequent CAS.
        let mut old_status = (*src_header).status.load(Relaxed);
        // Spin until the relocated flag is set.
        loop {
            // Check if the source resident can be mutably referenced.
            if old_status & arc::READ_LOCKED_MASK == 0 {
                // Set the relocated flag in the status field.
                let new_status = old_status | arc::RELOCATED_FLAG;
                // Atomically update the status field, synchronizing with relocation initiation and traversal.
                match (*src_header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) {
                    // CAS succeeded.
                    Ok(_) => {
                        // Update the status field.
                        old_status = new_status;
                        // Move initiated.
                        break;
                    },
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            } else {
                // Check if the source resident has already relocated.
                if old_status & arc::RELOCATED_FLAG != 0 {
                    // Synchronize with relocation initiation.
                    atomic::fence(Release);
                    // Get a fat pointer to the source resident, synchronizing with relocation completion.
                    let relocation = block::set_address(src_data, (*src_header).relocation.load(Acquire));
                    // Check if the relocation has completed.
                    if !relocation.is_null() {
                        // Temporarily reify the arc's relocation lease.
                        let relocation = mem::transmute::<*mut R::Data, Hard<'b, R>>(relocation);
                        // Set the destination lease to a clone of the relocation lease.
                        ptr::write(dst, relocation.clone());
                        // Discard the borrowed relocation lease.
                        mem::forget(relocation);
                        // Return successfully.
                        return Ok(());
                    }
                }
                // Concurrently relocating; reload the status field and spin.
                old_status = (*src_header).status.load(Relaxed);
            }
        }
        // Compute the layout of the destination arc structure, capturing the offset of its resident field.
        let (dst_layout, dst_offset) = Layout::for_type::<ArcHeader<R::Meta>>()
            .extended(R::new_resident_layout(&*src))?;
        // Allocate a block of memory to hold the new arc structure, bailing on failure.
        let dst_block = match hold.alloc(dst_layout) {
            // Allocation succeeded.
            Ok(block) => block,
            // Allocation failed.
            Err(error) => {
                // Spin until the relocated flag is unset.
                loop {
                    // Unset the relocated flag in the status field.
                    let new_status = old_status & !arc::RELOCATED_FLAG;
                    // Atomically update the status field, synchronizing with reference acquires and releases.
                    match (*src_header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) {
                        // CAS succeeded; return the allocation error.
                        Ok(_) => return Err(error),
                        // CAS failed; update the status field and try again.
                        Err(status) => old_status = status,
                    }
                }
            },
        };
        // Get a pointer to the header of the new arc.
        let dst_header = dst_block.as_ptr() as *mut ArcHeader<R::Meta>;
        // Initialize the new arc's relocation address to zero.
        ptr::write(&mut (*dst_header).relocation, AtomicUsize::new(0));
        // Initialize the new arc's status field with two hard references,
        // owned by the relocation reference of the source lease, and the other
        // owned by the destination lease.
        ptr::write(&mut (*dst_header).status, AtomicUsize::new(2));
        // Get a fat pointer to the destination resident.
        let dst_data = block::set_address(src_data, (dst_header as usize).wrapping_add(dst_offset));
        // Initialize the destination lease.
        ptr::write(dst, Hard::from_raw(dst_data));
        // Try to stow the resident.
        if let err @ Err(_) = R::resident_stow(&mut *src, &mut *dst, hold) {
            // Free the newly allocated arc.
            hold.dealloc(dst_block);
            // Spin until the relocated flag is unset.
            loop {
                // Unset the relocated flag in the status field.
                let new_status = old_status & !arc::RELOCATED_FLAG;
                // Atomically update the status field, synchronizing with relocation initiation and traversal.
                match (*src_header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) {
                    // CAS succeeded; return the stow error.
                    Ok(_) => return err,
                    // CAS failed; update the status field and try again.
                    Err(status) => old_status = status,
                }
            }
        }
        // Write the relocation address of the new resident into the old arc header,
        // synchronizing with relocation traversals, completing the relocation.
        (*src_header).relocation.store(dst_data as *mut u8 as usize, Release);
        // Return successfully.
        Ok(())
    }

    unsafe fn unstow(src: *mut Hard<'a, R>, dst: *mut Hard<'b, R>) {
        // Get a pointer to the source resident.
        let src_data = (*src).data.as_ptr();
        // Get the alignment of the resident.
        let align = mem::align_of_val(&*src_data);
        // Get the offset of the resident in the arc structure by rounding up
        // the size of the arc header to the alignment of the resident.
        let offset = mem::size_of::<ArcHeader<R::Meta>>()
            .wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
        // Get a pointer to the source header.
        let src_header = (src_data as *mut u8).wrapping_sub(offset) as *mut ArcHeader<R::Meta>;
        // Get a pointer to the destination resident.
        let dst_data = (*dst).data.as_ptr();
        // Get a pointer to the destination header.
        let dst_header = (dst_data as *mut u8).wrapping_sub(offset) as *mut ArcHeader<R::Meta>;
        // Load the destination status field; synchronized by subsequent CAS.
        let mut old_dst_status = (*dst_header).status.load(Relaxed);
        // Spin until the source arc's relocation lease has been dropped.
        loop {
            // Check if the source arc's relocation lease is unique.
            if old_dst_status == arc::UNIQUE_STATUS {
                // Forward lease is unique, clear the source arc's relocation address.
                // Can't race with relocation traversal because the src and dst
                // pointers can't be aliased outside the call stack.
                (*src_header).relocation.store(0, Release);
                // Load the source status field; synchronized by subsequent CAS.
                let mut old_src_status = (*src_header).status.load(Relaxed);
                // Spin until the source relocated flag is unset.
                loop {
                    // Unset the relocated flag in the status field.
                    let new_src_status = old_src_status & !arc::RELOCATED_FLAG;
                    // Atomically update the status field, synchronizing with relocation initiation and traversal.
                    match (*src_header).status.compare_exchange_weak(old_src_status, new_src_status, SeqCst, Relaxed) {
                        // CAS succeeded; proceed.
                        Ok(_) => break,
                        // CAS failed; update the status field and try again.
                        Err(status) => old_src_status = status,
                    }
                }
                // Unstow the resident.
                R::resident_unstow(&mut *src, &mut *dst);
                // Compute the total size of the arc structure.
                let size = offset.wrapping_add(R::resident_size(dst_data, &mut (*dst_header).meta));
                // Get the memory block containing the destination arc.
                let dst_block = Block::from_raw_parts(dst as *mut u8, size);
                // Deallocate the destination arc.
                AllocTag::from_ptr(dst_header as *mut u8).dealloc(dst_block);
                // Move has been fully reverted.
                return;
            } else {
                // Forward lease is aliased (within the current call stack);
                // release the source arc's hard reference.
                // Extract the hard reference count from the status field.
                let old_hard_count = old_dst_status & arc::HARD_COUNT_MASK;
                // Decrement the hard reference count, checking for underflow.
                let new_hard_count = match old_hard_count.checked_sub(1) {
                    Some(hard_count) => hard_count,
                    None => panic!("hard count underflow"),
                };
                // Clear the hard reference count field.
                let new_dst_status = old_dst_status & !arc::HARD_COUNT_MASK;
                // Splice the decremented hard reference count into the status field.
                let new_dst_status = new_dst_status | new_hard_count;
                // Atomically update the destination status field, synchronizing with reference acquires.
                match (*dst_header).status.compare_exchange_weak(old_dst_status, new_dst_status, Release, Relaxed) {
                    // CAS succeeded; hard reference released; relocation has been fully reverted.
                    Ok(_) => return,
                    // CAS failed; update the status field and try again.
                    Err(status) => old_dst_status = status,
                }
            }
        }
    }
}

unsafe impl<'a, #[may_dangle] R: Resident> Drop for Hard<'a, R> {
    fn drop(&mut self) {
        unsafe {
            // Get a pointer to the shared resident.
            let data = self.data.as_ptr();
            // Get the alignment of the resident.
            let align = mem::align_of_val(&*data);
            // Get the offset of the resident in the arc structure by rounding up
            // the size of the arc header to the alignment of the resident.
            let offset = mem::size_of::<ArcHeader<R::Meta>>()
                .wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
            // Get a pointer to the arc header by subtracting the resident's
            // offset in the arc structure.
            let header = (data as *mut u8).wrapping_sub(offset) as *mut ArcHeader<R::Meta>;
            // Compute the total size of the arc structure.
            let size = offset.wrapping_add(R::resident_size(data, &mut (*header).meta));
            // Load the status field; synchronized by subsequent CAS.
            let mut old_status = (*header).status.load(Relaxed);
            // Spin until the hard reference has been released.
            loop {
                // Extract the hard reference count from the status field.
                let old_hard_count = old_status & arc::HARD_COUNT_MASK;
                // Decrement the hard reference count, checking for underflow.
                let new_hard_count = match old_hard_count.checked_sub(1) {
                    Some(hard_count) => hard_count,
                    None => panic!("hard count underflow"),
                };
                // Clear the hard reference count field.
                let new_status = old_status & !arc::HARD_COUNT_MASK;
                // Splice the decremented hard reference count into the status field.
                let new_status = new_status | new_hard_count;
                // Check if any hard references will remain.
                if new_hard_count != 0 {
                    // Atomically update the status field, synchronizing with reference acquires.
                    match (*header).status.compare_exchange_weak(old_status, new_status, Release, Relaxed) {
                        // CAS succeeded; hard reference released.
                        Ok(_) => return,
                        // CAS failed; update the status field and try again.
                        Err(status) => old_status = status,
                    }
                } else {
                    // Extract the soft reference count from the status field.
                    let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT;
                    // Check if all soft references have dropped.
                    if old_soft_count == 0 {
                        // Store the new status field; can't fail because we're the last reference of any kind.
                        (*header).status.store(new_status, Relaxed);
                        // Check if the resident hasn't relocated.
                        if new_status & arc::RELOCATED_FLAG == 0 {
                            // Drop the shared resident.
                            R::resident_drop(data, &mut (*header).meta);
                        }
                        // Drop the arc header.
                        (*header).drop::<R>(data);
                        // Get the block of memory containing the arc structure.
                        let block = Block::from_raw_parts(header as *mut u8, size);
                        // Deallocate the block.
                        AllocTag::from_ptr(header as *mut u8).dealloc(block);
                        return;
                    } else {
                        // Convert our hard reference into a soft reference to avoid racing with other soft refs.
                        let new_soft_count = old_soft_count.wrapping_add(1);
                        // Check if the incremented soft reference count overflows its bit field.
                        if new_soft_count > arc::SOFT_COUNT_MAX {
                            panic!("soft count overflow");
                        }
                        // Clear the soft reference count bit field.
                        let new_status = new_status & !arc::SOFT_COUNT_MASK;
                        // Splice the incremented soft reference count into the status field.
                        let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT;
                        // Atomically update the status field, synchronizing with reference acquires and releases.
                        match (*header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) {
                            // CAS succeeded; the last hard reference has been released.
                            Ok(_) => {
                                // Check if the resident hasn't relocated.
                                if new_status & arc::RELOCATED_FLAG == 0 {
                                    // Drop the shared resident.
                                    R::resident_drop(data, &mut (*header).meta);
                                }
                                // Update the status field.
                                old_status = new_status;
                                // Spin until the soft reference has been released.
                                loop {
                                    // Extract the soft reference count from the status field.
                                    let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT;
                                    // Decrement the soft reference count, checking for underflow.
                                    let new_soft_count = match old_soft_count.checked_sub(1) {
                                        Some(soft_count) => soft_count,
                                        None => panic!("soft count underflow"),
                                    };
                                    // Clear the soft reference count bit field.
                                    let new_status = old_status & !arc::SOFT_COUNT_MASK;
                                    // Splice the decremented soft reference count into the status field.
                                    let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT;
                                    // Atomically update the status field, synchronizing with reference acquires.
                                    match (*header).status.compare_exchange_weak(old_status, new_status, Release, Relaxed) {
                                        // CAS succeeded.
                                        Ok(_) => {
                                            // Check if all soft references have been released.
                                            if new_soft_count == 0 {
                                                // Shared resident has already been dropped; drop the arc header.
                                                (*header).drop::<R>(data);
                                                // Get the block of memory containing the arc structure.
                                                let block = Block::from_raw_parts(header as *mut u8, size);
                                                // Deallocate the block.
                                                AllocTag::from_ptr(header as *mut u8).dealloc(block);
                                            }
                                            return;
                                        },
                                        // CAS failed; update the status field and try again.
                                        Err(status) => old_status = status,
                                    }
                                }
                            },
                            // CAS failed; update the status field and try again.
                            Err(status) => old_status = status,
                        }
                    }
                }
            }
        }
    }
}