bitvec 0.17.4

A crate for manipulating memory, bit by bit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
/*! Reïmplementation of the `[T]` API.

This module tracks the [`slice`] primitive and [`core::slice`] module in the
version of Rust specified in the `rust-toolchain` file. It is required to
provide an exact or equivalent API surface matching the `Box<[T]>` type, to the
extent that it is possible in the language. Where differences occur, they must
be documented in a section called `API Differences`.

[`core::slice`]: https://doc.rust-lang.org/core/slice
[`slice`]: https://doc.rust-lang.org/std/primitive.slice.html
!*/

use crate::{
	access::BitAccess,
	indices::BitIdx,
	order::BitOrder,
	pointer::BitPtr,
	slice::{
		BitSlice,
		iter::{
			Chunks,
			ChunksExact,
			ChunksExactMut,
			ChunksMut,
			GenericSplitN,
			Iter,
			IterMut,
			RChunks,
			RChunksExact,
			RChunksExactMut,
			RChunksMut,
			RSplit,
			RSplitMut,
			RSplitN,
			RSplitNMut,
			Split,
			SplitMut,
			SplitN,
			SplitNMut,
			Windows,
		},
		proxy::BitMut,
	},
	store::BitStore,
};

use core::{
	cmp,
	marker::PhantomData,
	ops::{
		Range,
		RangeFrom,
		RangeFull,
		RangeInclusive,
		RangeTo,
		RangeToInclusive,
	},
	ptr::NonNull,
	slice,
};

#[cfg(feature = "alloc")]
use crate::vec::BitVec;

/** Forms a `BitSlice` from a pointer, starting position, and length.

The `head` argument is the starting *index*, not the starting *bit position*.
The `bits` argumnent is the number of **bits**, not the number of elements `T`.

This function is the semantic equivalent to `[T]::from_raw_parts`, in contrast
to [`from_raw_parts`] which is the API equivalent.

# Safety

This function is unsafe as there is no guarantee that the given pointer is valid
for the elements required to hold `head + bits` bits, nor whether the lifetime
inferred is a suitable lifetime for the returned slice.

`data` must be non-null and aligned, even for zero-length slices. This is due to
requirements in the `bitvec` data structure operations. You can obtain a pointer
that is usable as `data` for zero-length slices from [`NonNull::dangling()`].

The total size of the bit slice must be no larger than `BitPtr::<T>::MAX_BITS`
**bits** in memory. See the safety documentation of `BitPtr` (if available).

# Caveat

The lifetime for the returned slice is inferred from its usage. To prevent
accidental misuse, it’s suggested to tie the lifetime to whichever source
lifetime is safe in the context, such as by providing a helper function taking
the lifetime of a host value for the slice, or by explicit annotation.

# Examples

```rust
use bitvec::{
    indices::BitIdx,
    order::Local,
    slice,
    slice::BitSlice,
};

// manifest a slice for a single element
let x = 42u8;
let ptr = &x as *const u8;
let bits: &BitSlice<Local, u8> = unsafe { slice::bits_from_raw_parts(
    ptr,
    BitIdx::new(2).unwrap(),
    5
) };
assert_eq!(bits.len(), 5);
```

[`from_raw_parts`]: #fn.from_raw_parts
**/
pub unsafe fn bits_from_raw_parts<'a, O, T>(
	data: *const T,
	head: BitIdx<T>,
	bits: usize,
) -> &'a BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
	BitPtr::new(data, head, bits).into_bitslice()
}

/** Performs the same functionality as [`bits_from_raw_parts`], except that a
mutable slice is returned.

This function is unsafe for the same reasons as [`bits_from_raw_parts`], as well
as not being able to provide a non-aliasing guarantee of the returned mutable
slice. `data` must be non-null and aligned even for zero-length slices as with
[`bits_from_raw_parts`]. The total size of the slice must be no larger than
`BitPtr::<T>::MAX_ELTS` **elements** `T` in memory.

See the documentation of [`bits_from_raw_parts`] for more details.

# Safety

Beyond the ordinary Rust requirements for aliasing, this function *also*
requires that the described region, when combined with the `O` [`BitOrder`]
type parameter, not cause aliasing with another `BitSlice` whose head and `O`
arguments cause aliasing in the underlying memory positions.

[`BitOrder`]: ../order/trait.BitOrder.html
[`bits_from_raw_parts`]: #fn.bits_from_raw_parts
**/
pub unsafe fn bits_from_raw_parts_mut<'a, O, T>(
	data: *mut T,
	head: BitIdx<T>,
	bits: usize,
) -> &'a mut BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
	BitPtr::new(data, head, bits).into_bitslice_mut()
}

/** Converts a reference to `T` into a `BitSlice` of that element (without
copying).

# Original

[`core::slice::from_mut`](https://doc.rust-lang.org/core/slice/fn.from_mut.html)
**/
pub fn from_mut<O, T>(elt: &mut T) -> &mut BitSlice<O, T>
where O: BitOrder, T: BitStore {
	BitSlice::from_element_mut(elt)
}

/** Forms a bit slice from a pointer and a length.

The `len` argument is the number of **elements**, not the number of bits.

# Safety

This function is unsafe as there is no guarantee that the given pointer is valid
for `len` elements, nor whether the lifetime inferred is a suitable lifetime for
the returned slice.

`data` must be non-null and aligned, even for zero-length slices. This is due to
requirements in the `bitvec` data structure operations. You can obtain a pointer
that is usable as `data` for zero-length slices from [`NonNull::dangling()`].

The total size of the bit slice must be no larger than `BitPtr::<T>::MAX_BITS`
**bits** in memory. See the safety documentation of `BitPtr` (if available).

# Caveat

The lifetime for the returned slice is inferred from its usage. To prevent
accidental misuse, it’s suggested to tie the lifetime to whichever source
lifetime is safe in the context, such as by providing a helper function taking
the lifetime of a host value for the slice, or by explicit annotation.

# Original

[`core::slice::from_raw_parts`](https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html)

# Examples

```rust
# use bitvec::prelude::*;
use bitvec::slice as bitslice;

//  manifest a slice for a single element
let x = 42u8; // 0b0010_1010
let ptr = &x as *const _;
let bitslice = unsafe { bitslice::from_raw_parts::<Msb0, _>(ptr, 1) };
assert!(bitslice[2]);
```
**/
pub unsafe fn from_raw_parts<'a, O, T>(
	data: *const T,
	len: usize,
) -> &'a BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
	BitSlice::from_slice(slice::from_raw_parts(data, len))
}

/** Performs the same functionality as [`from_raw_parts`], except that a mutable
slice is returned.

This function is unsafe for the same reason as [`from_raw_parts`], as well as
not being able to provide a non-aliasing guarantee of the returned mutable
slice. `data` must be non-null and aligned even for zero-length slices as with
[`from_raw_parts`]. The total size of the slice must be no larger than
`BitPtr::<T>::MAX_ELTS` **elements** in memory.

See the documentation of [`from_raw_parts`] for more details.

# Safety

See `from_raw_parts`.

# Original

[`core::slice::from_raw_parts_mut`](https://doc.rust-lang.org/core/slice/fn.from_raw_parts_mut.html)

[`from_raw_parts`]: #fn.from_raw_parts
**/
pub unsafe fn from_raw_parts_mut<'a, O, T>(
	data: *mut T,
	len: usize,
) -> &'a mut BitSlice<O, T>
where O: BitOrder, T: 'a + BitStore {
	BitSlice::from_slice_mut(slice::from_raw_parts_mut(data, len))
}

/** Converts a reference to `T` into a bit slice one element long (without
copying).

# Original

[`core::slice::from_ref`](https://doc.rust-lang.org/core/slice/fn.from_ref.html)
**/
pub fn from_ref<O, T>(elt: &T) -> &BitSlice<O, T>
where O: BitOrder, T: BitStore {
	BitSlice::from_element(elt)
}

/// Reimplementation of the `[T]` inherent-method API.
impl<O, T> BitSlice<O, T>
where O: BitOrder, T: BitStore {
	/// Returns the number of bits in the slice.
	///
	/// # Original
	///
	/// [`slice::len`](https://doc.rust-lang.org/std/primitive.slice.html#method.len)
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let bits = 0u8.bits::<Local>();
	/// assert_eq!(bits.len(), 8);
	/// ```
	pub fn len(&self) -> usize {
		self.bitptr().len()
	}

	/// Returns `true` if the slice has a length of 0.
	///
	/// # Original
	///
	/// [`slice::is_empty`](https://doc.rust-lang.org/std/primitive.slice.html#method.is_empty)
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let bits = 0u8.bits::<Local>();
	/// assert!(!bits.is_empty());
	///
	/// assert!(BitSlice::<Local, usize>::empty().is_empty())
	/// ```
	pub fn is_empty(&self) -> bool {
		self.bitptr().len() == 0
	}

	/// Returns the first bit of the slice, or `None` if it is empty.
	///
	/// # Original
	///
	/// [`slice::first`](https://doc.rust-lang.org/std/primitive.slice.html#method.first)
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let bits = 1u8.bits::<Lsb0>();
	/// assert_eq!(bits.first(), Some(&true));
	///
	/// assert!(BitSlice::<Local, usize>::empty().first().is_none());
	/// ```
	#[inline]
	pub fn first(&self) -> Option<&bool> {
		0.get(self)
	}

	/// Returns a mutable pointer to the first bit of the slice, or `None` if it
	/// is empty.
	///
	/// # Original
	///
	/// [`slice::first_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.first_mut)
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Lsb0>();
	/// if let Some(mut first) = bits.first_mut() {
	///     *first = true;
	/// }
	/// assert_eq!(data, 1u8);
	/// ```
	#[inline]
	pub fn first_mut(&mut self) -> Option<BitMut<O, T>> {
		0.get_mut(self)
	}

	/// Returns the first and all the rest of the bits of the slice, or `None`
	/// if it is empty.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let bits = 1u8.bits::<Lsb0>();
	/// if let Some((first, rest)) = bits.split_first() {
	///     assert_eq!(first, &true);
	///     assert_eq!(rest, &bits[1 ..]);
	/// }
	/// ```
	#[inline]
	pub fn split_first(&self) -> Option<(&bool, &Self)> {
		if self.is_empty() {
			None
		}
		else {
			let (head, rest) = self.split_at(1);
			unsafe { Some((0.get_unchecked(head), rest)) }
		}
	}

	/// Returns the first and all the rest of the bits of the slice, or `None`
	/// if it is empty.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Lsb0>();
	/// if let Some((mut first, rest)) = bits.split_first_mut() {
	///     *first = true;
	///     *rest.at(0) = true;
	///     *rest.at(1) = true;
	/// }
	/// assert_eq!(data, 7);
	/// ```
	#[inline]
	pub fn split_first_mut(&mut self) -> Option<(BitMut<O, T>, &mut Self)> {
		if self.is_empty() {
			None
		}
		else {
			let (head, rest) = self.split_at_mut(1);
			Some((unsafe { 0.get_unchecked_mut(head) }, rest))
		}
	}

	/// Returns the last and all the rest of the bits of the slice, or `None` if
	/// it is empty.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let bits = 1u8.bits::<Msb0>();
	/// if let Some((last, rest)) = bits.split_last() {
	///     assert_eq!(last, &true);
	///     assert_eq!(rest, &bits[.. 7]);
	/// }
	/// ```
	#[inline]
	pub fn split_last(&self) -> Option<(&bool, &Self)> {
		match self.len() {
			0 => None,
			len => {
				let (rest, tail) = self.split_at(len - 1);
				Some((unsafe { 0.get_unchecked(tail) }, rest))
			},
		}
	}

	/// Returns the last and all the rest of the bits of the slice, or `None` if
	/// it is empty.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// if let Some((mut last, rest)) = bits.split_last_mut() {
	///     *last = true;
	///     *rest.at(0) = true;
	///     *rest.at(1) = true;
	/// }
	/// assert_eq!(data, 128 | 64 | 1);
	/// ```
	#[inline]
	pub fn split_last_mut(&mut self) -> Option<(BitMut<O, T>, &mut Self)> {
		match self.len() {
			0 => None,
			len => {
				let (rest, tail) = self.split_at_mut(len - 1);
				Some((unsafe { 0.get_unchecked_mut(tail) }, rest))
			},
		}
	}

	/// Returns the last bit of the slice, or `None` if it is empty.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let bits = 1u8.bits::<Msb0>();
	/// assert_eq!(Some(&true), bits.last());
	/// assert!(BitSlice::<Local, usize>::empty().last().is_none());
	/// ```
	#[inline]
	pub fn last(&self) -> Option<&bool> {
		match self.len() {
			0 => None,
			len => Some(unsafe { (len - 1).get_unchecked(self) }),
		}
	}

	/// Returns a mutable pointer to the last bit in the slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// if let Some(mut last) = bits.last_mut() {
	///     *last = true;
	/// }
	/// assert!(bits[7]);
	#[inline]
	pub fn last_mut(&mut self) -> Option<BitMut<O, T>> {
		match self.len() {
			0 => None,
			len => Some(unsafe { (len - 1).get_unchecked_mut(self) }),
		}
	}

	/// Returns a reference to a bit or subslice depending on the type of
	/// `index`.
	///
	/// - If given a position, returns a reference to the bit at that position
	///   or `None` if out of bounds.
	/// - If given a range, returns the subslice corresponding to that range, or
	///   `None` if out of bounds.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 1u8;
	/// let bits = data.bits::<Lsb0>();
	/// assert_eq!(Some(&true), bits.get(0));
	/// assert!(bits.get(8).is_none());
	/// assert!(bits.get(1 ..).expect("in bounds").not_any());
	/// assert!(bits.get(.. 12).is_none());
	/// ```
	#[inline]
	pub fn get<'a, I>(&'a self, index: I) -> Option<I::Immut>
	where I: BitSliceIndex<'a, O, T> {
		index.get(self)
	}

	/// Returns a mutable reference to a bit or subslice depending on the type
	/// of `index` (see [`get`]) or `None` if the index is out of bounds.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Lsb0>();
	/// if let Some(mut bit) = bits.get_mut(1) {
	///     *bit = true;
	/// }
	/// if let Some(bits) = bits.get_mut(5 .. 7) {
	///     bits.set_all(true);
	/// }
	/// assert_eq!(data, 64 | 32 | 2);
	/// ```
	///
	/// [`get`]: #method.get
	#[inline]
	pub fn get_mut<'a, I>(&'a mut self, index: I) -> Option<I::Mut>
	where I: BitSliceIndex<'a, O, T> {
		index.get_mut(self)
	}

	/// Returns a reference to a bit or subslice, without doing bounds checking.
	///
	/// This is generally not recommended; use with caution! For a safe
	/// alternative, see [`get`].
	///
	/// # Safety
	///
	/// As this function does not perform boundary checking, the caller must
	/// ensure that `self` is an index within the boundaries of `slice` before
	/// calling in order to avoid boundary escapes and ensuing safety
	/// violations.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 4u8;
	/// let bits = data.bits::<Lsb0>();
	/// unsafe {
	///     assert!(bits.get_unchecked(2));
	///     assert!(!bits.get_unchecked(1));
	/// }
	/// ```
	///
	/// [`get`]: #method.get
	#[inline]
	pub unsafe fn get_unchecked<'a, I>(&'a self, index: I) -> I::Immut
	where I: BitSliceIndex<'a, O, T> {
		index.get_unchecked(self)
	}

	/// Returns a mutable reference to a bit or subslice, without doing bounds
	/// checking.
	///
	/// This is generally not recommended; use with caution! For a safe
	/// alternative, see [`get_mut`].
	///
	/// # Safety
	///
	/// As this function does not perform boundary checking, the caller must
	/// ensure that `self` is an index within the boundaries of `slice` before
	/// calling in order to avoid boundary escapes and ensuing safety
	/// violations.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// unsafe {
	///     let mut bit = bits.get_unchecked_mut(0);
	///     *bit = true;
	///     drop(bit); // release the borrow immediately
	///     let bits = bits.get_unchecked_mut(6 ..);
	///     bits.set_all(true);
	/// }
	/// assert_eq!(data, 1 | 2 | 128);
	/// ```
	///
	/// [`get_mut`]: #method.get_mut
	#[inline]
	pub unsafe fn get_unchecked_mut<'a, I>(&'a mut self, index: I) -> I::Mut
	where I: BitSliceIndex<'a, O, T> {
		index.get_unchecked_mut(self)
	}

	/// Returns a raw pointer to the slice’s buffer.
	///
	/// The caller must ensure that the slice outlives the pointer this function
	/// returns, or else it will end up pointing to garbage.
	///
	/// The caller must also ensure that the memory the pointer
	/// (non-transitively) points to is never written to (except inside an
	/// `UnsafeCell`) using this pointer or any pointer derived from it. If you
	/// need to mutate the contents of the buffer, use [`as_mut_ptr`].
	///
	/// Modifying the container referenced by this slice may cause its buffer to
	/// be reallocated, which would also make any pointers to it invalid.
	///
	/// # Notes
	///
	/// This pointer is always to the first `T` element in the backing storage,
	/// even if that element is only partially used by the `self` slice.
	/// Multiple separate `BitSlice` handles may produce the same pointer with
	/// this method.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = [0u8; 2];
	/// let bits = data.bits::<Msb0>();
	/// let (head, rest) = bits.split_at(4);
	/// assert_eq!(head.as_ptr(), rest.as_ptr());
	/// ```
	///
	/// [`as_mut_ptr`]: #method.as_mut_ptr
	//  FIXME(myrrlyn, 2019-10-22): Blocked on issue #57563.
	#[inline]
	pub /* const */ fn as_ptr(&self) -> *const T {
		self.bitptr().pointer().r()
	}

	/// Returns an unsafe mutable pointer to the slice’s buffer.
	///
	/// The caller must ensure thath the slice outlives the pointer this
	/// function returns, or else it will end up pointing to garbage.
	///
	/// Modifying the container referenced by this slice may couse its buffer to
	/// be reallocated, which would also make any pointers to it invalid.
	///
	/// # Notes
	///
	/// This pointer is always to the first `T` element in the backing storage,
	/// even if that element is only partially used by the `self` slice.
	/// Multiple separate `BitSlice` handles may produce the same pointer with
	/// this method.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = [0u8; 2];
	/// let bits = data.bits_mut::<Msb0>();
	/// let (head, rest) = bits.split_at_mut(4);
	/// assert_eq!(head.as_mut_ptr(), rest.as_mut_ptr());
	/// unsafe { *head.as_mut_ptr() = 2; }
	/// assert!(rest[2]);
	/// ```
	#[inline]
	pub fn as_mut_ptr(&mut self) -> *mut T {
		self.bitptr().pointer().w()
	}

	/// Swaps two bits in the slice.
	///
	/// # Arguments
	///
	/// - `a`: The index of the first bit
	/// - `b`: The index of the second bit
	///
	/// # Panics
	///
	/// Panics if `a` or `b` are out of bounds.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 2u8;
	/// let bits = data.bits_mut::<Lsb0>();
	/// bits.swap(0, 1);
	/// assert_eq!(data, 1);
	/// ```
	pub fn swap(&mut self, a: usize, b: usize) {
		let len = self.len();
		assert!(a < len, "Index {} out of bounds: {}", a, len);
		assert!(b < len, "Index {} out of bounds: {}", b, len);
		unsafe { self.swap_unchecked(a, b); }
	}

	/// Reverses the order of bits in the slice, in place.
	///
	/// # Examples
	///
	/// ```rust
	/// use bitvec::prelude::*;
	/// let mut data = 0b1_1001100u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits[1 ..].reverse();
	/// assert_eq!(data, 0b1_0011001);
	/// ```
	pub fn reverse(&mut self) {
		/* This is better implemented as a recursive algorithm, but Rust doesn’t
		yet flatten recursive tail calls into a loop, so it is done manually
		here.
		*/
		let mut cur: &mut Self = self;
		loop {
			let len = cur.len();
			//  Terminate when only one or zero bits remain to switch.
			if len < 2 {
				return;
			}
			let back = len - 1;
			unsafe {
				cur.swap_unchecked(0, back);
				cur = cur.get_unchecked_mut(1 .. back);
			}
		}
	}

	/// Returns an iterator over the slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 3u8;
	/// let bits = data.bits::<Lsb0>();
	/// let mut iter = bits[.. 4].iter();
	/// assert_eq!(iter.next(), Some(&true));
	/// assert_eq!(iter.next(), Some(&true));
	/// assert_eq!(iter.next(), Some(&false));
	/// assert_eq!(iter.next(), Some(&false));
	/// assert!(iter.next().is_none());
	/// ```
	#[inline]
	pub fn iter(&self) -> Iter<O, T> {
		self.into_iter()
	}

	/// Returns an iterator that allows modifying each bit.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = &mut data.bits_mut::<Lsb0>()[.. 2];
	/// for mut bit in bits.iter_mut() {
	///     *bit = true;
	/// }
	/// assert_eq!(data, 3);
	/// ```
	#[inline]
	pub fn iter_mut(&mut self) -> IterMut<O, T> {
		self.into_iter()
	}

	/// Returns an iterator over all contiguous windows of width `width`.
	///
	/// The windows overlap. If the slice is shorter than `width`, the iterator
	/// returns no values.
	///
	/// # Panics
	///
	/// Panics if `width` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b100_010_01u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits[.. 5].windows(3);
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
	/// assert_eq!(iter.next().unwrap(), &bits[1 .. 4]);
	/// assert_eq!(iter.next().unwrap(), &bits[2 .. 5]);
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// If the slice is shorter than `width`:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0u8;
	/// let bits = data.bits::<Local>();
	/// let mut iter = bits[.. 3].windows(4);
	/// assert!(iter.next().is_none());
	pub fn windows(&self, width: usize) -> Windows<O, T> {
		assert_ne!(width, 0, "Window width cannot be zero");
		super::Windows {
			inner: self,
			width,
		}
	}

	/// Returns an iterator over `chunk_size` bits of the slice at a time,
	/// starting at the beginning of the slice.
	///
	/// The chunks are slices and do not overlap. If `chunk_size` does not
	/// divide the length of the slice, then the last chunk will not have length
	/// `chunk_size`.
	///
	/// See [`chunks_exact`] for a variant of this iterator that returns chunks
	/// of always exactly `chunk_size` elements, and [`rchunks`] for the same
	/// iterator but starting at the end of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b001_010_10u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.chunks(3);
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
	/// assert_eq!(iter.next().unwrap(), &bits[3 .. 6]);
	/// assert_eq!(iter.next().unwrap(), &bits[6 .. 8]);
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// [`chunks_exact`]: #method.chunks_exact
	/// [`rchunks`]: #method.rchunks
	pub fn chunks(&self, chunk_size: usize) -> Chunks<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		super::Chunks {
			inner: self,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` bits of the slice at a time,
	/// starting at the beginning of the slice.
	///
	/// The chunks are mutable slices, and do not overlap. If `chunk_size` does
	/// not divide the length of the slice, then the last chunk will not have
	/// length `chunk_size`.
	///
	/// See [`chunks_exact_mut`] for a variant of this iterator that returns
	/// chunks of always exactly `chunk_size` bits, and [`rchunks_mut`] for the
	/// same iterator but starting at the end of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let mut count = 0;
	///
	/// for chunk in bits.chunks_mut(3) {
	///     chunk.store(4u8 >> count);
	///     count += 1;
	/// }
	/// assert_eq!(count, 3);
	/// assert_eq!(data, 0b100_010_01);
	/// ```
	///
	/// [`chunks_exact_mut`]: #method.chunks_exact_mut
	/// [`rchunks_mut`]: #method.rchunks_mut
	pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		super::ChunksMut {
			inner: self,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` elements of the slice at a time,
	/// starting at the beginning of the slice.
	///
	/// The chunks are slices and do not overlap. If `chunk_size` does not
	/// divide the length of the slice, then the last up to `chunk_size - 1`
	/// elements will be omitted and can be retrieved from the `remainder`
	/// function of the iterator.
	///
	/// Due to each chunk having exactly `chunk_size` elements, the compiler can
	/// often optimize the resulting code better than in the case of [`chunks`].
	///
	/// See [`chunks`] for a variant of this iterator that also returns the
	/// remainder as a smaller chunk, and [`rchunks_exact`] for the same
	/// iterator but starting at the end of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b100_010_01u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.chunks_exact(3);
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
	/// assert_eq!(iter.next().unwrap(), &bits[3 .. 6]);
	/// assert!(iter.next().is_none());
	/// assert_eq!(iter.remainder(), &bits[6 .. 8]);
	/// ```
	///
	/// [`chunks`]: #method.chunks
	/// [`rchunks_exact`]: #method.rchunks_exact
	pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		let len = self.len();
		let rem = len % chunk_size;
		let mid = len - rem;
		let (inner, extra) = self.split_at(mid);
		super::ChunksExact {
			inner,
			extra,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` elements of the slice at a time,
	/// starting at the beginning of the slice.
	///
	/// The chunks are mutable slices, and do not overlap. If `chunk_size` does
	/// not divide the length of the slice, then the last up to `chunk_size - 1`
	/// elements will be omitted and can be retrieved from the `into_remainder`
	/// function of the iterator.
	///
	/// Due to each chunk having exactly `chunk_size` elements, the compiler can
	/// often optimize the resulting code better than in the case of
	/// [`chunks_mut`].
	///
	/// See [`chunks_mut`] for a variant of this iterator that also returns the
	/// remainder as a smaller chunk, and [`rchunks_exact_mut`] for the same
	/// iterator but starting at the end of the slice of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let mut count = 0u8;
	///
	/// let mut iter = bits.chunks_exact_mut(3);
	/// for chunk in &mut iter {
	///     chunk.store(4u8 >> count);
	///     count += 1;
	/// }
	/// iter.into_remainder().store(1u8);
	/// assert_eq!(count, 2);
	/// assert_eq!(data, 0b100_010_01);
	/// ```
	///
	/// [`chunks_mut`]: #method.chunks_mut
	/// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
	pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		let len = self.len();
		let rem = len % chunk_size;
		let mid = len - rem;
		let (inner, extra) = self.split_at_mut(mid);
		super::ChunksExactMut {
			inner,
			extra,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` bits of the slice at a time,
	/// starting at the end of the slice.
	///
	/// The chunks are slices and do not overlap. If `chunk_size` does not
	/// divide the length of the slice, then the last chunk will not have length
	/// of the slice, then the last chunk will not have length `chunk_size`.
	///
	/// See [`rchunks_exact`] for a variant of this iterator that returns chunks
	/// of always exactly `chunk_size` bits, and [`chunks`] for the same
	/// iterator but starting at the beginning of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b01_010_100u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.rchunks(3);
	/// assert_eq!(iter.next().unwrap(), &bits[5 .. 8]);
	/// assert_eq!(iter.next().unwrap(), &bits[2 .. 5]);
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 2]);
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// [`chunks`]: #method.chunks
	/// [`rchunks_exact`]: #method.rchunks_exact
	pub fn rchunks(&self, chunk_size: usize) -> RChunks<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		RChunks {
			inner: self,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` bits of the slice at a time,
	/// starting at the end of the slice.
	///
	/// The chunks are mutable slices and do not overlap. If `chunk_size` does
	/// not divide the length of the slice, then the last chunk will not have
	/// length of the slice, then the last chunk will not have length
	/// `chunk_size`.
	///
	/// See [`rchunks_exact_mut`] for a variant of this iterator that returns
	/// chunks of always exactly `chunk_size` bits, and [`chunks_mut`] for the
	/// same iterator but starting at the beginning of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Lsb0>();
	/// let mut count = 0;
	///
	/// for chunk in bits.rchunks_mut(3) {
	///     chunk.store(4u8 >> count);
	///     count += 1;
	/// }
	/// assert_eq!(count, 3);
	/// assert_eq!(data, 0b100_010_01);
	/// ```
	///
	/// [`chunks_mut`]: #method.chunks_mut
	/// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
	pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		RChunksMut {
			inner: self,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` bits of the slice at a time,
	/// starting at the end of the slice.
	///
	/// The chunks are slices and do not overlap. If `chunk_size` does not
	/// divide the length of the slice, then the last up to `chunk_size - 1`
	/// bits will be omitted and can be retrieved from the `remainder` function
	/// of the iterator.
	///
	/// Due to each chunk having exactly `chunk_size` bits, the compiler can
	/// often optimize the resulting code better than in the case of [`chunks`].
	///
	/// See [`rchunks`] for a variant of this iterator that also returns the
	/// remainder as a smaller chunk, and [`chunks_exact`] for the same iterator
	/// but starting at the beginning of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b100_010_01u8;
	/// let bits = data.bits::<Lsb0>();
	/// let mut iter = bits.rchunks_exact(3);
	/// assert_eq!(iter.next().unwrap(), &bits[5 .. 8]);
	/// assert_eq!(iter.next().unwrap(), &bits[2 .. 5]);
	/// assert!(iter.next().is_none());
	/// assert_eq!(iter.remainder(), &bits[0 ..2]);
	/// ```
	///
	/// [`chunks`]: #method.chunks
	/// [`rchunks`]: #method.rchunks
	/// [`chunks_exact`]: #method.chunks_exact
	pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		let (extra, inner) = self.split_at(self.len() % chunk_size);
		RChunksExact {
			inner,
			extra,
			width: chunk_size,
		}
	}

	/// Returns an iterator over `chunk_size` bits of the slice at a time,
	/// starting at the end of the slice.
	///
	/// The chunks are mutable slices, and do not overlap. If `chunk_size` does
	/// not divide the length of the slice, then the last up to `chunk_size - 1`
	/// bits will be omitted and can be retrieved from the `into_remainder`
	/// function of the iterator.
	///
	/// Due to each chunk having exactly `chunk_size` bits, the compiler can
	/// often optimize the resulting code better than in the case of
	/// [`chunks_mut`].
	///
	/// See [`rchunks_mut`] for a variant of this iterator that also returns the
	/// remainder as a smaller chunk, and [`chunks_exact_mut`] for the same
	/// iterator but starting at the beginning of the slice.
	///
	/// # Panics
	///
	/// Panics if `chunk_size` is 0.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Lsb0>();
	/// let mut count = 0;
	/// let mut iter = bits.rchunks_exact_mut(3);
	///
	/// for chunk in &mut iter {
	///     chunk.store(4u8 >> count);
	///     count += 1;
	/// }
	/// iter.into_remainder().store(1u8);
	/// assert_eq!(data, 0b100_010_01);
	/// assert_eq!(count, 2);
	/// ```
	///
	/// [`chunks_mut`]: #method.chunks_mut
	/// [`rchunks_mut`]: #method.rchunks_mut
	/// [`chunks_exact_mut`]: #method.chunks_exact_mut
	pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<O, T> {
		assert_ne!(chunk_size, 0, "Chunk width cannot be zero");
		let (extra, inner) = self.split_at_mut(self.len() % chunk_size);
		RChunksExactMut {
			inner,
			extra,
			width: chunk_size,
		}
	}

	/// Divides one slice into two at an index.
	///
	/// The first will contain all indices from `[0, mid)` (excluding the index
	/// `mid` itself) and the second will contain all indices from `[mid, len)`
	/// (excluding the index `len` itself).
	///
	/// # Panics
	///
	/// Panics if `mid > len`.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0x0Fu8;
	/// let bits = data.bits::<Msb0>();
	///
	/// {
	///     let (left, right) = bits.split_at(0);
	///     assert!(left.is_empty());
	///     assert_eq!(right, bits);
	/// }
	///
	/// {
	///     let (left, right) = bits.split_at(4);
	///     assert!(left.not_any());
	///     assert!(right.all());
	/// }
	///
	/// {
	///     let (left, right) = bits.split_at(8);
	///     assert_eq!(left, bits);
	///     assert!(right.is_empty());
	/// }
	/// ```
	pub fn split_at(&self, mid: usize) -> (&Self, &Self) {
		let len = self.len();
		assert!(mid <= len, "Index {} out of bounds: {}", mid, len);
		unsafe { self.split_at_unchecked(mid) }
	}

	/// Divides one mutable slice into two at an index.
	///
	/// The first will contain all indices from `[0, mid)` (excluding the index
	/// `mid` itself) and the second will contain all indices from `[mid, len)`
	/// (excluding the index `len` itself).
	///
	/// # Panics
	///
	/// Panics if `mid > len`.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0x0Fu8;
	/// let bits = data.bits_mut::<Msb0>();
	///
	/// let (left, right) = bits.split_at_mut(4);
	/// assert!(left.not_any());
	/// assert!(right.all());
	/// *left.at(1) = true;
	/// *right.at(2) = false;
	///
	/// assert_eq!(data, 0b0100_1101);
	/// ```
	#[inline]
	pub fn split_at_mut(&mut self, mid: usize) -> (&mut Self, &mut Self) {
		let (head, tail) = self.split_at(mid);
		(head.bitptr().into_bitslice_mut(), tail.bitptr().into_bitslice_mut())
	}

	/// Returns an iterator over subslices separated by indexed bits that
	/// satisfy the predicate `func`tion. The matched position is not contained
	/// in the subslices.
	///
	/// # API Differences
	///
	/// The [`slice::split`] method takes a predicate function with signature
	/// `(&T) -> bool`, whereas this method’s predicate function has signature
	/// `(usize, &T) -> bool`. This difference is in place because `BitSlice` by
	/// definition has only one bit of information per slice item, and including
	/// the index allows the callback function to make more informed choices.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b01_001_000u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.split(|pos, bit| *bit);
	///
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 1]);
	/// assert_eq!(iter.next().unwrap(), &bits[2 .. 4]);
	/// assert_eq!(iter.next().unwrap(), &bits[5 .. 8]);
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// If the first position is matched, an empty slice will be the first item
	/// returned by the iterator. Similarly, if the last position in the slice
	/// is matched, an empty slice will be the last item returned by the
	/// iterator:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 1u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.split(|pos, bit| *bit);
	///
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 7]);
	/// assert_eq!(iter.next().unwrap(), BitSlice::<Local, usize>::empty());
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// If two matched positions are directly adjacent, an empty slice will be
	/// present between them.
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b001_100_00u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.split(|pos, bit| *bit);
	///
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 2]);
	/// assert_eq!(iter.next().unwrap(), BitSlice::<Local, usize>::empty());
	/// assert_eq!(iter.next().unwrap(), &bits[4 .. 8]);
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// [`slice::split`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split
	#[inline]
	pub fn split<F>(&self, func: F) -> Split<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		Split {
			inner: self,
			place: Some(0),
			func,
		}
	}

	/// Returns an iterator over mutable subslices separated by indexed bits
	/// that satisfy the predicate `func`tion. The matched position is not
	/// contained in the subslices.
	///
	/// # API Differences
	///
	/// The [`slice::split_mut`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0b001_000_10u8;
	/// let bits = data.bits_mut::<Msb0>();
	///
	/// for group in bits.split_mut(|pos, bit| *bit) {
	///     *group.at(0) = true;
	/// }
	/// assert_eq!(data, 0b101_1001_1u8);
	/// ```
	///
	/// [`slice::split_mut`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.split_mut
	#[inline]
	pub fn split_mut<F>(&mut self, func: F) -> SplitMut<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		SplitMut {
			inner: self,
			place: Some(0),
			func,
		}
	}

	/// Returns an iterator over subslices separated by indexed bits that
	/// satisfy a predicate `func`tion, starting at the end of the slice and
	/// working backwards. The matched position is not contained in the
	/// subslices.
	///
	/// # API Differences
	///
	/// The [`slice::rsplit`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b0001_0000u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.rsplit(|pos, bit| *bit);
	///
	/// assert_eq!(iter.next().unwrap(), &bits[4 .. 8]);
	/// assert_eq!(iter.next().unwrap(), &bits[0 .. 3]);
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// As with `split()`, if the first or last position is matched, an empty
	/// slice will be the first (or last) item returned by the iterator.
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b1001_0001u8;
	/// let bits = data.bits::<Msb0>();
	/// let mut iter = bits.rsplit(|pos, bit| *bit);
	/// assert!(iter.next().unwrap().is_empty());
	/// assert_eq!(iter.next().unwrap(), &bits[4 .. 7]);
	/// assert_eq!(iter.next().unwrap(), &bits[1 .. 3]);
	/// assert!(iter.next().unwrap().is_empty());
	/// assert!(iter.next().is_none());
	/// ```
	///
	/// [`slice::rsplit`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rsplit
	#[inline]
	pub fn rsplit<F>(&self, func: F) -> RSplit<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		RSplit {
			inner: self.split(func),
		}
	}

	/// Returns an iterator over mutable subslices separated by indexed bits
	/// that satisfy a predicate `func`tion, starting at the end of the slice
	/// and working backwards. The matched position is not contained in the
	/// subslices.
	///
	/// # API Differences
	///
	/// The [`slice::rsplit_mut`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	///
	/// let mut count = 0u8;
	/// for group in bits.rsplit_mut(|pos, bit| pos % 3 == 2) {
	///     count += 1;
	///     group.store(count);
	/// }
	/// assert_eq!(data, 0b11_0_10_0_01);
	/// ```
	///
	/// [`slice::rsplit_mut`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rsplit_mut
	#[inline]
	pub fn rsplit_mut<F>(&mut self, func: F) -> RSplitMut<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		RSplitMut {
			inner: self.split_mut(func),
		}
	}

	/// Returns an iterator over subslices separated by indexed bits that
	/// satisfy the predicate `func`tion, limited to returning at most `n`
	/// items. The matched position is not contained in the subslices.
	///
	/// The last element returned, if any, will contain the remainder of the
	/// slice.
	///
	/// # API Differences
	///
	/// The [`slice::splitn`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// Print the slice split once by indices divisible by 3:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0xA5u8;
	/// let bits = data.bits::<Msb0>();
	///
	/// for group in bits.splitn(2, |pos, bit| pos % 3 == 2) {
	///     println!("{}", group);
	/// }
	/// //  [10]
	/// //  [00101]
	/// ```
	///
	/// [`slice::splitn`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.splitn
	#[inline]
	pub fn splitn<F>(&self, n: usize, func: F) -> SplitN<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		SplitN {
			inner: GenericSplitN {
				inner: self.split(func),
				count: n,
			}
		}
	}

	/// Returns an iterator over mutable subslices separated by indexed bits
	/// that satisfy the predicate `func`tion, limited to returning at most `n`
	/// items. The matched position is not contained in the subslices.
	///
	/// The last element returned, if any, will contain the remainder of the
	/// slice.
	///
	/// # API Differences
	///
	/// The [`slice::splitn_mut`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let mut counter = 0u8;
	///
	/// for group in bits.splitn_mut(2, |pos, bit| pos % 4 == 3) {
	///     counter += 1;
	///     group.store(counter);
	/// }
	/// assert_eq!(data, 0b001_0_0010);
	/// ```
	///
	/// [`slice::splitn_mut`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.splitn_mut
	#[inline]
	pub fn splitn_mut<F>(&mut self, n: usize, func: F) -> SplitNMut<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		SplitNMut {
			inner: GenericSplitN {
				inner: self.split_mut(func),
				count: n,
			}
		}
	}

	/// Returns an iterator over subslices separated by indexed bits that
	/// satisfy a predicate `func`tion, limited to returning at most `n` items.
	/// This starts at the end of the slice and works backwards. The matched
	/// position is not contained in the subslices.
	///
	/// The last element returned, if any, will contain the remainder of the
	/// slice.
	///
	/// # API Differences
	///
	/// The [`slice::rsplitn`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// Print the slice split once, starting from the end, by indices divisible
	/// by 3:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0xA5u8;
	/// let bits = data.bits::<Msb0>();
	///
	/// for group in bits.rsplitn(2, |pos, bit| pos % 3 == 2) {
	///     println!("{}", group);
	/// }
	/// //  [01]
	/// //  [10100]
	/// ```
	///
	/// [`slice::rsplitn`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rsplitn
	#[inline]
	pub fn rsplitn<F>(&self, n: usize, func: F) -> RSplitN<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		RSplitN {
			inner: GenericSplitN {
				inner: self.rsplit(func),
				count: n,
			}
		}
	}

	/// Returns an iterator over mutable subslices separated by indexed bits
	/// that satisfy a predicate `func`tion, limited to returning at most `n`
	/// items. This starts at the end of the slice and works backwards. The
	/// matched position is not contained in the subslices.
	///
	/// The last element returned, if any, will contain the remainder of the
	/// slice.
	///
	/// # API Differences
	///
	/// The [`slice::rsplitn_mut`] method takes a predicate function with
	/// signature `(&T) -> bool`, whereas this method’s predicate function has
	/// signature `(usize, &T) -> bool`. This difference is in place because
	/// `BitSlice` by definition has only one bit of information per slice item,
	/// and including the index allows the callback function to make more
	/// informed choices.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let mut counter = 0u8;
	///
	/// for group in bits.rsplitn_mut(2, |pos, bit| pos % 3 == 2) {
	///     counter += 1;
	///     group.store(counter);
	/// }
	/// assert_eq!(data, 0b00010_0_01);
	/// ```
	///
	/// [`slice::rsplitn_mut`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.rsplitn_mut
	#[inline]
	pub fn rsplitn_mut<F>(&mut self, n: usize, func: F) -> RSplitNMut<'_, O, T, F>
	where F: FnMut(usize, &bool) -> bool {
		RSplitNMut {
			inner: GenericSplitN {
				inner: self.rsplit_mut(func),
				count: n,
			}
		}
	}

	/// Returns `true` if the slice contains a region that matches the given
	/// span.
	///
	/// # API Differences
	///
	/// The [`slice::contains`] method tests for a single slice element.
	/// Because this is a slice of single bits, testing for the presence of one
	/// `bool` value is not very informative. This instead searches for a
	/// subslice, which may be one or more bits.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b0101_1010u8;
	/// let bits_be = data.bits::<Msb0>();
	/// let bits_le = data.bits::<Lsb0>();
	/// assert!(bits_be.contains(&bits_le[1 .. 5]));
	/// ```
	///
	/// This example uses a palindrome pattern to demonstrate that the query
	/// does not need to have the same type parameters as the searched slice.
	///
	/// [`slice::contains`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.contains
	pub fn contains<P, U>(&self, query: &BitSlice<P, U>) -> bool
	where P: BitOrder, U: BitStore {
		let len = query.len();
		if len > self.len() {
			return false;
		}
		self.windows(len).any(|s| s == query)
	}

	/// Returns `true` if `prefix` is a prefix of the slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b0110_1110u8;
	/// let bits = data.bits::<Msb0>();
	/// assert!(bits.starts_with(&data.bits::<Lsb0>()[.. 2]));
	/// ```
	pub fn starts_with<P, U>(&self, prefix: &BitSlice<P, U>) -> bool
	where P: BitOrder, U: BitStore {
		let plen = prefix.len();
		self.len() >= plen && prefix == unsafe { self.get_unchecked(.. plen) }
	}

	/// Returns `true` if `suffix` is a suffix of the slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = 0b0111_1010u8;
	/// let bits = data.bits::<Msb0>();
	/// assert!(bits.ends_with(&data.bits::<Lsb0>()[6 ..]));
	/// ```
	pub fn ends_with<P, U>(&self, suffix: &BitSlice<P, U>) -> bool
	where P: BitOrder, U: BitStore, {
		let slen = suffix.len();
		let len = self.len();
		len >= slen && suffix == unsafe { self.get_unchecked(len - slen ..) }
	}

	/// Rotates the slice in-place such that the first `by` bits of the slice
	/// move to the end while the last `self.len() - by` bits move to the
	/// front. After calling `rotate_left`, the bit previously at index `by`
	/// will become the first bit in the slice.
	///
	/// # Panics
	///
	/// This function will panic if `by` is greater than the length of the
	/// slice. Note that `by == self.len()` does *not* panic and is a noöp
	/// rotation.
	///
	/// # Complexity
	///
	/// Takes linear (in `self.len()`) time.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0xF0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits.rotate_left(2);
	/// assert_eq!(data, 0xC3);
	/// ```
	///
	/// Rotating a subslice:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0xF0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits[1 .. 5].rotate_left(1);
	/// assert_eq!(data, 0b1_1101_000);
	/// ```
	pub fn rotate_left(&mut self, mut by: usize) {
		let len = self.len();
		assert!(by <= len, "Slices cannot be rotated by more than their length");
		if by == 0 || by == len {
			return;
		}

		/* Rotation can be accelerated by copying chunks out onto the stack,
		then moving each bit down by a longer distance. This block collects up
		to a single `usize`’s worth of bits from the start of the slice, then
		moves all remaining bits down by the collection amount, then writes the
		collected bits into the back of the slice. While this is does not affect
		the length-determined runtime cost, it does reduce the
		distance-determined cost by a factor of the target word width.
		*/
		let mut tmp = 0usize;
		let bits = BitSlice::<O, _>::from_element_mut(&mut tmp);

		while by > 0 {
			//  Clamp the collection count by the word size and shift distance.
			let shamt = cmp::min(usize::BITS as usize, by);
			//  Bounds checking is already performed. This block erases all
			//  interior checks in the iteration body.
			unsafe {
				//  Collect bits from the front of the slice into scratch.
				bits.get_unchecked_mut(.. shamt)
					.clone_from_slice(self.get_unchecked(.. shamt));
				//  Move all remaining bits down to the front of the slice.
				for (to, from) in (shamt .. len).enumerate() {
					self.copy_unchecked(from, to);
				}
				//  Emit the scratch bits into the back of the slice.
				self.get_unchecked_mut(len - shamt ..)
					.clone_from_slice(bits.get_unchecked(.. shamt));
			}
			by -= shamt;
		}
	}

	/// Rotates the slice in-place such that the first `self.len() - by` bits of
	/// the slice move to the end while the last `by` bits move to the front.
	/// After calling `rotate_right`, the bit previously at index
	/// `self.len() - by` will become the first bit in the slice.
	///
	/// # Panics
	///
	/// This function will panic if `by` is greater than the length of the
	/// slice. Note that `by == self.len()` does *not* panic and is a noöp
	/// rotation.
	///
	/// # Complexity
	///
	/// Takes linear (in `self.len()`) time.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0xF0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits.rotate_right(2);
	/// assert_eq!(data, 0x3C);
	/// ```
	///
	/// Rotate a subslice:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0xF0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits[1 .. 5].rotate_right(1);
	/// assert_eq!(data, 0b1_0111_000);
	/// ```
	pub fn rotate_right(&mut self, mut by: usize) {
		let len = self.len();
		assert!(by <= len, "Slices cannot be rotated by more than their length");
		if by == 0 || by == len {
			return;
		}

		/* Rotation can be accelerated by copying chunks out onto the stack,
		then moving each bit down by a longer distance. This block collects up
		to a single `usize`’s worth of bits from the end of the slice, then
		moves all remaining bits up by the collection amount, then writes the
		collected bits into the front of the slice. While this is does not
		affect the length-determined runtime cost, it does reduce the
		distance-determined cost by a factor of the target word width.
		*/
		let mut tmp = 0usize;
		let bits = BitSlice::<O, _>::from_element_mut(&mut tmp);

		while by > 0 {
			//  Clamp the collection count by the word size and shift distance.
			let shamt = cmp::min(usize::BITS as usize, by);
			//  Bounds checking is already performed. This block erases all
			//  interior checks in the iteration body.
			unsafe {
				//  Collect bits from the back of the slice into scratch.
				bits.get_unchecked_mut(.. shamt)
					.clone_from_slice(self.get_unchecked(len - shamt ..));
				//  Move all remaining bits up to the back of the slice.
				for (from, to) in (shamt .. len).enumerate().rev() {
					self.copy_unchecked(from, to);
				}
				//  Emit the scratch bits into the front of the slice.
				self.get_unchecked_mut(.. shamt)
					.clone_from_slice(bits.get_unchecked(.. shamt));
			}
			by -= shamt;
		}
	}

	/// Copies the elements from `src` into `self`.
	///
	/// The length of `src` must be the same as `self`.
	///
	/// This is equivalent to `copy_from_slice`; this function is only included
	/// for API surface equivalence.
	///
	/// # Panics
	///
	/// This function will panic if the two slices have different lengths.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let src = 0x0Fu16.bits::<Lsb0>();
	/// bits.clone_from_slice(&src[.. 8]);
	/// assert_eq!(data, 0xF0);
	/// ```
	///
	/// Rust enforces that there can only be one mutable reference with no
	/// immutable references to a particular piece of data in a particular
	/// scope. Because of this, attempting to use `clone_from_slice` on a single
	/// slice will result in a compile failure:
	///
	/// ```rust,compile_fail
	/// # use bitvec::prelude::*;
	/// let mut data = 3u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits[.. 2].clone_from_slice(&bits[6 ..]);
	/// ```
	///
	/// To work around this, we can use [`split_at_mut`] to create two distinct
	/// sub-slices from a slice:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 3u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let (head, tail) = bits.split_at_mut(4);
	/// head.clone_from_slice(tail);
	/// assert_eq!(data, 0x33);
	/// ```
	pub fn clone_from_slice<P, U>(&mut self, src: &BitSlice<P, U>)
	where P: BitOrder, U: BitStore {
		assert_eq!(
			self.len(),
			src.len(),
			"Cloning from slice requires equal lengths",
		);
		for idx in 0 .. self.len() {
			unsafe {
				self.set_unchecked(idx, *src.get_unchecked(idx));
			}
		}
	}

	/// Copies the elements from `src` into `self`.
	///
	/// The length of `src` must be the same as `self`.
	///
	/// This is restricted to take exactly the same type of bit slice as the
	/// source slice, so that the implementation has the chace to use faster
	/// `memcpy` if possible.
	///
	/// # Panics
	///
	/// This function will panic if the two slices have different lengths.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 0u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let src = 0x0Fu8.bits::<Msb0>();
	/// bits.copy_from_slice(src);
	/// assert_eq!(data, 0x0F);
	/// ```
	///
	/// Rust enforces that there can only be one mutable reference with no
	/// immutable references to a particular piece of data in a particular
	/// scope. Because of this, attempting to use `copy_from_slice` on a single
	/// slice will result in a compile failure:
	///
	/// ```rust,compile_fail
	/// # use bitvec::prelude::*;
	/// let mut data = 3u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits[.. 2].copy_from_slice(&bits[6 ..]);
	/// ```
	///
	/// To work around this, we can use [`split_at_mut`] to create two distinct
	/// sub-slices from a slice:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 3u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// let (head, tail) = bits.split_at_mut(4);
	/// head.copy_from_slice(tail);
	/// assert_eq!(data, 0x33);
	/// ```
	pub fn copy_from_slice(&mut self, src: &Self) {
		self.clone_from_slice(src)
	}

	/// Swaps all bits in `self` with those in `other`.
	///
	/// The length of `other` must be the same as `self`.
	///
	/// # Panics
	///
	/// This function will panic if the two slices hav different lengths.
	///
	/// # Example
	///
	/// Swapping two elements across slices:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut a = 0u8;
	/// let mut b = 0x96A5u16;
	/// let bits_a = a.bits_mut::<Lsb0>();
	/// let bits_b = b.bits_mut::<Msb0>();
	///
	/// bits_a.swap_with_slice(&mut bits_b[4 .. 12]);
	///
	/// assert_eq!(a, 0x56);
	/// assert_eq!(b, 0x9005);
	/// ```
	///
	/// Rust enforces that there can only be one mutable reference to a
	/// particular piece of data in a particular scope. Because of this,
	/// attempting to use `swap_with_slice` on a single slice will result in a
	/// compile failure:
	///
	/// ```rust,compile_fail
	/// # use bitvec::prelude::*;
	/// let mut data = 15u8;
	/// let bits = data.bits_mut::<Msb0>();
	/// bits[.. 3].swap_with_slice(&mut bits[5 ..]);
	/// ```
	///
	/// To work around this, we can use [`split_at_mut`] to create two distinct
	/// mutable sub-slices from a slice:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let mut data = 15u8;
	/// let bits = data.bits_mut::<Msb0>();
	///
	/// {
	///     let (left, right) = bits.split_at_mut(4);
	///     left[.. 2].swap_with_slice(&mut right[2 ..]);
	/// }
	///
	/// assert_eq!(data, 0xCC);
	/// ```
	pub fn swap_with_slice<P, U>(&mut self, other: &mut BitSlice<P, U>)
	where P: BitOrder, U: BitStore {
		assert_eq!(
			self.len(),
			other.len(),
			"Swapping between slices requires equal lengths",
		);
		self.iter_mut().zip(other.iter_mut()).for_each(|(mut this, mut that)| {
			let (a, b) = (*this, *that);
			*this = b;
			*that = a;
		})
	}

	/// Transmute the slice to a slice with a different backing store, ensuring
	/// alignment of the types is maintained.
	///
	/// This method splits the slice into three distinct slices: prefix,
	/// correctly aligned middle slice of a new backing type, and the suffix
	/// slice. The method does a best effort to make the middle slice the
	/// greatest length possible for a given type and input slice, but only your
	/// algorithm’s performance should depend on that, not its correctness.
	///
	/// # Safety
	///
	/// This method is essentially a `transmute` with respect to the elements in
	/// the returned middle slice, so all the usual caveats pertaining to
	/// `transmute::<T, U>` also apply here.
	///
	/// # Examples
	///
	/// Basic usage:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// unsafe {
	///     let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
	///     let bits = bytes.bits::<Local>();
	///     let (prefix, shorts, suffix) = bits.align_to::<u16>();
	///     match prefix.len() {
	///         0 => {
	///             assert_eq!(shorts, bits[.. 48]);
	///             assert_eq!(suffix, bits[48 ..]);
	///         },
	///         8 => {
	///             assert_eq!(prefix, bits[.. 8]);
	///             assert_eq!(shorts, bits[8 ..]);
	///         },
	///         _ => unreachable!("This case will not occur")
	///     }
	/// }
	/// ```
	pub unsafe fn align_to<U>(&self) -> (&Self, &BitSlice<O, U>, &Self)
	where U: BitStore {
		let bitptr = self.bitptr();
		let (l, c, r) = bitptr.as_slice().align_to::<U>();
		let l_start = *bitptr.head() as usize;
		let l = &Self::from_slice(l)[l_start ..];
		let c = BitSlice::from_slice(c);
		let r = &Self::from_slice(r)[.. bitptr.len() - l.len() - c.len()];
		(l, c, r)
	}

	/// Transmute the slice to a slice with a different backing store, ensuring
	/// alignment of the types is maintained.
	///
	/// This method splits the slice into three distinct slices: prefix,
	/// correctly aligned middle slice of a new backing type, and the suffix
	/// slice. The method does a best effort to make the middle slice the
	/// greatest length possible for a given type and input slice, but only your
	/// algorithm’s performance should depend on that, not its correctness.
	///
	/// # Safety
	///
	/// This method is essentially a `transmute` with respect to the elements in
	/// the returned middle slice, so all the usual caveats pertaining to
	/// `transmute::<T, U>` also apply here.
	///
	/// # Examples
	///
	/// Basic usage:
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// unsafe {
	///     let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
	///     let bits = bytes.bits_mut::<Local>();
	///     let (prefix, shorts, suffix) = bits.align_to_mut::<u16>();
	///     //  same access and behavior as in `align_to`
	/// }
	/// ```
	#[inline]
	pub unsafe fn align_to_mut<U>(&mut self) -> (
		&mut Self,
		&mut BitSlice<O, U>,
		&mut Self,
	)
	where U: BitStore {
		let (l, c, r) = self.align_to::<U>();
		(
			l.bitptr().into_bitslice_mut(),
			c.bitptr().into_bitslice_mut(),
			r.bitptr().into_bitslice_mut(),
		)
	}

	/// Copies `self` into a new `BitVec`.
	///
	/// # Examples
	///
	/// ```rust
	/// # use bitvec::prelude::*;
	/// let data = [0u8, !0u8];
	/// let bits = data.bits::<Local>();
	/// let vec = bits.to_vec();
	/// assert_eq!(bits, vec);
	/// ```
	#[cfg(feature = "alloc")]
	#[inline]
	pub fn to_vec(&self) -> BitVec<O, T> {
		BitVec::from_bitslice(self)
	}
}

/** Replacement for [`slice::SliceIndex`].

This trait is stabilized in definition and `type Output` only, but all methods
are unstable. This makes it unusable in non-`libstd` slice libraries, and so it
must be duplicated here.

There is no tracking issue for `feature(slice_index_methods)`.

[`slice::SliceIndex`]: https://doc.rust-lang.org/stable/core/slice/trait.SliceIndex.html
**/
pub trait BitSliceIndex<'a, O, T>
where O: 'a + BitOrder, T: 'a + BitStore {
	/// Immutable output type.
	type Immut;

	/// Mutable output type. This is necessary because `&mut BitSlice` is
	/// producible for range indices, but `&mut bool` is not producable for
	/// `usize` indices.
	type Mut;

	/// Returns a shared reference to the output at this location, if in bounds.
	///
	/// # Parameters
	///
	/// - `self`: The index value.
	/// - `slice`: The slice under index.
	///
	/// # Returns
	///
	/// An immutable output, if `self` is in bounds; otherwise `None`.
	fn get(self, slice: &'a BitSlice<O, T>) -> Option<Self::Immut>;

	/// Returns a mutable reference to the output at this location, if in
	/// bounds.
	///
	/// # Parameters
	///
	/// - `self`: The index value.
	/// - `slice`: The slice under index.
	///
	/// # Returns
	///
	/// A mutable output, if `self` is in bounds; otherwise `None`.
	fn get_mut(self, slice: &'a mut BitSlice<O, T>) -> Option<Self::Mut>;

	/// Returns a shared reference to the output at this location, without
	/// performing any bounds checking.
	///
	/// # Parameters
	///
	/// - `self`: The index value.
	/// - `slice`: The slice under index.
	///
	/// # Returns
	///
	/// An immutable output.
	///
	/// # Safety
	///
	/// As this function does not perform boundary checking, the caller must
	/// ensure that `self` is an index within the boundaries of `slice` before
	/// calling in order to avoid boundary escapes and ensuing safety
	/// violations.
	unsafe fn get_unchecked(self, slice: &'a BitSlice<O, T>) -> Self::Immut;

	/// Returns a mutable reference to the output at this location, without
	/// performing any bounds checking.
	///
	/// # Parameters
	///
	/// - `self`: The index value.
	/// - `slice`: The slice under index.
	///
	/// # Returns
	///
	/// A mutable output.
	///
	/// # Safety
	///
	/// As this function does not perform boundary checking, the caller must
	/// ensure that `self` is an index within the boundaries of `slice` before
	/// calling in order to avoid boundary escapes and ensuing safety
	/// violations.
	unsafe fn get_unchecked_mut(
		self,
		slice: &'a mut BitSlice<O, T>,
	) -> Self::Mut;

	/// Returns a shared reference to the output at this location, panicking if
	/// out of bounds.
	///
	/// # Parameters
	///
	/// - `self`: The index value.
	/// - `slice`: The slice under index.
	///
	/// # Returns
	///
	/// An immutable output.
	///
	/// # Panics
	///
	/// This panics if `self` is out of bounds of `slice`.
	fn index(self, slice: &'a BitSlice<O, T>) -> Self::Immut;

	/// Returns a mutable reference to the output at this location, panicking if
	/// out of bounds.
	///
	/// # Parameters
	///
	/// - `self`: The index value.
	/// - `slice`: The slice under index.
	///
	/// # Returns
	///
	/// A mutable output.
	///
	/// # Panics
	///
	/// This panics if `self` is out of bounds of `slice`.
	fn index_mut(self, slice: &'a mut BitSlice<O, T>) -> Self::Mut;
}

impl<'a, O, T> BitSliceIndex<'a, O, T> for usize
where O: 'a + BitOrder, T: 'a + BitStore {
	type Immut = &'a bool;
	type Mut = BitMut<'a, O, T>;

	fn get(self, slice: &'a BitSlice<O, T>) -> Option<Self::Immut> {
		if self < slice.len() {
			Some(unsafe { self.get_unchecked(slice) })
		}
		else {
			None
		}
	}

	fn get_mut(self, slice: &'a mut BitSlice<O, T>) -> Option<Self::Mut> {
		if self < slice.len() {
			Some(unsafe { self.get_unchecked_mut(slice) })
		}
		else {
			None
		}
	}

	unsafe fn get_unchecked(self, slice: &'a BitSlice<O, T>) -> Self::Immut {
		let bitptr = slice.bitptr();
		let (elt, bit) = bitptr.head().offset(self as isize);
		let data_ptr = bitptr.pointer().a();

		if (&*data_ptr.offset(elt)).get::<O>(bit) {
			&true
		}
		else {
			&false
		}
	}

	#[inline]
	unsafe fn get_unchecked_mut(
		self,
		slice: &'a mut BitSlice<O, T>,
	) -> Self::Mut {
		let bp = slice.bitptr();
		let (offset, head) = bp.head().offset(self as isize);
		let ptr = bp.pointer().a().offset(offset);
		BitMut {
			_parent: PhantomData,
			data: NonNull::new_unchecked(ptr as *mut T::Access),
			head,
			bit: (*ptr).get::<O>(head)
		}
	}

	fn index(self, slice: &'a BitSlice<O, T>) -> Self::Immut {
		self.get(slice).unwrap_or_else(|| {
			panic!("Index {} out of bounds: {}", self, slice.len())
		})
	}

	fn index_mut(self, slice: &'a mut BitSlice<O, T>) -> Self::Mut {
		let len = slice.len();
		self.get_mut(slice).unwrap_or_else(|| {
			panic!("Index {} out of bounds: {}", self, len)
		})
	}
}

/// This macro allows each range implementation to have its own copy of the
/// trait methods, rather than reshaping the range to route through `Range` and
/// deepen the call AST.
///
/// Only `get` and `get_unchecked` are interesting; the other four methods can
/// all be implemented in terms of these two.
///
/// This macro can be invoked either with definition bodies for `get` and
/// `get_unchecked`, or with a range transform. The latter is useful for
/// converting inclusive ranges to exclusive; the former allows different range
/// shape to perform only the work that they actually need.
macro_rules! range_impl {
	( $( $r:ty => get $get:expr, unchecked $unchecked:expr; )* ) => { $(
		impl<'a, O, T> BitSliceIndex<'a, O, T> for $r
		where O: 'a + BitOrder, T: 'a + BitStore {
			type Immut = &'a BitSlice<O, T>;
			type Mut = &'a mut BitSlice<O, T>;

			fn get(self, slice: Self::Immut) -> Option<Self::Immut> {
				$get(self, slice)
			}

			#[inline]
			fn get_mut(self, slice: Self::Mut) -> Option<Self::Mut> {
				self.get(slice).map(|s| s.bitptr().into_bitslice_mut())
			}

			unsafe fn get_unchecked(self, slice: Self::Immut) -> Self::Immut {
				$unchecked(self, slice)
			}

			#[inline]
			unsafe fn get_unchecked_mut(self, slice: Self::Mut) -> Self::Mut {
				self.get_unchecked(slice).bitptr().into_bitslice_mut()
			}

			#[inline]
			fn index(self, slice: Self::Immut) -> Self::Immut {
				let r = self.clone();
				let l = slice.len();
				self.clone()
					.get(slice)
					.unwrap_or_else(|| {
						panic!("Range {:?} out of bounds: {}", r, l)
					})
			}

			#[inline]
			fn index_mut(self, slice: Self::Mut) -> Self::Mut {
				self.index(slice).bitptr().into_bitslice_mut()
			}
		}
	)* };

	( $( $r:ty => map $func:expr; )* ) => { $(
		impl<'a, O, T> BitSliceIndex<'a, O, T> for $r
		where O: 'a + BitOrder, T: 'a + BitStore {
			type Immut = &'a BitSlice<O, T>;
			type Mut = &'a mut BitSlice<O, T>;

			#[inline]
			fn get(self, slice: Self::Immut) -> Option<Self::Immut> {
				$func(self).get(slice)
			}

			#[inline]
			fn get_mut(self, slice: Self::Mut) -> Option<Self::Mut> {
				$func(self).get_mut(slice)
			}

			#[inline]
			unsafe fn get_unchecked(self, slice: Self::Immut) -> Self::Immut {
				$func(self).get_unchecked(slice)
			}

			#[inline]
			unsafe fn get_unchecked_mut(self, slice: Self::Mut) -> Self::Mut {
				$func(self).get_unchecked_mut(slice)
			}

			#[inline]
			fn index(self, slice: Self::Immut) -> Self::Immut {
				$func(self).index(slice)
			}

			#[inline]
			fn index_mut(self, slice: Self::Mut) -> Self::Mut {
				$func(self).index_mut(slice)
			}
		}
	)* };
}

range_impl! {
	Range<usize> => get |Range { start, end }, slice: Self::Immut| {
		let len = slice.len();

		if start > len || end > len || start > end {
			return None;
		}

		Some(unsafe { (start .. end).get_unchecked(slice) })
	},
	unchecked |Range { start, end }, slice: Self::Immut| {
		let (data, head, _) = slice.bitptr().raw_parts();

		let (skip, new_head) = head.offset(start as isize);

		BitPtr::new_unchecked(
			data.r().offset(skip),
			new_head,
			end - start,
		).into_bitslice()
	};

	RangeFrom<usize> => get |RangeFrom { start }, slice: Self::Immut| {
		let len = slice.len();
		if start <= len {
			Some(unsafe { (start ..).get_unchecked(slice) })
		}
		else {
			None
		}
	},
	unchecked |RangeFrom { start }, slice: Self::Immut| {
		let (data, head, bits) = slice.bitptr().raw_parts();

		let (skip, new_head) = head.offset(start as isize);

		BitPtr::new_unchecked(
			data.r().offset(skip),
			new_head,
			bits - start,
		).into_bitslice()
	};

	// `.. end` just changes the length
	RangeTo<usize> => get |RangeTo { end }, slice: Self::Immut| {
		let len = slice.len();
		if end <= len {
			Some(unsafe { (.. end).get_unchecked(slice) })
		}
		else {
			None
		}
	},
	unchecked |RangeTo { end }, slice: Self::Immut| {
		let mut bp = slice.bitptr();
		bp.set_len(end);
		bp.into_bitslice()
	};
}

range_impl! {
	RangeInclusive<usize> => map |this: Self| {
		#[allow(clippy::range_plus_one)]
		(*this.start() .. *this.end() + 1)
	};

	RangeToInclusive<usize> => map |RangeToInclusive { end }| {
		#[allow(clippy::range_plus_one)]
		(.. end + 1)
	};
}

/// `RangeFull` is the identity function.
impl<'a, O, T> BitSliceIndex<'a, O, T> for RangeFull
where O: 'a + BitOrder, T: 'a + BitStore {
	type Immut = &'a BitSlice<O, T>;
	type Mut = &'a mut BitSlice<O, T>;

	#[inline]
	fn get(self, slice: Self::Immut) -> Option<Self::Immut> {
		Some(slice)
	}

	#[inline]
	fn get_mut(self, slice: Self::Mut) -> Option<Self::Mut> {
		Some(slice)
	}

	#[inline]
	unsafe fn get_unchecked(self, slice: Self::Immut) -> Self::Immut {
		slice
	}

	#[inline]
	unsafe fn get_unchecked_mut(self, slice: Self::Mut) -> Self::Mut {
		slice
	}

	#[inline]
	fn index(self, slice: Self::Immut) -> Self::Immut {
		slice
	}

	#[inline]
	fn index_mut(self, slice: Self::Mut) -> Self::Mut {
		slice
	}
}