Files
addr2line
adler
aead
aes
aes_gcm
aes_soft
ahash
aho_corasick
ansi_term
anyhow
approx
arrayref
arrayvec
asn1_der
asn1_der_derive
async_channel
async_executor
async_global_executor
async_io
async_mutex
async_process
async_std
collections
fs
future
io
net
option
os
path
pin
result
rt
stream
string
sync
task
unit
vec
async_task
async_trait
asynchronous_codec
atomic
atomic_waker
atty
backtrace
base58
base64
base_x
bincode
bip39
bitflags
bitvec
blake2
blake2_rfc
blake2b_simd
blake2s_simd
blake3
block_buffer
block_cipher
block_padding
blocking
bs58
bstr
bumpalo
byte_slice_cast
byteorder
bytes
cache_padded
cfg_if
chacha20
chacha20poly1305
chrono
cid
cipher
clap
concurrent_queue
const_fn
constant_time_eq
cpp_demangle
cpuid_bool
cranelift_bforest
cranelift_codegen
cranelift_codegen_shared
cranelift_entity
cranelift_frontend
cranelift_native
cranelift_wasm
crc32fast
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
crunchy
crypto_mac
ct_logs
cuckoofilter
curve25519_dalek
data_encoding
data_encoding_macro
data_encoding_macro_internal
derive_more
digest
directories
directories_next
dirs_sys
dirs_sys_next
dns_parser
dyn_clonable
dyn_clonable_impl
dyn_clone
ed25519
ed25519_dalek
either
env_logger
environmental
erased_serde
errno
event_listener
exit_future
failure
failure_derive
fallible_iterator
fastrand
fdlimit
file_per_thread_logger
finality_grandpa
fixed_hash
flate2
fnv
fork_tree
form_urlencoded
frame_benchmarking
frame_benchmarking_cli
frame_executive
frame_metadata
frame_support
frame_support_procedural
frame_support_procedural_tools
frame_support_procedural_tools_derive
frame_system
frame_system_rpc_runtime_api
fs_swap
funty
futures
futures_channel
futures_core
futures_diagnose
futures_executor
futures_io
futures_lite
futures_macro
futures_rustls
futures_sink
futures_task
futures_timer
futures_util
async_await
compat
future
io
lock
sink
stream
task
generic_array
getrandom
ghash
gimli
globset
h2
handlebars
hash256_std_hasher
hash_db
hashbrown
heck
hex
hex_fmt
hmac
hmac_drbg
http
http_body
httparse
httpdate
humantime
hyper
hyper_rustls
idna
if_watch
impl_codec
impl_serde
impl_trait_for_tuples
indexmap
inflector
cases
camelcase
case
classcase
kebabcase
pascalcase
screamingsnakecase
sentencecase
snakecase
tablecase
titlecase
traincase
numbers
deordinalize
ordinalize
string
constants
deconstantize
demodulize
pluralize
singularize
suffix
foreignkey
instant
integer_sqrt
intervalier
iovec
ip_network
ipnet
itertools
itoa
js_sys
jsonrpc_client_transports
jsonrpc_core
jsonrpc_core_client
jsonrpc_derive
jsonrpc_http_server
jsonrpc_ipc_server
jsonrpc_pubsub
jsonrpc_server_utils
jsonrpc_ws_server
keccak
kv_log_macro
kvdb
kvdb_memorydb
kvdb_rocksdb
lazy_static
lazycell
leb128
libc
libm
libp2p
libp2p_core
libp2p_core_derive
libp2p_deflate
libp2p_dns
libp2p_floodsub
libp2p_gossipsub
libp2p_identify
libp2p_kad
libp2p_mdns
libp2p_mplex
libp2p_noise
libp2p_ping
libp2p_plaintext
libp2p_pnet
libp2p_request_response
libp2p_swarm
libp2p_tcp
libp2p_uds
libp2p_wasm_ext
libp2p_websocket
libp2p_yamux
librocksdb_sys
libz_sys
linked_hash_map
linked_hash_set
linregress
lock_api
log
lru
maplit
matchers
matches
matrixmultiply
memchr
memmap2
memoffset
memory_db
memory_units
merlin
minicbor
minicbor_derive
miniz_oxide
mio
mio_extras
mio_named_pipes
mio_uds
miow
more_asserts
multibase
multihash
multihash_derive
multistream_select
nalgebra
base
geometry
linalg
names
nb_connect
net2
node_template
node_template_runtime
nohash_hasher
num_bigint
num_complex
num_cpus
num_integer
num_rational
num_traits
object
once_cell
opaque_debug
openssl_probe
owning_ref
pallet_aura
pallet_authorship
pallet_balances
pallet_collection
pallet_exchange
pallet_grandpa
pallet_graph
pallet_nft
pallet_nftdao
pallet_randomness_collective_flip
pallet_session
pallet_sub
pallet_sudo
pallet_timestamp
pallet_transaction_payment
pallet_transaction_payment_rpc
pallet_transaction_payment_rpc_runtime_api
parity_db
parity_multiaddr
parity_scale_codec
parity_scale_codec_derive
parity_send_wrapper
parity_tokio_ipc
parity_util_mem
parity_util_mem_derive
parity_wasm
parity_ws
parking
parking_lot
parking_lot_core
paste
paste_impl
pbkdf2
pdqselect
percent_encoding
pest
pest_derive
pest_generator
pest_meta
pin_project
pin_project_lite
pin_utils
polling
poly1305
polyval
ppv_lite86
primitive_types
proc_macro2
proc_macro_crate
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
prometheus
prost
prost_derive
psm
pwasm_utils
quick_error
quicksink
quote
radium
rand
rand_chacha
rand_core
rand_distr
raw_cpuid
rawpointer
rayon
rayon_core
ref_cast
ref_cast_impl
regalloc
regex
regex_automata
regex_syntax
region
remove_dir_all
retain_mut
ring
rocksdb
rpassword
rustc_demangle
rustc_hash
rustc_hex
rustls
rustls_native_certs
rw_stream_sink
ryu
safe_mix
salsa20
sc_basic_authorship
sc_block_builder
sc_chain_spec
sc_chain_spec_derive
sc_cli
sc_client_api
sc_client_db
sc_consensus
sc_consensus_aura
sc_consensus_babe
sc_consensus_epochs
sc_consensus_slots
sc_consensus_uncles
sc_executor
sc_executor_common
sc_executor_wasmi
sc_executor_wasmtime
sc_finality_grandpa
sc_informant
sc_keystore
sc_light
sc_network
sc_network_gossip
sc_offchain
sc_peerset
sc_proposer_metrics
sc_rpc
sc_rpc_api
sc_rpc_server
sc_service
sc_state_db
sc_telemetry
sc_tracing
sc_tracing_proc_macro
sc_transaction_graph
sc_transaction_pool
schnorrkel
scoped_tls
scopeguard
scroll
scroll_derive
sct
secp256k1
secrecy
serde
serde_derive
serde_json
sha1
sha2
sha3
sharded_slab
signal_hook
signal_hook_registry
signature
simba
slab
smallvec
snow
socket2
soketto
sp_allocator
sp_api
sp_api_proc_macro
sp_application_crypto
sp_arithmetic
sp_authorship
sp_block_builder
sp_blockchain
sp_chain_spec
sp_consensus
sp_consensus_aura
sp_consensus_babe
sp_consensus_slots
sp_consensus_vrf
sp_core
sp_database
sp_debug_derive
sp_externalities
sp_finality_grandpa
sp_inherents
sp_io
sp_keyring
sp_keystore
sp_offchain
sp_panic_handler
sp_rpc
sp_runtime
sp_runtime_interface
sp_runtime_interface_proc_macro
sp_serializer
sp_session
sp_staking
sp_state_machine
sp_std
sp_storage
sp_tasks
sp_timestamp
sp_tracing
sp_transaction_pool
sp_trie
sp_utils
sp_version
sp_wasm_interface
spin
stable_deref_trait
static_assertions
statrs
stream_cipher
strsim
structopt
structopt_derive
strum
strum_macros
substrate_bip39
substrate_fixed
substrate_frame_rpc_system
substrate_prometheus_endpoint
subtle
syn
synstructure
take_mut
tap
target_lexicon
tempfile
termcolor
textwrap
thiserror
thiserror_impl
thread_local
threadpool
time
tiny_keccak
tinyvec
tinyvec_macros
tokio
future
io
loom
macros
net
park
runtime
signal
stream
sync
task
time
util
tokio_codec
tokio_executor
tokio_io
tokio_named_pipes
tokio_reactor
tokio_rustls
tokio_service
tokio_sync
tokio_uds
tokio_util
toml
tower_service
tracing
tracing_attributes
tracing_core
tracing_futures
tracing_log
tracing_serde
tracing_subscriber
trie_db
trie_root
try_lock
twox_hash
typenum
ucd_trie
uint
unicase
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
universal_hash
unsigned_varint
untrusted
url
vec_arena
vec_map
void
waker_fn
want
wasm_bindgen
wasm_bindgen_backend
wasm_bindgen_futures
wasm_bindgen_macro
wasm_bindgen_macro_support
wasm_bindgen_shared
wasm_timer
wasmi
wasmi_validation
wasmparser
wasmtime
wasmtime_cache
wasmtime_cranelift
wasmtime_debug
wasmtime_environ
wasmtime_jit
wasmtime_obj
wasmtime_profiling
wasmtime_runtime
wast
wat
webpki
webpki_roots
winapi
wyz
x25519_dalek
yamux
zeroize
zeroize_derive
zstd
zstd_safe
zstd_sys
  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
//! Iterators over `Vec<T>`.

use crate::{
	devel as dvl,
	mutability::Mutability,
	order::BitOrder,
	ptr::BitRef,
	slice::{
		BitSlice,
		Iter,
	},
	store::BitStore,
	vec::BitVec,
};

use alloc::vec::Vec;

use core::{
	fmt::{
		self,
		Debug,
		Formatter,
	},
	iter::{
		FromIterator,
		FusedIterator,
	},
	mem::{
		self,
		ManuallyDrop,
	},
	ops::{
		Range,
		RangeBounds,
	},
	ptr::NonNull,
};

use tap::{
	pipe::Pipe,
	tap::{
		Tap,
		TapOptional,
	},
};

impl<O, T> Extend<bool> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = bool> {
		let mut iter = iter.into_iter();
		match iter.size_hint() {
			(n, None) | (_, Some(n)) => {
				// This body exists to try to accelerate the push-per-bit loop.
				self.reserve(n);
				let len = self.len();
				let new_len = len + n;
				let new = unsafe { self.get_unchecked_mut(len .. new_len) };
				let mut pulled = 0;
				for (slot, bit) in
					unsafe { new.iter_mut().remove_alias() }.zip(iter.by_ref())
				{
					slot.set(bit);
					pulled += 1;
				}
				unsafe {
					self.set_len(len + pulled);
				}
			},
		}
		iter.for_each(|bit| self.push(bit));
	}
}

impl<'a, O, T> Extend<&'a bool> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = &'a bool> {
		self.extend(iter.into_iter().copied());
	}
}

impl<'a, M, O1, O2, T1, T2> Extend<BitRef<'a, M, O2, T2>> for BitVec<O1, T1>
where
	M: Mutability,
	O1: BitOrder,
	O2: BitOrder,
	T1: BitStore,
	T2: BitStore,
{
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = BitRef<'a, M, O2, T2>> {
		self.extend(iter.into_iter().map(|bit| *bit));
	}
}

impl<O, T> Extend<T> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = T> {
		for elem in iter.into_iter() {
			self.extend(BitSlice::<O, T>::from_element(&elem));
		}
	}
}

impl<'a, O, T> Extend<&'a T> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = &'a T> {
		for elem in iter.into_iter() {
			self.extend(BitSlice::<O, T>::from_element(elem));
		}
	}
}

impl<O, T> FromIterator<bool> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = bool> {
		Self::new().tap_mut(|bv| bv.extend(iter.into_iter()))
	}
}

impl<'a, M, O1, O2, T1, T2> FromIterator<BitRef<'a, M, O2, T2>>
	for BitVec<O1, T1>
where
	M: Mutability,
	O1: BitOrder,
	O2: BitOrder,
	T1: BitStore,
	T2: BitStore,
{
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = BitRef<'a, M, O2, T2>> {
		Self::new().tap_mut(|bv| bv.extend(iter.into_iter()))
	}
}

impl<'a, O, T> FromIterator<&'a bool> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = &'a bool> {
		iter.into_iter().copied().pipe(Self::from_iter)
	}
}

/** Collect a sequence of memory elements into a bit-vector.

This is a short-hand for, and implemented as, `iter.collect::<Vec<_>>().into()`.

This is not a standard-library API, and was added for [Issue #83].

[Issue #83]: https://github.com/myrrlyn/bitvec/issues/83
**/
impl<O, T> FromIterator<T> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = T> {
		iter.into_iter().collect::<Vec<_>>().pipe(Self::from_vec)
	}
}

impl<'a, O, T> FromIterator<&'a T> for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = &'a T> {
		let mut vec = iter
			.into_iter()
			.map(BitStore::load_value)
			.collect::<Vec<T::Mem>>()
			.pipe(ManuallyDrop::new);
		let (ptr, len, capa) = (vec.as_mut_ptr(), vec.len(), vec.capacity());
		unsafe { Vec::from_raw_parts(ptr as *mut T, len, capa) }
			.pipe(Self::from_vec)
	}
}

impl<O, T> IntoIterator for BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	type IntoIter = IntoIter<O, T>;
	type Item = bool;

	fn into_iter(self) -> Self::IntoIter {
		IntoIter::new(self)
	}
}

impl<'a, O, T> IntoIterator for &'a BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	type IntoIter = <&'a BitSlice<O, T> as IntoIterator>::IntoIter;
	type Item = <&'a BitSlice<O, T> as IntoIterator>::Item;

	fn into_iter(self) -> Self::IntoIter {
		self.as_bitslice().into_iter()
	}
}

impl<'a, O, T> IntoIterator for &'a mut BitVec<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	type IntoIter = <&'a mut BitSlice<O, T> as IntoIterator>::IntoIter;
	type Item = <&'a mut BitSlice<O, T> as IntoIterator>::Item;

	fn into_iter(self) -> Self::IntoIter {
		self.as_mut_bitslice().into_iter()
	}
}

/** An iterator that moves out of a [`BitVec`].

This `struct` is created by the [`into_iter`] method on [`BitVec`] (provided by
the [`IntoIterator`] trait).

# Original

[`vec::IntoIter`](alloc::vec::IntoIter)

[`BitVec`]: crate::vec::BitVec
[`IntoIterator`]: core::iter::IntoIterator
[`into_iter`]: core::iter::IntoIterator::into_iter
**/
pub struct IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	/// The base address of the allocation.
	base: NonNull<T>,
	/// The allocation capacity, measured in elements `T`.
	capa: usize,
	/// A [`BitSlice`] iterator over the vector’s contents.
	///
	/// [`BitSlice`]: crate::slice::BitSlice
	iter: Iter<'static, O, T>,
}

impl<O, T> IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	/// Constructs an iterator over a [`BitVec`].
	///
	/// [`BitVec`]: crate::vec::BitVec
	fn new(bv: BitVec<O, T>) -> Self {
		let capa = bv.capacity;
		//  Construct a `BitSlice` iterator over the region, and detach its
		//  lifetime.
		let iter = bv.bitspan.to_bitslice_ref().iter();
		//  Only the allocation’s base and capacity need to be kept for `Drop`.
		let base = bv.bitspan.address().to_nonnull();
		mem::forget(bv);
		Self { base, capa, iter }
	}

	/// Returns the remaining bits of this iterator as a [`BitSlice`].
	///
	/// # Original
	///
	/// [`vec::IntoIter::as_slice`](alloc::vec::IntoIter::as_slice)
	///
	/// # Examples
	///
	/// ```rust
	/// use bitvec::prelude::*;
	///
	/// let bv = bitvec![0, 1, 0, 1];
	/// let mut into_iter = bv.into_iter();
	///
	/// assert_eq!(into_iter.as_bitslice(), bits![0, 1, 0, 1]);
	/// let _ = into_iter.next().unwrap();
	/// assert_eq!(into_iter.as_bitslice(), bits![1, 0, 1]);
	/// ```
	///
	/// [`BitSlice`]: crate::slice::BitSlice
	pub fn as_bitslice(&self) -> &BitSlice<O, T> {
		self.iter.as_bitslice()
	}

	#[doc(hidden)]
	#[inline(always)]
	#[cfg(not(tarpalin_include))]
	#[deprecated = "Use `as_bitslice` to view the underlying slice"]
	pub fn as_slice(&self) -> &BitSlice<O, T> {
		self.as_bitslice()
	}

	/// Returns the remaining bits of this iterator as a mutable [`BitSlice`].
	///
	/// # Original
	///
	/// [`vec::IntoIter::as_mut_slice`](alloc::vec::IntoIter::as_mut_slice)
	///
	/// # Examples
	///
	/// ```rust
	/// use bitvec::prelude::*;
	///
	/// let bv = bitvec![0, 1, 0, 1];
	/// let mut into_iter = bv.into_iter();
	///
	/// assert_eq!(into_iter.as_bitslice(), bits![0, 1, 0, 1]);
	/// into_iter.as_mut_bitslice().set(2, true);
	/// assert!(!into_iter.next().unwrap());
	/// assert!(into_iter.next().unwrap());
	/// assert!(into_iter.next().unwrap());
	/// ```
	///
	/// [`BitSlice`]: crate::slice::BitSlice
	pub fn as_mut_bitslice(&mut self) -> &mut BitSlice<O, T> {
		let span = self.iter.as_bitslice().as_bitspan();
		let span_mut = unsafe { span.assert_mut() };
		span_mut.to_bitslice_mut()
	}

	#[doc(hidden)]
	#[inline(always)]
	#[cfg(not(tarpaulin_include))]
	#[deprecated = "Use `as_mut_bitslice` to view the underlying slice"]
	pub fn as_mut_slice(&mut self) -> &mut BitSlice<O, T> {
		self.as_mut_bitslice()
	}
}

#[cfg(not(tarpaulin_include))]
impl<O, T> Debug for IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
		fmt.debug_tuple("IntoIter")
			.field(&self.as_bitslice())
			.finish()
	}
}

impl<O, T> Iterator for IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	type Item = bool;

	fn next(&mut self) -> Option<Self::Item> {
		self.iter.next().as_deref().copied()
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		self.iter.size_hint()
	}

	fn count(self) -> usize {
		self.len()
	}

	fn nth(&mut self, n: usize) -> Option<Self::Item> {
		self.iter.nth(n).as_deref().copied()
	}

	fn last(mut self) -> Option<Self::Item> {
		self.next_back()
	}
}

impl<O, T> DoubleEndedIterator for IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn next_back(&mut self) -> Option<Self::Item> {
		self.iter.next_back().as_deref().copied()
	}

	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
		self.iter.nth_back(n).as_deref().copied()
	}
}

impl<O, T> ExactSizeIterator for IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn len(&self) -> usize {
		self.iter.len()
	}
}

impl<O, T> FusedIterator for IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
}

impl<O, T> Drop for IntoIter<O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn drop(&mut self) {
		//  Rebuild the `Vec` governing the allocation, and run its destructor.
		drop(unsafe { Vec::from_raw_parts(self.base.as_ptr(), 0, self.capa) });
	}
}

/** A draining iterator for [`BitVec`].

This `struct` is created by the [`.drain()`] method on [`BitVec`].

# Original

[`vec::Drain`](alloc::vec::Drain)

[`BitVec`]: crate::vec::BitVec
[`.drain()`]: crate::vec::BitVec::drain
**/
pub struct Drain<'a, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	/// Exclusive reference to the vector this drains.
	source: NonNull<BitVec<O, T>>,
	/// The range of the source vector’s buffer being drained.
	drain: Iter<'a, O, T>,
	/// The range of the source vector’s preserved tail. This runs from the back
	/// edge of the drained region to the vector’s original length.
	tail: Range<usize>,
}

impl<'a, O, T> Drain<'a, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	pub(super) fn new<R>(source: &'a mut BitVec<O, T>, range: R) -> Self
	where R: RangeBounds<usize> {
		//  Hold the current vector size for bounds comparison.
		let len = source.len();
		//  Normalize the input range and assert that it is within bounds.
		let drain = dvl::normalize_range(range, len);
		dvl::assert_range(drain.clone(), len);

		//  The tail region is everything after the drain, before the real end.
		let tail = drain.end .. len;
		//  The drain span is an iterator over the provided range.
		let drain = unsafe {
			//  Set the source vector to end before the drain.
			source.set_len(drain.start);
			//  Grab the drain range and produce an iterator over it.
			source
				.as_bitslice()
				.get_unchecked(drain)
				//  Detach the region from the `source` borrow.
				.as_bitspan()
				.to_bitslice_ref()
				.iter()
		};
		let source = source.into();
		Self {
			source,
			drain,
			tail,
		}
	}

	/// Returns the remaining bits of this iterator as a [`BitSlice`].
	///
	/// # Original
	///
	/// [`Drain::as_slice`](alloc::vec::Drain::as_slice)
	///
	/// # API Differences
	///
	/// This method is renamed, as it operates on a [`BitSlice`] rather than an
	/// element slice.
	///
	/// [`BitSlice`]: crate::slice::BitSlice
	pub fn as_bitslice(&self) -> &'a BitSlice<O, T> {
		self.drain.as_bitslice()
	}

	#[doc(hidden)]
	#[inline(always)]
	#[cfg(not(tarpaulin_include))]
	#[deprecated = "Use `as_bitslice` to view the underlying slice"]
	pub fn as_slice(&self) -> &BitSlice<O, T> {
		self.as_bitslice()
	}

	/// Attempts to overwrite the drained region with another iterator.
	///
	/// # Type Parameters
	///
	/// - `I`: Some source of `bool`s.
	///
	/// # Parameters
	///
	/// - `&mut self`
	/// - `iter`: A source of `bool`s with which to overwrite the drained span.
	///
	/// # Returns
	///
	/// Whether the drained span was completely filled, or if the replacement
	/// source `iter`ator was exhausted first.
	///
	/// # Effects
	///
	/// The source vector is extended to include all bits filled in from the
	/// replacement `iter`ator, but is *not* extended to include the tail, even
	/// if drained region is completely filled. This work is done in the
	/// destructor.
	fn fill<I>(&mut self, iter: &mut I) -> FillStatus
	where I: Iterator<Item = bool> {
		let bitvec = unsafe { self.source.as_mut() };
		//  Get the length of the source vector. This will be grown as `iter`
		//  writes into the drain span.
		let mut len = bitvec.len();
		//  Get the drain span as a bit-slice.
		let span = unsafe { bitvec.get_unchecked_mut(len .. self.tail.start) };

		//  Set the exit flag to assume completion.
		let mut out = FillStatus::FullSpan;
		//  Write the `iter` bits into the drain `span`.
		for slot in span {
			//  While the `iter` is not exhausted, write it into the span and
			//  increase the vector length counter.
			if let Some(bit) = iter.next() {
				slot.set(bit);
				len += 1;
			}
			//  If the `iter` exhausts before the drain `span` is filled, set
			//  the exit flag accordingly.
			else {
				out = FillStatus::EmptyInput;
				break;
			}
		}
		//  Update the vector length counter to include the bits written by
		//  `iter`.
		unsafe {
			bitvec.set_len(len);
		}
		out
	}

	/// Inserts `additional` capacity between the vector and the tail.
	///
	/// # Parameters
	///
	/// - `&mut self`
	/// - `additional`: The amount of new bits to reserve between the head and
	///   tail sections of the vector.
	///
	/// # Effects
	///
	/// This is permitted to reällocate the buffer in order to grow capacity.
	/// After completion, the tail segment will be relocated to begin
	/// `additional` bits after the head segment ends. The drain iteration
	/// cursor will not be modified.
	unsafe fn move_tail(&mut self, additional: usize) {
		if additional == 0 {
			return;
		}

		let bitvec = self.source.as_mut();
		let tail_len = self.tail.end - self.tail.start;

		//  Reserve allocation capacity for `additional` and the tail.
		//  `.reserve()` begins from the `bitvec.len()`, so the tail length must
		//  still be included.
		let full_len = additional + tail_len;
		bitvec.reserve(full_len);
		let new_tail_start = additional + self.tail.start;
		let orig_tail = mem::replace(
			&mut self.tail,
			new_tail_start .. new_tail_start + tail_len,
		);
		//  Temporarily resize the vector to include the full buffer. This is
		//  necessary until `copy_within_unchecked` stops using `.len()`
		//  internally.
		let len = bitvec.len();
		bitvec.set_len(full_len);
		bitvec.copy_within_unchecked(orig_tail, new_tail_start);
		bitvec.set_len(len);
	}
}

impl<O, T> AsRef<BitSlice<O, T>> for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn as_ref(&self) -> &BitSlice<O, T> {
		self.as_bitslice()
	}
}

#[cfg(not(tarpaulin_include))]
impl<'a, O, T> Debug for Drain<'a, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
		fmt.debug_tuple("Drain")
			.field(&self.drain.as_bitslice())
			.finish()
	}
}

impl<O, T> Iterator for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	type Item = bool;

	fn next(&mut self) -> Option<Self::Item> {
		self.drain.next().as_deref().copied()
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		self.drain.size_hint()
	}

	fn count(self) -> usize {
		self.len()
	}

	fn nth(&mut self, n: usize) -> Option<Self::Item> {
		self.drain.nth(n).as_deref().copied()
	}

	fn last(mut self) -> Option<Self::Item> {
		self.next_back()
	}
}

impl<O, T> DoubleEndedIterator for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn next_back(&mut self) -> Option<Self::Item> {
		self.drain.next_back().as_deref().copied()
	}

	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
		self.drain.nth_back(n).as_deref().copied()
	}
}

impl<O, T> ExactSizeIterator for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn len(&self) -> usize {
		self.drain.len()
	}
}

impl<O, T> FusedIterator for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
}

unsafe impl<O, T> Send for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
}

unsafe impl<O, T> Sync for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
}

impl<O, T> Drop for Drain<'_, O, T>
where
	O: BitOrder,
	T: BitStore,
{
	fn drop(&mut self) {
		//  Grab the tail range descriptor
		let tail = self.tail.clone();
		//  And compute its length.
		let tail_len = tail.end - tail.start;
		//  If the tail region is empty, then there is no cleanup work to do.
		if tail_len == 0 {
			return;
		}
		//  Otherwise, access the source vector,
		let bitvec = unsafe { self.source.as_mut() };
		//  And grab its current end.
		let old_len = bitvec.len();
		let new_len = old_len + tail_len;
		unsafe {
			//  Expand the vector to include where the tail bits will be.
			bitvec.set_len(new_len);
			//  Then move the tail bits into the new location.
			bitvec.copy_within_unchecked(tail, old_len);
			//  This ordering is important! `copy_within_unchecked` uses the
			//  `len` boundary.
		}
	}
}

/** `std` uses a `bool` flag for done/not done, which is less clear about what
it signals.

See <https://github.com/rust-lang/rust/blob/5779815/library/alloc/src/vec.rs#L3327-L3348>.
**/
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum FillStatus {
	/// The drain span is completely filled.
	FullSpan   = 0,
	/// The replacement source is completely emptied.
	EmptyInput = 1,
}

/** A splicing iterator for [`BitVec`].

This struct is created by the [`.splice()`] method on [`BitVec`]. See its
documentation for more.

# Original

[`vec::Splice`](alloc::vec::Splice)

[`BitVec`]: crate::vec::BitVec
[`.splice()`]: crate::vec::BitVec::splice
**/
#[derive(Debug)]
pub struct Splice<'a, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
	/// The region of the vector being spliced.
	drain: Drain<'a, O, T>,
	/// The bitstream to be written into the drain.
	splice: I,
}

impl<'a, O, T, I> Splice<'a, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
	/// Constructs a splice out of a drain and a replacement.
	pub(super) fn new<II>(drain: Drain<'a, O, T>, splice: II) -> Self
	where II: IntoIterator<IntoIter = I, Item = bool> {
		let splice = splice.into_iter();
		Self { drain, splice }
	}
}

impl<O, T, I> Iterator for Splice<'_, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
	type Item = bool;

	fn next(&mut self) -> Option<Self::Item> {
		self.drain.next().tap_some(|_| {
			/* Attempt to write a bit into the now-vacated slot at the front of
			the `Drain`. If the `splice` stream produces a bit, then it is
			written into the end of the `Drain`’s buffer, extending it by one.
			This works because `Drain` always truncates its vector to the front
			edge of the drain region, so `bv.len()` is always the first bit of
			the `Drain` region if the `Drain` is willing to yield a bit.
			*/
			if let Some(bit) = self.splice.next() {
				unsafe {
					let bv = self.drain.source.as_mut();
					let len = bv.len();
					bv.set_len_unchecked(len + 1);
					bv.set_unchecked(len, bit);
				}
			}
		})
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		self.drain.size_hint()
	}

	fn count(self) -> usize {
		self.len()
	}

	fn last(mut self) -> Option<Self::Item> {
		self.next_back()
	}
}

impl<O, T, I> DoubleEndedIterator for Splice<'_, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
	fn next_back(&mut self) -> Option<Self::Item> {
		self.drain.next_back()
	}

	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
		self.drain.nth_back(n)
	}
}

impl<O, T, I> ExactSizeIterator for Splice<'_, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
	fn len(&self) -> usize {
		self.drain.len()
	}
}

impl<O, T, I> FusedIterator for Splice<'_, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
}

impl<O, T, I> Drop for Splice<'_, O, T, I>
where
	O: BitOrder,
	T: BitStore,
	I: Iterator<Item = bool>,
{
	fn drop(&mut self) {
		let tail = self.drain.tail.clone();
		let tail_len = tail.end - tail.start;
		let bitvec = unsafe { self.drain.source.as_mut() };

		//  If the `drain` has no tail span, then extend the vector with the
		//  splice and exit.
		if tail_len == 0 {
			bitvec.extend(self.splice.by_ref());
			return;
		}

		//  Fill the drained range first. If the `splice` exhausts, then the
		//  `Drain` destructor will handle relocating the vector tail segment.
		if let FillStatus::EmptyInput = self.drain.fill(&mut self.splice) {
			return;
		}

		//  If the `splice` has not yet exhausted, then the `Drain` needs to
		//  adjust to receive its contents.
		let len = match self.splice.size_hint() {
			(n, None) | (_, Some(n)) => n,
		};
		unsafe {
			self.drain.move_tail(len);
		}
		//  Now that the tail has been relocated, fill the `splice` into it. If
		//  this exhausts the `splice`, exit.
		if let FillStatus::EmptyInput = self.drain.fill(&mut self.splice) {
			return;
		}

		/* If the `splice` *still* has bits to provide, then its `.size_hint()`
		is untrustworthy. Collect the `splice` into a vector, then insert the
		vector into the spliced region.
		*/
		let mut collected = self.splice.by_ref().collect::<BitVec>().into_iter();
		let len = collected.len();
		if len > 0 {
			unsafe {
				self.drain.move_tail(len);
			}
			let filled = self.drain.fill(&mut collected);
			debug_assert_eq!(filled, FillStatus::EmptyInput);
			debug_assert_eq!(collected.len(), 0);
		}
	}
}