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
/*! `BitSlice` Wide Reference

This module bears some explanation. Let’s get *uncomfortable* here.

Safe Rust is very strict about concepts like lifetimes and size in memory. It
won’t allow you to have arbitrary *references* to things where Rust doesn’t feel
absolutely confident that the referent will outlive the reference, and it won’t
let you have things *at all* that it can't size at compile time. This makes
dealing with runtime-sized memory of uncertain lifetime tricky to do, and the
language provides some tools out of the box for this: slice references, which
store a pointer and also a length, and do so in a manner vaguely obscured to the
rest of Rust code behind opaque stdlib types.

My first instinct was to define `BitSlice` as a newtype wrapper around an `&T`,
so that `BitSlice` would be sized and manageable directly. Unfortunately, this
parameterizes the lifetime of the reference into the `BitSlice` struct, making
it generic over a lifetime. When I tried to implement `Deref` on `BitVec` to
return a `BitSlice`, I realized I could not do so for two main reasons: one,
`Deref` requires returning a reference to a type, and it is impossible to tell
Rust "this type is a named reference", and two, … the lifetime parameter of
`BitSlice` is not able to be provided by the `Deref` trait, the `deref` trait
function, or even by using Higher Ranked Trait Bounds because HRTB just allows
the creation of a lifetime parameter in items in the trait scope that were not
defined with that lifetime parameter, but without Generic Associated Types it is
impossible to add that lifetime parameter to the associated type `Target`!

Also this ran into mutability issues in regards to the interior reference vs the
wrapper.

So `BitSlice` is a newtype wrapper around `[T]`, and can only be touched as a
reference or mutable reference, and has the advantage that now it can be a
`Deref::Target`.

**DO NOT** create an `&BitSlice` yourself! A slice reference can be made to
count bits using `.into()`.
!*/

use core::{
	cmp::{
		Eq,
		Ord,
		Ordering,
		PartialEq,
		PartialOrd,
	},
	convert::{
		AsMut,
		AsRef,
		From,
	},
	hash::{
		Hash,
		Hasher,
	},
	iter::{
		DoubleEndedIterator,
		ExactSizeIterator,
		Iterator,
		IntoIterator,
	},
	marker::PhantomData,
	mem,
	ops::{
		AddAssign,
		BitAndAssign,
		BitOrAssign,
		BitXorAssign,
		Index,
		Neg,
		Not,
		ShlAssign,
		ShrAssign,
	},
	ptr,
	slice,
};

#[cfg(feature = "alloc")]
use core::fmt::{
	self,
	Debug,
	Display,
	Formatter,
};

#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::borrow::ToOwned;

#[cfg(feature = "std")]
use std::borrow::ToOwned;

/** A compact slice of bits, whose cursor and storage type can be customized.

`BitSlice` is a newtype wrapper over `[T]`, and as such can only be held by
reference. It is impossible to create a `Box<BitSlice<C, T>>` from this library,
and assembling one yourself is Undefined Behavior for which this library is not
responsible. **Do not try to create a `Box<BitSlice>`.** If you want an owned
bit collection, use `BitVec`. (This may change in a future release.)

`BitSlice` is strictly a reference type. The memory it governs must be owned by
some other type, and a shared or exclusive reference to it as `BitSlice` can be
created by using the `From` implementation on `&BitSlice` and `&mut BitSlice`.

`BitSlice` is to `BitVec` what `[T]` is to `Vec<T>`.

`BitSlice` takes two type parameters.

- `C: Cursor` must be an implementor of the `Cursor` trait. `BitVec` takes a
  `PhantomData` marker for access to the associated functions, and will never
  make use of an instance of the trait. The default implementations,
  `LittleEndian` and `BigEndian`, are zero-sized, and any further
  implementations should be as well, as the invoked functions will never receive
  state.
- `T: Bits` must be a primitive type. Rust decided long ago to not provide a
  unifying trait over the primitives, so `Bits` provides access to just enough
  properties of the primitives for `BitVec` to use. This trait is sealed against
  downstream implementation, and can only be implemented in this crate.
**/
#[repr(transparent)]
pub struct BitSlice<C = crate::BigEndian, T = u8>
where C: crate::Cursor, T: crate::Bits {
	_cursor: PhantomData<C>,
	inner: [T],
}

impl<C, T> BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Gets the bit value at the given position.
	///
	/// The index value is a semantic count, not a bit address. It converts to a
	/// bit position internally to this function.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![0, 0, 1, 0, 0];
	/// let bits: &BitSlice = &bv;
	/// assert!(bits.get(2));
	/// # }
	/// ```
	pub fn get(&self, index: usize) -> bool {
		assert!(index < self.len(), "Index out of range!");
		let (elt, bit) = T::split(index);
		self.as_ref()[elt].get(C::curr::<T>(bit))
	}

	/// Sets the bit value at the given position.
	///
	/// The index value is a semantic count, not a bit address. It converts to a
	/// bit position internally to this function.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv = bitvec![0; 5];
	/// let bits: &mut BitSlice = &mut bv;
	/// bits.set(2, true);
	/// assert!(bits.get(2));
	/// # }
	/// ```
	pub fn set(&mut self, index: usize, value: bool) {
		assert!(index < self.len(), "Index out of range!");
		let (elt, bit) = T::split(index);
		self.as_mut()[elt].set(C::curr::<T>(bit), value);
	}

	/// Returns true if *all* bits in the slice are set (logical `∧`).
	///
	/// # Truth Table
	///
	/// ```text
	/// 0 0 => 0
	/// 0 1 => 0
	/// 1 0 => 0
	/// 1 1 => 1
	/// ```
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let all = bitvec![1; 10];
	/// let any = bitvec![0, 0, 1, 0, 0];
	/// let some = bitvec![1, 1, 0, 1, 1];
	/// let none = bitvec![0; 10];
	///
	/// assert!(all.all());
	/// assert!(!any.all());
	/// assert!(!some.all());
	/// assert!(!none.all());
	/// # }
	/// ```
	pub fn all(&self) -> bool {
		//  Gallop the filled elements
		for elt in self.body() {
			if *elt != T::from(!0) {
				return false;
			}
		}
		//  Walk the partial tail
		if let Some(tail) = self.tail() {
			for bit in 0 .. self.bits() {
				if !tail.get(C::curr::<T>(bit)) {
					return false;
				}
			}
		}
		true
	}

	/// Returns true if *any* bit in the slice is set (logical `∨`).
	///
	/// # Truth Table
	///
	/// ```text
	/// 0 0 => 0
	/// 0 1 => 1
	/// 1 0 => 1
	/// 1 1 => 1
	/// ```
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let all = bitvec![1; 10];
	/// let any = bitvec![0, 0, 1, 0, 0];
	/// let some = bitvec![1, 1, 0, 1, 1];
	/// let none = bitvec![0; 10];
	///
	/// assert!(all.any());
	/// assert!(any.any());
	/// assert!(some.any());
	/// assert!(!none.any());
	/// # }
	/// ```
	pub fn any(&self) -> bool {
		//  Gallop the filled elements
		for elt in self.body() {
			if *elt != T::from(0) {
				return true;
			}
		}
		//  Walk the partial tail
		if let Some(tail) = self.tail() {
			for bit in 0 .. self.bits() {
				if tail.get(C::curr::<T>(bit)) {
					return true;
				}
			}
		}
		false
	}

	/// Returns true if *any* bit in the slice is unset (logical `¬∧`).
	///
	/// # Truth Table
	///
	/// ```text
	/// 0 0 => 1
	/// 0 1 => 1
	/// 1 0 => 1
	/// 1 1 => 0
	/// ```
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let all = bitvec![1; 10];
	/// let any = bitvec![0, 0, 1, 0, 0];
	/// let some = bitvec![1, 1, 0, 1, 1];
	/// let none = bitvec![0; 10];
	///
	/// assert!(!all.not_all());
	/// assert!(any.not_all());
	/// assert!(some.not_all());
	/// assert!(none.not_all());
	/// # }
	/// ```
	pub fn not_all(&self) -> bool {
		!self.all()
	}

	/// Returns true if *all* bits in the slice are unset (logical `¬∨`).
	///
	/// # Truth Table
	///
	/// ```text
	/// 0 0 => 1
	/// 0 1 => 0
	/// 1 0 => 0
	/// 1 1 => 0
	/// ```
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let all = bitvec![1; 10];
	/// let any = bitvec![0, 0, 1, 0, 0];
	/// let some = bitvec![1, 1, 0, 1, 1];
	/// let none = bitvec![0; 10];
	///
	/// assert!(!all.not_any());
	/// assert!(!any.not_any());
	/// assert!(!some.not_any());
	/// assert!(none.not_any());
	/// # }
	/// ```
	pub fn not_any(&self) -> bool {
		!self.any()
	}

	/// Returns true if some, but not all, bits are set and some, but not all,
	/// are unset.
	///
	/// This is false if either `all()` or `none()` are true.
	///
	/// # Truth Table
	///
	/// ```text
	/// 0 0 => 0
	/// 0 1 => 1
	/// 1 0 => 1
	/// 1 1 => 0
	/// ```
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let all = bitvec![1; 2];
	/// let some = bitvec![1, 0];
	/// let none = bitvec![0; 2];
	///
	/// assert!(!all.some());
	/// assert!(some.some());
	/// assert!(!none.some());
	/// # }
	/// ```
	pub fn some(&self) -> bool {
		self.any() && self.not_all()
	}

	/// Counts how many bits are set high.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1];
	/// assert_eq!(bv.count_ones(), 7);
	/// # }
	/// ```
	pub fn count_ones(&self) -> usize {
		self.body().iter().map(T::ones).sum::<usize>() +
		self.tail().map(|t| (0 .. self.bits())
			.map(|n| t.get(C::curr::<T>(n))).filter(|b| *b).count()
		).unwrap_or(0)
	}

	/// Counts how many bits are set low.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1];
	/// assert_eq!(bv.count_zeros(), 6);
	/// # }
	/// ```
	pub fn count_zeros(&self) -> usize {
		self.body().iter().map(T::zeros).sum::<usize>() +
		self.tail().map(|t| (0 .. self.bits())
			.map(|n| t.get(C::curr::<T>(n))).filter(|b| !*b).count()
		).unwrap_or(0)
	}

	/// Returns the number of bits contained in the `BitSlice`.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 10];
	/// let bits: &BitSlice = &bv;
	/// assert_eq!(bits.len(), 10);
	/// # }
	/// ```
	pub fn len(&self) -> usize {
		self.inner.len()
	}

	/// Counts how many *whole* storage elements are in the `BitSlice`.
	///
	/// If the `BitSlice` length is not an even multiple of the width of `T`,
	/// then the slice under this `BitSlice` is one element longer than this
	/// method reports, and the number of bits in it are reported by `bits()`.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 10];
	/// let bits: &BitSlice = &bv;
	/// assert_eq!(bits.elts(), 1);
	/// # }
	/// ```
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 16];
	/// let bits: &BitSlice = &bv;
	/// assert_eq!(bits.elts(), 2);
	/// # }
	/// ```
	pub fn elts(&self) -> usize {
		self.len() >> T::BITS
	}

	/// Counts how many bits are in the trailing partial storage element.
	///
	/// If the `BitSlice` length is an even multiple of the width of `T`, then
	/// this returns 0 and the `BitSlice` does not consider its final element to
	/// be partially used.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 10];
	/// let bits: &BitSlice = &bv;
	/// assert_eq!(bits.bits(), 2);
	/// # }
	/// ```
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 16];
	/// let bits: &BitSlice = &bv;
	/// assert_eq!(bits.bits(), 0);
	/// # }
	/// ```
	pub fn bits(&self) -> u8 {
		self.len() as u8 & T::MASK
	}

	/// Returns `true` if the slice contains no bits.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![];
	/// let bits: &BitSlice = &bv;
	/// assert!(bits.is_empty());
	/// # }
	/// ```
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![0; 5];
	/// let bits: &BitSlice = &bv;
	/// assert!(!bits.is_empty());
	/// # }
	/// ```
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}

	/// Provides read-only iteration across the collection.
	///
	/// The iterator returned from this method implements `ExactSizeIterator`
	/// and `DoubleEndedIterator` just as the consuming `.into_iter()` method’s
	/// iterator does.
	pub fn iter(&self) -> Iter<C, T> {
		self.into_iter()
	}

	/// Provides mutable traversal of the collection.
	///
	/// It is impossible to implement `IndexMut` on `BitSlice` because bits do
	/// not have addresses, so there can be no `&mut u1`. This method allows the
	/// client to receive an enumerated bit, and provide a new bit to set at
	/// each index.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv = bitvec![1; 8];
	/// let bref: &mut BitSlice = &mut bv;
	/// bref.for_each(|idx, bit| {
	///     if idx % 2 == 0 {
	///         !bit
	///     }
	///     else {
	///         bit
	///     }
	/// });
	/// assert_eq!(&[0b01010101], bref.as_ref());
	/// # }
	/// ```
	pub fn for_each<F>(&mut self, op: F)
	where F: Fn(usize, bool) -> bool {
		for idx in 0 .. self.len() {
			let tmp = self.get(idx);
			self.set(idx, op(idx, tmp));
		}
	}

	/// Retrieves a read pointer to the start of the data slice.
	pub(crate) fn as_ptr(&self) -> *const T {
		self.inner.as_ptr()
	}

	/// Retrieves a write pointer to the start of the data slice.
	pub(crate) fn as_mut_ptr(&mut self) -> *mut T {
		self.inner.as_mut_ptr()
	}

	/// Computes the actual length of the data slice, including the partial tail
	/// if present.
	///
	/// This is a crate-local function. It only appears in the docs so that it
	/// can be tested.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(all(feature = "alloc", feature = "testing"))] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 10];
	/// let bits: &BitSlice = &bv;
	/// assert_eq!(bits.elts(), 1);
	/// assert_eq!(bits.raw_len(), 2);
	/// # }
	/// ```
	#[cfg(feature = "testing")]
	pub fn raw_len(&self) -> usize { self.raw_len_inner() }
	#[cfg(not(feature = "testing"))]
	pub(crate) fn raw_len(&self) -> usize { self.raw_len_inner() }
	#[doc(hidden)]
	#[inline(always)]
	fn raw_len_inner(&self) -> usize {
		self.elts() + if self.bits() > 0 { 1 } else { 0 }
	}

	/// Gets access to the set of all filled elements as a slice.
	///
	/// This is primarily useful for bulk operations on the filled elements.
	///
	/// This is a crate-local function. It only appears in the docs so that it
	/// can be tested.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(all(feature = "alloc", feature = "testing"))] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 10];
	/// let body: &[u8] = bv.body();
	/// assert_eq!(body.len(), 1);
	/// # }
	/// ```
	#[cfg(feature = "testing")]
	pub fn body(&self) -> &[T] { self.body_inner() }
	#[cfg(not(feature = "testing"))]
	pub(crate) fn body(&self) -> &[T] { self.body_inner() }
	#[doc(hidden)]
	#[inline(always)]
	fn body_inner(&self) -> &[T] {
		let elts = self.elts();
		&self.as_ref()[.. elts]
	}

	/// Gets mutable access to the set of all filled elements as a slice.
	///
	/// This is primarily useful for bulk operations on the filled elements.
	///
	/// This is a crate-local function. It only appears in the docs so that it
	/// can be tested.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(all(feature = "alloc", feature = "testing"))] {
	/// use bitvec::*;
	/// let mut bv = bitvec![1; 10];
	/// assert!(bv[0]);
	/// {
	///   let body: &mut [u8] = bv.body_mut();
	///   assert_eq!(body.len(), 1);
	///   assert_eq!(body[0], 0xFF);
	///   body[0] = 0;
	///   assert_eq!(body[0], 0x00);
	/// }
	/// assert!(!bv[0]);
	/// # }
	/// ```
	#[cfg(feature = "testing")]
	pub fn body_mut(&mut self) -> &mut [T] { self.body_mut_inner() }
	#[cfg(not(feature = "testing"))]
	pub(crate) fn body_mut(&mut self) -> &mut [T] { self.body_mut_inner() }
	#[doc(hidden)]
	#[inline(always)]
	fn body_mut_inner(&mut self) -> &mut [T] {
		let elts = self.elts();
		&mut self.as_mut()[.. elts]
	}

	/// Gets access to the partially-filled tail, if it exists.
	///
	/// This is a crate-local function. It only appears in the docs so that it
	/// can be tested.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(all(feature = "alloc", feature = "testing"))] {
	/// use bitvec::*;
	/// let bv = bitvec![1; 10];
	/// let tail: &u8 = bv.tail().unwrap();
	/// assert_eq!(*tail, 0b1100_0000);
	/// # }
	/// ```
	#[cfg(feature = "testing")]
	pub fn tail(&self) -> Option<&T> { self.tail_inner() }
	#[cfg(not(feature = "testing"))]
	pub(crate) fn tail(&self) -> Option<&T> { self.tail_inner() }
	#[doc(hidden)]
	#[inline(always)]
	fn tail_inner(&self) -> Option<&T> {
		if self.bits() > 0 {
			let elts = self.elts();
			Some(&self.as_ref()[elts])
		}
		else {
			None
		}
	}

	/// Gets mutable access to the partially-filled tail, if it exists.
	///
	/// This is a crate-local function. It only appears in the docs so that it
	/// can be tested.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(all(feature = "alloc", feature = "testing"))] {
	/// use bitvec::*;
	/// let mut bv = bitvec![1; 10];
	/// bv.push(false);
	/// assert!(!bv[10]);
	/// {
	///   let tail: &mut u8 = bv.tail_mut().unwrap();
	///   assert_eq!(*tail, 0b1100_0000);
	///   *tail = 0xFF;
	///   assert_eq!(*tail, 0xFF);
	/// }
	/// assert!(bv[10]);
	/// # }
	/// ```
	#[cfg(feature = "testing")]
	pub fn tail_mut(&mut self) -> Option<&mut T> { self.tail_mut_inner() }
	#[cfg(not(feature = "testing"))]
	pub(crate) fn tail_mut(&mut self) -> Option<&mut T> { self.tail_mut_inner() }
	#[doc(hidden)]
	#[inline(always)]
	fn tail_mut_inner(&mut self) -> Option<&mut T> {
		if self.bits() > 0 {
			let elts = self.elts();
			Some(&mut self.as_mut()[elts])
		}
		else {
			None
		}
	}

	/// Prints a type header into the Formatter.
	#[cfg(feature = "alloc")]
	pub(crate) fn fmt_header(&self, fmt: &mut Formatter) -> fmt::Result {
		write!(fmt, "BitSlice<{}, {}>", C::TY, T::TY)
	}

	/// Formats the contents data slice.
	///
	/// The debug flag indicates whether to indent each line (`Debug` does,
	/// `Display` does not).
	#[cfg(feature = "alloc")]
	pub(crate) fn fmt_body(&self, fmt: &mut Formatter, debug: bool) -> fmt::Result {
		let (elts, bits) = T::split(self.len());
		let len = self.raw_len();
		let buf = self.as_ref();
		let alt = fmt.alternate();
		for (idx, elt) in buf.iter().take(elts).enumerate() {
			Self::fmt_element(fmt, elt)?;
			if idx < len - 1 {
				match (alt, debug) {
					// {}
					(false, false) => fmt.write_str(" "),
					// {:#}
					(true, false) => writeln!(fmt),
					// {:?}
					(false, true) => fmt.write_str(", "),
					// {:#?}
					(true, true) => { writeln!(fmt, ",")?; fmt.write_str("    ") },
				}?;
			}
		}
		if bits > 0 {
			Self::fmt_bits(fmt, &buf[elts], bits)?;
		}
		Ok(())
	}

	/// Formats a whole storage element of the data slice.
	#[cfg(feature = "alloc")]
	pub(crate) fn fmt_element(fmt: &mut Formatter, elt: &T) -> fmt::Result {
		Self::fmt_bits(fmt, elt, T::WIDTH)
	}

	/// Formats a partial element of the data slice.
	#[cfg(feature = "alloc")]
	pub(crate) fn fmt_bits(fmt: &mut Formatter, elt: &T, bits: u8) -> fmt::Result {
		use core::fmt::Write;

		#[cfg(not(feature = "std"))]
		use alloc::string::String;

		let mut out = String::with_capacity(bits as usize);
		for bit in 0 .. bits {
			let cur = C::curr::<T>(bit);
			out.write_str(if elt.get(cur) { "1" } else { "0" })?;
		}
		fmt.write_str(&out)
	}
}

/// Creates a new `BitVec` out of a `BitSlice`.
#[cfg(feature = "alloc")]
impl<C, T> ToOwned for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	type Owned = crate::BitVec<C, T>;

	/// Clones a borrowed `BitSlice` into an owned `BitVec`.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let src = bitvec![0; 5];
	/// let src_ref: &BitSlice = &src;
	/// let dst = src_ref.to_owned();
	/// assert_eq!(src, dst);
	/// # }
	/// ```
	fn to_owned(&self) -> Self::Owned {
		let mut out = Self::Owned::with_capacity(self.len());
		unsafe {
			let src = self.as_ptr();
			let dst = out.as_mut_ptr();
			let len = self.raw_len();
			ptr::copy_nonoverlapping(src, dst, len);
			out.set_len(self.len());
		}
		out
	}
}

impl<C, T> Eq for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {}

impl<C, T> Ord for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	fn cmp(&self, rhs: &Self) -> Ordering {
		match self.partial_cmp(rhs) {
			Some(ord) => ord,
			None => unreachable!("`BitSlice` has a total ordering"),
		}
	}
}

/// Tests if two `BitSlice`s are semantically — not bitwise — equal.
///
/// It is valid to compare two slices of different endianness or element types.
///
/// The equality condition requires that they have the same number of total bits
/// and that each pair of bits in semantic order are identical.
impl<A, B, C, D> PartialEq<BitSlice<C, D>> for BitSlice<A, B>
where A: crate::Cursor, B: crate::Bits, C: crate::Cursor, D: crate::Bits {
	/// Performs a comparison by `==`.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let l: BitVec<LittleEndian, u16> = bitvec![LittleEndian, u16; 0, 1, 0, 1];
	/// let r: BitVec<BigEndian, u32> = bitvec![BigEndian, u32; 0, 1, 0, 1];
	///
	/// let ls: &BitSlice<_, _> = &l;
	/// let rs: &BitSlice<_, _> = &r;
	/// assert!(ls == rs);
	/// # }
	/// ```
	fn eq(&self, rhs: &BitSlice<C, D>) -> bool {
		let (l, r) = (self.iter(), rhs.iter());
		if l.len() != r.len() {
			return false;
		}
		l.zip(r).all(|(l, r)| l == r)
	}
}

/// Compares two `BitSlice`s by semantic — not bitwise — ordering.
///
/// The comparison sorts by testing each index for one slice to have a set bit
/// where the other has an unset bit. If the slices are different, the slice
/// with the set bit sorts greater than the slice with the unset bit.
///
/// If one of the slices is exhausted before they differ, the longer slice is
/// greater.
impl<A, B, C, D> PartialOrd<BitSlice<C, D>> for BitSlice<A, B>
where A: crate::Cursor, B: crate::Bits, C: crate::Cursor, D: crate::Bits {
	/// Performs a comparison by `<` or `>`.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let a = bitvec![0, 1, 0, 0];
	/// let b = bitvec![0, 1, 0, 1];
	/// let c = bitvec![0, 1, 0, 1, 1];
	/// let aref: &BitSlice = &a;
	/// let bref: &BitSlice = &b;
	/// let cref: &BitSlice = &c;
	/// assert!(aref < bref);
	/// assert!(bref < cref);
	/// # }
	/// ```
	fn partial_cmp(&self, rhs: &BitSlice<C, D>) -> Option<Ordering> {
		for (l, r) in self.iter().zip(rhs.iter()) {
			match (l, r) {
				(true, false) => return Some(Ordering::Greater),
				(false, true) => return Some(Ordering::Less),
				_ => continue,
			}
		}
		self.len().partial_cmp(&rhs.len())
	}
}

/// Gives write access to all elements in the underlying storage, including the
/// partially-filled tail element (if present).
impl<C, T> AsMut<[T]> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Accesses the underlying store.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv: BitVec = bitvec![0, 0, 0, 0, 0, 0, 0, 0, 1];
	/// for elt in bv.as_mut() {
	///   *elt += 2;
	/// }
	/// assert_eq!(&[2, 130], bv.as_ref());
	/// # }
	/// ```
	fn as_mut(&mut self) -> &mut [T] {
		let (ptr, len): (*mut T, usize) = (self.as_mut_ptr(), self.raw_len());
		unsafe { slice::from_raw_parts_mut(ptr, len) }
	}
}

/// Gives read access to all elements in the underlying storage, including the
/// partially-filled tail element (if present).
impl<C, T> AsRef<[T]> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Accesses the underlying store.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![0, 0, 0, 0, 0, 0, 0, 0, 1];
	/// let bref: &BitSlice = &bv;
	/// assert_eq!(&[0, 0b1000_0000], bref.as_ref());
	/// # }
	/// ```
	fn as_ref(&self) -> &[T] {
		let (ptr, len): (*const T, usize) = (self.as_ptr(), self.raw_len());
		unsafe { slice::from_raw_parts(ptr, len) }
	}
}

/// Builds a `BitSlice` from a slice of elements. The resulting `BitSlice` will
/// always completely fill the original slice, and will not have a partial tail.
impl<'a, C, T> From<&'a [T]> for &'a BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	/// Wraps an `&[T: Bits]` in an `&BitSlice<C: Cursor, T>`. The endianness
	/// must be specified by the call site. The element type cannot be changed.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let src = vec![1u8, 2, 3];
	/// let borrow: &[u8] = &src;
	/// let bits: &BitSlice<BigEndian, _> = borrow.into();
	/// assert_eq!(bits.len(), 24);
	/// assert_eq!(bits.elts(), 3);
	/// assert_eq!(bits.bits(), 0);
	/// assert!(bits.get(7));  // src[0] == 0b0000_0001
	/// assert!(bits.get(14)); // src[1] == 0b0000_0010
	/// assert!(bits.get(22)); // src[2] == 0b0000_0011
	/// assert!(bits.get(23));
	/// # }
	/// ```
	fn from(src: &'a [T]) -> Self {
		let (ptr, len): (*const T, usize) = (src.as_ptr(), src.len());
		assert!(len <= T::MAX_ELT, "Source slice length out of range!");
		unsafe {
			mem::transmute(
				slice::from_raw_parts(ptr, len << T::BITS)
			)
		}
	}
}

/// Builds a mutable `BitSlice` from a slice of mutable elements. The resulting
/// `BitSlice` will always completely fill the original slice, and will not have
/// a partial tail.
impl<'a, C, T> From<&'a mut [T]> for &'a mut BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	/// Wraps an `&mut [T: Bits]` in an `&mut BitSlice<C: Cursor, T>`. The
	/// endianness must be specified by the call site. The element type cannot
	/// be changed.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut src = vec![1u8, 2, 3];
	/// let borrow: &mut [u8] = &mut src;
	/// let bits: &mut BitSlice<LittleEndian, _> = borrow.into();
	/// //  The first bit read is the LSb of the first element, which is set.
	/// assert!(bits.get(0));
	/// bits.set(0, false);
	/// assert!(!bits.get(0));
	/// # }
	/// ```
	fn from(src: &'a mut [T]) -> Self {
		let (ptr, len): (*mut T, usize) = (src.as_mut_ptr(), src.len());
		assert!(len <= T::MAX_ELT, "Source slice length out of range!");
		unsafe {
			mem::transmute(
				slice::from_raw_parts_mut(ptr, len << T::BITS)
			)
		}
	}
}

/// Prints the `BitSlice` for debugging.
///
/// The output is of the form `BitSlice<C, T> [ELT, *]` where `<C, T>` is the
/// endianness and element type, with square brackets on each end of the bits
/// and all the elements of the array printed in binary. The printout is always
/// in semantic order, and may not reflect the underlying buffer. To see the
/// underlying buffer, use `.as_ref()`.
///
/// The alternate character `{:#?}` prints each element on its own line, rather
/// than having all elements on the same line.
#[cfg(feature = "alloc")]
impl<C, T> Debug for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Renders the `BitSlice` type header and contents for debug.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bits: &BitSlice<LittleEndian, u16> = &bitvec![
	///   LittleEndian, u16;
	///   0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1,
	///   0, 1
	/// ];
	/// assert_eq!(
    ///     "BitSlice<LittleEndian, u16> [0101000011110101, 01]",
	///     &format!("{:?}", bits)
	/// );
	/// # }
	/// ```
	fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
		let alt = fmt.alternate();
		self.fmt_header(fmt)?;
		fmt.write_str(" [")?;
		if alt { writeln!(fmt)?; fmt.write_str("    ")?; }
		self.fmt_body(fmt, true)?;
		if alt { writeln!(fmt)?; }
		fmt.write_str("]")
	}
}

/// Prints the `BitSlice` for displaying.
///
/// This prints each element in turn, formatted in binary in semantic order (so
/// the first bit seen is printed first and the last bit seen is printed last).
/// Each element of storage is separated by a space for ease of reading.
///
/// The alternate character `{:#}` prints each element on its own line.
///
/// To see the in-memory representation, use `.as_ref()` to get access to the
/// raw elements and print that slice instead.
#[cfg(feature = "alloc")]
impl<C, T> Display for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Renders the `BitSlice` contents for display.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bits: &BitSlice = &bitvec![0, 1, 0, 0, 1, 0, 1, 1, 0, 1];
	/// assert_eq!("01001011 01", &format!("{}", bits));
	/// # }
	/// ```
	fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
		self.fmt_body(fmt, false)
	}
}

/// Writes the contents of the `BitSlice`, in semantic bit order, into a hasher.
impl<C, T> Hash for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Writes each bit of the `BitSlice`, as a full `bool`, into the hasher.
	fn hash<H>(&self, hasher: &mut H)
	where H: Hasher {
		for bit in self {
			hasher.write_u8(bit as u8);
		}
	}
}

/// Produces a read-only iterator over all the bits in the `BitSlice`.
///
/// This iterator follows the ordering in the `BitSlice` type, and implements
/// `ExactSizeIterator` as `BitSlice` has a known, fixed length, and
/// `DoubleEndedIterator` as it has known ends.
impl<'a, C, T> IntoIterator for &'a BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	type Item = bool;
	type IntoIter = Iter<'a, C, T>;

	/// Iterates over the slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![1, 0, 1, 0, 1, 1, 0, 0];
	/// let bref: &BitSlice = &bv;
	/// let mut count = 0;
	/// for bit in bref {
	///     if bit { count += 1; }
	/// }
	/// assert_eq!(count, 4);
	/// # }
	/// ```
	fn into_iter(self) -> Self::IntoIter {
		self.into()
	}
}

/// Performs unsigned addition in place on a `BitSlice`.
///
/// If the addend `BitSlice` is shorter than `self`, the addend is zero-extended
/// at the left (so that its final bit matches with `self`’s final bit). If the
/// addend is longer, the excess front length is unused.
///
/// Addition proceeds from the right ends of each slice towards the left.
/// Because this trait is forbidden from returning anything, the final carry-out
/// bit is discarded.
///
/// Note that, unlike `BitVec`, there is no subtraction implementation until I
/// find a subtraction algorithm that does not require modifying the subtrahend.
///
/// Subtraction can be implemented by negating the intended subtrahend yourself
/// and then using addition, or by using `BitVec`s instead of `BitSlice`s.
impl<'a, C, T> AddAssign<&'a BitSlice<C, T>> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Performs unsigned wrapping addition in place.
	///
	/// # Examples
	///
	/// This example shows addition of a slice wrapping from MAX to zero.
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let nums: [BitVec; 3] = [
	///     bitvec![1, 1, 1, 0],
	///     bitvec![1, 1, 1, 1],
	///     bitvec![0, 0, 0, 0],
	/// ];
	/// let one = bitvec![0, 1];
	/// let mut num = nums[0].clone();
	/// let numr: &mut BitSlice = &mut num;
	/// *numr += &one;
	/// assert_eq!(numr, &nums[1] as &BitSlice);
	/// *numr += &one;
	/// assert_eq!(numr, &nums[2] as &BitSlice);
	/// # }
	/// ```
	fn add_assign(&mut self, addend: &'a BitSlice<C, T>) {
		use core::iter::repeat;
		//  zero-extend the addend if it’s shorter than self
		let mut addend_iter = addend.into_iter().rev().chain(repeat(false));
		let mut c = false;
		for place in (0 .. self.len()).rev() {
			//  See `BitVec::AddAssign`
			static JUMP: [u8; 8] = [0, 2, 2, 1, 2, 1, 1, 3];
			let a = self.get(place);
			let b = addend_iter.next().unwrap(); // addend is an infinite source
			let idx = ((c as u8) << 2) | ((a as u8) << 1) | (b as u8);
			let yz = JUMP[idx as usize];
			let (y, z) = (yz & 2 != 0, yz & 1 != 0);
			self.set(place, y);
			c = z;
		}
	}
}

/// Performs the Boolean `AND` operation against another bitstream and writes
/// the result into `self`. If the other bitstream ends before `self` does, it
/// is extended with zero, clearing all remaining bits in `self`.
impl<C, T, I> BitAndAssign<I> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits, I: IntoIterator<Item=bool> {
	/// `AND`s a bitstream into a slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let lhs: &mut BitSlice = &mut bitvec![0, 1, 0, 1, 0, 1];
	/// let rhs                =      bitvec![0, 0, 1, 1];
	/// *lhs &= rhs;
	/// assert_eq!("000100", &format!("{}", lhs));
	/// # }
	/// ```
	fn bitand_assign(&mut self, rhs: I) {
		use core::iter::repeat;
		for (idx, other) in (0 .. self.len()).zip(rhs.into_iter().chain(repeat(false))) {
			let val = self.get(idx) & other;
			self.set(idx, val);
		}
	}
}

/// Performs the Boolean `OR` operation against another bitstream and writes the
/// result into `self`. If the other bitstream ends before `self` does, it is
/// extended with zero, leaving all remaining bits in `self` as they were.
impl<C, T, I> BitOrAssign<I> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits, I: IntoIterator<Item=bool> {
	/// `OR`s a bitstream into a slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let lhs: &mut BitSlice = &mut bitvec![0, 1, 0, 1, 0, 1];
	/// let rhs                =      bitvec![0, 0, 1, 1];
	/// *lhs |= rhs;
	/// assert_eq!("011101", &format!("{}", lhs));
	/// # }
	/// ```
	fn bitor_assign(&mut self, rhs: I) {
		for (idx, other) in (0 .. self.len()).zip(rhs.into_iter()) {
			let val = self.get(idx) | other;
			self.set(idx, val);
		}
	}
}

/// Performs the Boolean `XOR` operation against another bitstream and writes
/// the result into `self`. If the other bitstream ends before `self` does, it
/// is extended with zero, leaving all remaining bits in `self` as they were.
impl<C, T, I> BitXorAssign<I> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits, I: IntoIterator<Item=bool> {
	/// `XOR`s a bitstream into a slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let lhs: &mut BitSlice = &mut bitvec![0, 1, 0, 1, 0, 1];
	/// let rhs                =      bitvec![0, 0, 1, 1];
	/// *lhs ^= rhs;
	/// assert_eq!("011001", &format!("{}", lhs));
	/// # }
	/// ```
	fn bitxor_assign(&mut self, rhs: I) {
		use core::iter::repeat;
		for (idx, other) in (0 .. self.len()).zip(rhs.into_iter().chain(repeat(false))) {
			let val = self.get(idx) ^ other;
			self.set(idx, val);
		}
	}
}

/// Indexes a single bit by semantic count. The index must be less than the
/// length of the `BitSlice`.
impl<'a, C, T> Index<usize> for &'a BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	type Output = bool;

	/// Looks up a single bit by semantic count.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![0, 0, 1, 0, 0];
	/// let bits: &BitSlice = &bv;
	/// assert!(bits[2]);
	/// assert!(!bits[3]);
	/// # }
	/// ```
	fn index(&self, index: usize) -> &Self::Output {
		if self.get(index) { &true} else { &false }
	}
}

/// Indexes a single bit by element and bit index within the element. The
/// element index must be less than the length of the underlying store, and the
/// bit index must be less than the width of the underlying element.
///
/// This index is not recommended for public use.
impl<'a, C, T> Index<(usize, u8)> for &'a BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	type Output = bool;

	/// Looks up a single bit by storage element and bit indices. The bit index
	/// is still a semantic count, not an absolute index into the element.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv = bitvec![0; 10];
	/// bv.push(true);
	/// let bits: &BitSlice = &bv;
	/// assert!(bits[(1, 2)]); // 10
	/// assert!(!bits[(1, 1)]); // 9
	/// # }
	/// ```
	fn index(&self, (elt, bit): (usize, u8)) -> &Self::Output {
		if self.get(T::join(elt, bit)) { &true } else { &false }
	}
}

/// Performs fixed-width 2’s-complement negation of a `BitSlice`.
///
/// Unlike the `!` operator (`Not` trait), the unary `-` operator treats the
/// `BitSlice` as if it represents a signed 2’s-complement integer of fixed
/// width. The negation of a number in 2’s complement is defined as its
/// inversion (using `!`) plus one, and on fixed-width numbers has the following
/// discontinuities:
///
/// - A slice whose bits are all zero is considered to represent the number zero
///   which negates as itself.
/// - A slice whose bits are all one is considered to represent the most
///   negative number, which has no correpsonding positive number, and thus
///   negates as zero.
///
/// This behavior was chosen so that all possible values would have *some*
/// output, and so that repeated application converges at idempotence. The most
/// negative input can never be reached by negation, but `--MOST_NEG` converges
/// at the least unreasonable fallback value, 0.
///
/// Because `BitSlice` cannot move, the negation is performed in place.
impl<'a, C, T> Neg for &'a mut BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	type Output = Self;

	/// Perform 2’s-complement fixed-width negation.
	///
	/// # Examples
	///
	/// The contortions shown here are a result of this operator applying to a
	/// mutable reference, and this example balancing access to the original
	/// `BitVec` for comparison with aquiring a mutable borrow *as a slice* to
	/// ensure that the `BitSlice` implementation is used, not the `BitVec`.
	///
	/// Negate an arbitrary positive number (first bit unset).
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut num = bitvec![0, 1, 1, 0];
	/// - (&mut num as &mut BitSlice);
	/// assert_eq!(num, bitvec![1, 0, 1, 0]);
	/// # }
	/// ```
	///
	/// Negate an arbitrary negative number. This example will use the above
	/// result to demonstrate round-trip correctness.
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut num = bitvec![1, 0, 1, 0];
	/// - (&mut num as &mut BitSlice);
	/// assert_eq!(num, bitvec![0, 1, 1, 0]);
	/// # }
	/// ```
	///
	/// Negate the most negative number, which will become zero, and show
	/// convergence at zero.
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let zero = bitvec![0; 10];
	/// let mut num = bitvec![1; 10];
	/// - (&mut num as &mut BitSlice);
	/// assert_eq!(num, zero);
	/// - (&mut num as &mut BitSlice);
	/// assert_eq!(num, zero);
	/// # }
	/// ```
	fn neg(self) -> Self::Output {
		if self.is_empty() || self.not_any() {
			return self;
		}
		let _ = Not::not(&mut *self);
		//  Fill an element with all 1 bits
		let elt: [T; 1] = [! unsafe { mem::zeroed() }];
		if self.any() {
			//  Turn a slice reference `[T; 1]` into a bit-slice reference
			//  `[u1; 1]`
			let addend: &BitSlice<C, T> = {
				unsafe { mem::transmute::<&[T], &BitSlice<C, T>>(&elt) }
			};
			//  And add it (if the slice was not all-ones).
			AddAssign::add_assign(&mut *self, addend);
		}
		self
	}
}

/// Flips all bits in the slice, in place.
///
/// This invokes the `!` operator on each element of the borrowed storage, and
/// so it will also flip bits in the tail that are outside the `BitSlice` length
/// if any. Use `^= repeat(true)` to flip only the bits actually inside the
/// `BitSlice` purview. `^=` also has the advantage of being a borrowing
/// operator rather than a consuming/returning operator.
impl<'a, C, T> Not for &'a mut BitSlice<C, T>
where C: crate::Cursor, T: 'a + crate::Bits {
	type Output = Self;

	/// Inverts all bits in the slice.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv = bitvec![0; 10];
	/// let bits: &mut BitSlice = &mut bv;
	/// let new_bits = !bits;
	/// //  The `bits` binding is consumed by the `!` operator, and a new reference
	/// //  is returned.
	/// // assert_eq!(bits.as_ref(), &[!0, !0]);
	/// assert_eq!(new_bits.as_ref(), &[!0, !0]);
	/// # }
	/// ```
	fn not(self) -> Self::Output {
		for elt in self.as_mut() {
			*elt = !*elt;
		}
		self
	}
}

__bitslice_shift!(u8, u16, u32, u64, i8, i16, i32, i64);

/// Shifts all bits in the array to the left — **DOWN AND TOWARDS THE FRONT**.
///
/// On primitives, the left-shift operator `<<` moves bits away from the origin
/// and towards the ceiling. This is because we label the bits in a primitive
/// with the minimum on the right and the maximum on the left, which is
/// big-endian bit order. This increases the value of the primitive being
/// shifted.
///
/// **THAT IS NOT HOW `BitSlice` WORKS!**
///
/// `BitSlice` defines its layout with the minimum on the left and the maximum
/// on the right! Thus, left-shifting moves bits towards the **minimum**.
///
/// In BigEndian order, the effect in memory will be what you expect the `<<`
/// operator to do.
///
/// **In LittleEndian order, the effect will be equivalent to using `>>` on**
/// **the primitives in memory!**
///
/// # Notes
///
/// In order to preserve the effecs in memory that this operator traditionally
/// expects, the bits that are emptied by this operation are zeroed rather than
/// left to their old value.
///
/// The shift amount is modulated against the array length, so it is not an
/// error to pass a shift amount greater than the array length.
///
/// A shift amount of zero is a no-op, and returns immediately.
impl<C, T> ShlAssign<usize> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Shifts a slice left, in place.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv = bitvec![1, 1, 1, 0, 0, 0, 0, 0, 1];
	/// let bits: &mut BitSlice = &mut bv;
	/// *bits <<= 3;
	/// assert_eq!("00000100 0", &format!("{}", bits));
	/// //               ^ former tail
	/// # }
	/// ```
	fn shl_assign(&mut self, shamt: usize) {
		let len = self.len();
		//  Bring the shift amount down into the slice's domain.
		let shamt = shamt % len;
		//  If the shift amount was an even multiple of the length, exit.
		if shamt == 0 {
			return;
		}
		//  If the shift amount is an even multiple of the element width, use
		//  ptr::copy instead of a bitwise crawl
		if shamt & T::MASK as usize == 0 {
			//  Compute the shift distance measured in elements.
			let offset = shamt >> T::BITS;
			//  Compute the number of elements that will remain.
			let rem = self.raw_len() - offset;
			//  Memory model: suppose we have this slice of sixteen elements,
			//  that is shifted five elements to the left. We have three
			//  pointers and two lengths to manage.
			//  - rem is 11
			//  - offset is 5
			//  - head is [0]
			//  - body is [5; 11]
			//  - tail is [11]
			//  [ 0 1 2 3 4 5 6 7 8 9 a b c d e f ]
			//              ^-------before------^
			//    ^-------after-------^ 0 0 0 0 0
			//  Pointer to the front of the slice
			let head: *mut T = self.as_mut_ptr();
			//  Pointer to the front of the section that will move and be
			//  retained
			let body: *const T = &self.as_ref()[offset];
			//  Pointer to the back of the slice that will be zero-filled.
			let tail: *mut T = &mut self.as_mut()[rem];
			unsafe {
				ptr::copy(body, head, rem);
				ptr::write_bytes(tail, 0, offset);
			}
			return;
		}
		//  If the shift amount is not an even multiple, do a bitwise crawl and
		//  move bits forward, then zero-fill the back.
		//  Same general logic as above, but bit-level instead of element-level.
		for (to, from) in (shamt .. len).enumerate() {
			let val = self.get(from);
			self.set(to, val);
		}
		for bit in (len - shamt) .. len {
			self.set(bit, false);
		}
	}
}

/// Shifts all bits in the array to the right — **UP AND TOWARDS THE BACK**.
///
/// On primitives, the right-shift operator `>>` moves bits towards the origin
/// and away from the ceiling. This is because we label the bits in a primitive
/// with the minimum on the right and the maximum on the left, which is
/// big-endian bit order. This decreases the value of the primitive being
/// shifted.
///
/// **THAT IS NOT HOW `BitSlice` WORKS!**
///
/// `BitSlice` defines its layout with the minimum on the left and the maximum
/// on the right! Thus, right-shifting moves bits towards the **maximum**.
///
/// In Big-Endian order, the effect in memory will be what you expect the `>>`
/// operator to do.
///
/// **In LittleEndian order, the effect will be equivalent to using `<<` on**
/// **the primitives in memory!**
///
/// # Notes
///
/// In order to preserve the effects in memory that this operator traditionally
/// expects, the bits that are emptied by this operation are zeroed rather than
/// left to their old value.
///
/// The shift amount is modulated against the array length, so it is not an
/// error to pass a shift amount greater than the array length.
///
/// A shift amount of zero is a no-op, and returns immediately.
impl<C, T> ShrAssign<usize> for BitSlice<C, T>
where C: crate::Cursor, T: crate::Bits {
	/// Shifts a slice right, in place.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let mut bv = bitvec![1, 0, 0, 0, 0, 0, 1, 1, 1];
	/// let bits: &mut BitSlice = &mut bv;
	/// *bits >>= 3;
	/// assert_eq!("00010000 0", &format!("{}", bits));
	/// //             ^ former head
	/// # }
	/// ```
	fn shr_assign(&mut self, shamt: usize) {
		let len = self.len();
		//  Bring the shift amount down into the slice's domain.
		let shamt = shamt % len;
		//  If the shift amount was an even multiple of the length, exit.
		if shamt == 0 {
			return;
		}
		//  If the shift amount is an even multiple of the element width, use
		//  ptr::copy instead of a bitwise crawl.
		if shamt & T::MASK as usize == 0 {
			//  Compute the shift amount measured in elements.
			let offset = shamt >> T::BITS;
			//  Compute the number of elements that will remain.
			let rem = self.raw_len() - offset;
			//  Memory model: suppose we have this slice of sixteen elements,
			//  that is shifted five elements to the right. We have two pointers
			//  and two lengths to manage.
			//  - rem is 11
			//  - offset is 5
			//  - head is [0; 11]
			//  - body is [5]
			//  [ 0 1 2 3 4 5 6 7 8 9 a b c d e f ]
			//    ^-------before------^
			//    0 0 0 0 0 ^-------after-------^
			let head: *mut T = self.as_mut_ptr();
			let body: *mut T = &mut self.as_mut()[offset];
			unsafe {
				ptr::copy(head, body, rem);
				ptr::write_bytes(head, 0, offset);
			}
			return;
		}
		for (from, to) in (shamt .. len).enumerate().rev() {
			let val = self.get(from);
			self.set(to, val);
		}
		for bit in 0 .. shamt {
			self.set(bit, false);
		}
	}
}

/// Permits iteration over a `BitSlice`
#[doc(hidden)]
pub struct Iter<'a, C, T>
where C: 'a + crate::Cursor, T: 'a + crate::Bits {
	inner: &'a BitSlice<C, T>,
	head: usize,
	tail: usize,
}

impl<'a, C, T> Iter<'a, C, T>
where C: 'a + crate::Cursor, T: 'a + crate::Bits {
	fn reset(&mut self) {
		self.head = 0;
		self.tail = self.inner.len();
	}
}

impl<'a, C, T> DoubleEndedIterator for Iter<'a, C, T>
where C: 'a + crate::Cursor, T: 'a + crate::Bits {
	fn next_back(&mut self) -> Option<Self::Item> {
		if self.tail > self.head {
			self.tail -= 1;
			Some(self.inner.get(self.tail))
		}
		else {
			self.reset();
			None
		}
	}
}

impl<'a, C, T> ExactSizeIterator for Iter<'a, C, T>
where C: 'a + crate::Cursor, T: 'a + crate::Bits {
	fn len(&self) -> usize {
		self.tail - self.head
	}
}

impl<'a, C, T> From<&'a BitSlice<C, T>> for Iter<'a, C, T>
where C: 'a + crate::Cursor, T: 'a + crate::Bits {
	fn from(src: &'a BitSlice<C, T>) -> Self {
		let len = src.len();
		Self {
			inner: src,
			head: 0,
			tail: len,
		}
	}
}

impl<'a, C, T> Iterator for Iter<'a, C, T>
where C: 'a + crate::Cursor, T: 'a + crate::Bits {
	type Item = bool;

	fn next(&mut self) -> Option<Self::Item> {
		if self.head < self.tail {
			let ret = self.inner.get(self.head);
			self.head += 1;
			Some(ret)
		}
		else {
			self.reset();
			None
		}
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		let rem = ExactSizeIterator::len(self);
		(rem, Some(rem))
	}

	/// Counts how many bits are live in the iterator, consuming it.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![BigEndian, u8; 0, 1, 0, 1, 0];
	/// assert_eq!(bv.iter().count(), 5);
	/// # }
	/// ```
	fn count(self) -> usize {
		ExactSizeIterator::len(&self)
	}

	/// Advances the iterator by `n` bits, starting from zero.
	///
	/// It is not an error to advance past the end of the iterator! Doing so
	/// returns `None`, and resets the iterator to its beginning.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![BigEndian, u8; 0, 0, 0, 1];
	/// let mut bv_iter = bv.iter();
	/// assert_eq!(bv_iter.len(), 4);
	/// assert!(bv_iter.nth(3).unwrap());
	/// # }
	/// ```
	///
	/// This example intentionally overshoots the iterator bounds, which causes
	/// a reset to the initial state. It then demonstrates that `nth` is
	/// stateful, and is not an absolute index, by seeking ahead by two (to the
	/// third zero bit) and then taking the bit immediately after it, which is
	/// set. This shows that the argument to `nth` is how many bits to discard
	/// before yielding the next.
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![BigEndian, u8; 0, 0, 0, 1];
	/// let mut bv_iter = bv.iter();
	/// assert!(bv_iter.nth(4).is_none());
	/// assert!(!bv_iter.nth(2).unwrap());
	/// assert!(bv_iter.nth(0).unwrap());
	/// # }
	/// ```
	fn nth(&mut self, n: usize) -> Option<bool> {
		self.head = self.head.saturating_add(n);
		self.next()
	}

	/// Consumes the iterator, returning only the last bit.
	///
	/// # Examples
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![BigEndian, u8; 0, 0, 0, 1];
	/// assert!(bv.into_iter().last().unwrap());
	/// # }
	/// ```
	///
	/// Empty iterators return `None`
	///
	/// ```rust
	/// # #[cfg(feature = "alloc")] {
	/// use bitvec::*;
	/// let bv = bitvec![];
	/// assert!(bv.into_iter().last().is_none());
	/// # }
	/// ```
	fn last(mut self) -> Option<bool> {
		self.next_back()
	}
}