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
#![doc = include_str!("../../doc/vec/iter.md")]

use alloc::vec::Vec;
use core::{
	fmt::{
		self,
		Debug,
		Formatter,
	},
	iter::{
		FromIterator,
		FusedIterator,
	},
	mem,
	ops::Range,
};

use tap::{
	Pipe,
	Tap,
	TapOptional,
};
use wyz::{
	comu::{
		Mut,
		Mutability,
	},
	range::RangeExt,
};

use super::BitVec;
use crate::{
	boxed::BitBox,
	mem::bits_of,
	order::BitOrder,
	ptr::{
		BitPtrRange,
		BitRef,
	},
	slice::BitSlice,
	store::BitStore,
	view::BitView,
};

#[doc = include_str!("../../doc/vec/iter/Extend_bool.md")]
impl<T, O> Extend<bool> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = bool> {
		let mut iter = iter.into_iter();
		#[allow(irrefutable_let_patterns)] // Removing the `if` is unstable.
		if let (_, Some(n)) | (n, None) = iter.size_hint() {
			self.reserve(n);
			let len = self.len();
			//  If the reservation did not panic, then this will not overflow.
			let new_len = len.wrapping_add(n);
			let new = unsafe { self.get_unchecked_mut(len .. new_len) };

			let pulled = new
				.as_mut_bitptr_range()
				.zip(iter.by_ref())
				.map(|(ptr, bit)| unsafe {
					ptr.write(bit);
				})
				.count();
			unsafe {
				self.set_len(len + pulled);
			}
		}

		//  If the iterator is well-behaved and finite, this should never
		//  enter; if the iterator is infinite, then this will eventually crash.
		iter.for_each(|bit| self.push(bit));
	}
}

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

#[cfg(not(tarpaulin_include))]
#[doc = include_str!("../../doc/vec/iter/Extend_BitRef.md")]
impl<'a, M, T1, T2, O1, O2> Extend<BitRef<'a, M, T2, O2>> for BitVec<T1, O1>
where
	M: Mutability,
	T1: BitStore,
	T2: BitStore,
	O1: BitOrder,
	O2: BitOrder,
{
	#[inline]
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = BitRef<'a, M, T2, O2>> {
		self.extend(iter.into_iter().map(|bit| *bit));
	}
}

impl<T, O> Extend<T> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = T> {
		let iter = iter.into_iter();
		#[allow(irrefutable_let_patterns)]
		if let (_, Some(n)) | (n, None) = iter.size_hint() {
			self.reserve(n.checked_mul(bits_of::<T::Mem>()).unwrap());
		}
		iter.for_each(|elem| self.extend_from_bitslice(elem.view_bits::<O>()));
	}
}

#[cfg(not(tarpaulin_include))]
impl<'a, T, O> Extend<&'a T> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn extend<I>(&mut self, iter: I)
	where I: IntoIterator<Item = &'a T> {
		self.extend(
			iter.into_iter()
				.map(BitStore::load_value)
				.map(<T as BitStore>::new),
		);
	}
}

#[cfg(not(tarpaulin_include))]
#[doc = include_str!("../../doc/vec/iter/FromIterator_bool.md")]
impl<T, O> FromIterator<bool> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = bool> {
		Self::new().tap_mut(|bv| bv.extend(iter))
	}
}

#[cfg(not(tarpaulin_include))]
impl<'a, T, O> FromIterator<&'a bool> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = &'a bool> {
		iter.into_iter().copied().collect::<Self>()
	}
}

#[cfg(not(tarpaulin_include))]
#[doc = include_str!("../../doc/vec/iter/FromIterator_BitRef.md")]
impl<'a, M, T1, T2, O1, O2> FromIterator<BitRef<'a, M, T2, O2>>
	for BitVec<T1, O1>
where
	M: Mutability,
	T1: BitStore,
	T2: BitStore,
	O1: BitOrder,
	O2: BitOrder,
{
	#[inline]
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = BitRef<'a, M, T2, O2>> {
		iter.into_iter().map(|br| *br).pipe(Self::from_iter)
	}
}

#[cfg(not(tarpaulin_include))]
impl<T, O> FromIterator<T> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = T> {
		iter.into_iter().collect::<Vec<T>>().pipe(Self::from_vec)
	}
}

#[cfg(not(tarpaulin_include))]
impl<'a, T, O> FromIterator<&'a T> for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn from_iter<I>(iter: I) -> Self
	where I: IntoIterator<Item = &'a T> {
		iter.into_iter()
			.map(<T as BitStore>::load_value)
			.map(<T as BitStore>::new)
			.collect::<Self>()
	}
}

#[doc = include_str!("../../doc/vec/iter/IntoIterator.md")]
impl<T, O> IntoIterator for BitVec<T, O>
where
	T: BitStore,
	O: BitOrder,
{
	type IntoIter = <BitBox<T, O> as IntoIterator>::IntoIter;
	type Item = <BitBox<T, O> as IntoIterator>::Item;

	#[inline]
	fn into_iter(self) -> Self::IntoIter {
		self.into_boxed_bitslice().into_iter()
	}
}

#[cfg(not(tarpaulin_include))]
/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Vec.html#impl-IntoIterator-1)
impl<'a, T, O> IntoIterator for &'a BitVec<T, O>
where
	O: BitOrder,
	T: 'a + BitStore,
{
	type IntoIter = <&'a BitSlice<T, O> as IntoIterator>::IntoIter;
	type Item = <&'a BitSlice<T, O> as IntoIterator>::Item;

	#[inline]
	fn into_iter(self) -> Self::IntoIter {
		self.as_bitslice().iter()
	}
}

#[cfg(not(tarpaulin_include))]
/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Vec.html#impl-IntoIterator-2)
impl<'a, T, O> IntoIterator for &'a mut BitVec<T, O>
where
	O: BitOrder,
	T: 'a + BitStore,
{
	type IntoIter = <&'a mut BitSlice<T, O> as IntoIterator>::IntoIter;
	type Item = <&'a mut BitSlice<T, O> as IntoIterator>::Item;

	#[inline]
	fn into_iter(self) -> Self::IntoIter {
		self.as_mut_bitslice().iter_mut()
	}
}

#[doc = include_str!("../../doc/vec/iter/Drain.md")]
pub struct Drain<'a, T, O>
where
	O: BitOrder,
	T: 'a + BitStore,
{
	/// Exclusive reference to the handle that created the drain.
	source: &'a mut BitVec<T, O>,
	/// The range of the source bit-vector’s buffer that is being drained.
	drain:  BitPtrRange<Mut, T, O>,
	/// The range of the source bit-vector’s preserved back section. This runs
	/// from the first bit after the `.drain` to the first bit after the
	/// original bit-vector ends.
	tail:   Range<usize>,
}

impl<'a, T, O> Drain<'a, T, O>
where
	O: BitOrder,
	T: 'a + BitStore,
{
	/// Produces a new drain over a region of a bit-vector.
	pub(super) fn new<R>(source: &'a mut BitVec<T, O>, range: R) -> Self
	where R: RangeExt<usize> {
		let len = source.len();
		let region = range.normalize(None, len);
		assert!(
			region.end <= len,
			"drains cannot extend past the length of their source bit-vector",
		);

		//  The `.tail` region is everything in the bit-vector after the drain.
		let tail = region.end .. len;
		let drain = unsafe {
			//  Artificially truncate the source bit-vector to before the drain
			//  region. This is restored in the destructor.
			source.set_len_unchecked(region.start);
			let base = source.as_mut_bitptr();
			BitPtrRange {
				start: base.add(region.start),
				end:   base.add(region.end),
			}
		};

		Self {
			source,
			drain,
			tail,
		}
	}

	/// Views the unyielded bits remaining in the drain.
	///
	/// ## Original
	///
	/// [`Drain::as_slice`](alloc::vec::Drain::as_slice)
	#[inline]
	#[cfg(not(tarpaulin_include))]
	pub fn as_bitslice(&self) -> &'a BitSlice<T, O> {
		unsafe { self.drain.clone().into_bitspan().into_bitslice_ref() }
	}

	#[inline]
	#[cfg(not(tarpaulin_include))]
	#[deprecated = "use `.as_bitslice()` instead"]
	#[allow(missing_docs, clippy::missing_docs_in_private_items)]
	pub fn as_slice(&self) -> &'a BitSlice<T, O> {
		self.as_bitslice()
	}

	/// Attempts to fill the `drain` region with the contents of another
	/// iterator.
	///
	/// The source bit-vector is extended to include each bit that the
	/// replacement iterator provides, but is *not yet* extended to include the
	/// `tail` region, even if the replacement iterator completely fills the
	/// `drain` region. That work occurs in the destructor.
	///
	/// This is only used by [`Splice`].
	///
	/// [`Splice`]: crate::vec::Splice
	#[inline]
	fn fill(&mut self, iter: &mut impl Iterator<Item = bool>) -> FillStatus {
		let bv = &mut *self.source;
		let mut len = bv.len();
		let span =
			unsafe { bv.as_mut_bitptr().add(len).range(self.tail.start - len) };

		let mut out = FillStatus::FullSpan;
		for ptr in span {
			if let Some(bit) = iter.next() {
				unsafe {
					ptr.write(bit);
				}
				len += 1;
			}
			else {
				out = FillStatus::EmptyInput;
				break;
			}
		}
		unsafe {
			bv.set_len_unchecked(len);
		}
		out
	}

	/// Reserves space for `additional` more bits at the end of the `drain`
	/// region by moving the `tail` region upwards in memory.
	///
	/// This has the same effects as [`BitVec::resize`], except that the bits
	/// are inserted between `drain` and `tail` rather than at the end.
	///
	/// This does not modify the drain iteration cursor, including its endpoint.
	/// The newly inserted bits are not available for iteration.
	///
	/// This is only used by [`Splice`], which may insert more bits than the
	/// drain removed.
	///
	/// [`BitVec::resize`]: crate::vec::BitVec::resize
	/// [`Splice`]: crate::vec::Splice
	unsafe fn move_tail(&mut self, additional: usize) {
		if additional == 0 {
			return;
		}

		let bv = &mut *self.source;
		let tail_len = self.tail.len();

		let full_len = additional + tail_len;
		bv.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,
		);
		let len = bv.len();
		bv.set_len_unchecked(full_len);
		bv.copy_within_unchecked(orig_tail, new_tail_start);
		bv.set_len_unchecked(len);
	}
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-AsRef%3C%5BT%5D%3E)
#[cfg(not(tarpaulin_include))]
impl<T, O> AsRef<BitSlice<T, O>> for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn as_ref(&self) -> &BitSlice<T, O> {
		self.as_bitslice()
	}
}

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

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-Iterator)
#[cfg(not(tarpaulin_include))]
impl<T, O> Iterator for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
{
	type Item = bool;

	easy_iter!();

	#[inline]
	fn next(&mut self) -> Option<Self::Item> {
		self.drain.next().map(|bp| unsafe { bp.read() })
	}

	#[inline]
	fn nth(&mut self, n: usize) -> Option<Self::Item> {
		self.drain.nth(n).map(|bp| unsafe { bp.read() })
	}
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-DoubleEndedIterator)
#[cfg(not(tarpaulin_include))]
impl<T, O> DoubleEndedIterator for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn next_back(&mut self) -> Option<Self::Item> {
		self.drain.next_back().map(|bp| unsafe { bp.read() })
	}

	#[inline]
	fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
		self.drain.nth_back(n).map(|bp| unsafe { bp.read() })
	}
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-ExactSizeIterator)
#[cfg(not(tarpaulin_include))]
impl<T, O> ExactSizeIterator for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn len(&self) -> usize {
		self.drain.len()
	}
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-FusedIterator)
impl<T, O> FusedIterator for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
{
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-Send)
// #[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T, O> Send for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
	for<'a> &'a mut BitSlice<T, O>: Send,
{
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-Sync)
unsafe impl<T, O> Sync for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
	BitSlice<T, O>: Sync,
{
}

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-Drop)
impl<T, O> Drop for Drain<'_, T, O>
where
	T: BitStore,
	O: BitOrder,
{
	#[inline]
	fn drop(&mut self) {
		let tail = mem::take(&mut self.tail);
		let tail_len = tail.len();
		if tail_len == 0 {
			return;
		}

		let bv = &mut *self.source;
		let old_len = bv.len();
		unsafe {
			bv.set_len_unchecked(tail.end);
			bv.copy_within_unchecked(tail, old_len);
			bv.set_len_unchecked(old_len + tail_len);
		}
	}
}

#[repr(u8)]
#[doc = include_str!("../../doc/vec/iter/FillStatus.md")]
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum FillStatus {
	/// The drain span is completely filled.
	FullSpan   = 0,
	/// The replacement source is completely exhausted.
	EmptyInput = 1,
}

#[derive(Debug)]
#[doc = include_str!("../../doc/vec/iter/Splice.md")]
pub struct Splice<'a, T, O, I>
where
	O: BitOrder,
	T: 'a + BitStore,
	I: Iterator<Item = bool>,
{
	/// The region of the bit-vector being drained.
	drain:  Drain<'a, T, O>,
	/// The bitstream that replaces drained bits.
	splice: I,
}

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

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

	easy_iter!();

	#[inline]
	fn next(&mut self) -> Option<Self::Item> {
		self.drain.next().tap_some(|_| unsafe {
			if let Some(bit) = self.splice.next() {
				let bv = &mut *self.drain.source;
				let len = bv.len();
				bv.set_len_unchecked(len + 1);
				bv.set_unchecked(len, bit);
			}
		})
	}
}

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

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

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

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

/// [Original](https://doc.rust-lang.org/alloc/vec/struct.Drain.html#impl-Drop)
impl<T, O, I> Drop for Splice<'_, T, O, I>
where
	T: BitStore,
	O: BitOrder,
	I: Iterator<Item = bool>,
{
	#[inline]
	fn drop(&mut self) {
		let tail = self.drain.tail.clone();
		let tail_len = tail.len();
		let bv = &mut *self.drain.source;

		if tail_len == 0 {
			bv.extend(self.splice.by_ref());
			return;
		}

		if let FillStatus::EmptyInput = self.drain.fill(&mut self.splice) {
			return;
		}

		let len = match self.splice.size_hint() {
			(n, None) | (_, Some(n)) => n,
		};

		unsafe {
			self.drain.move_tail(len);
		}
		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
		 * bit-vector, then insert the bit-vector into the spliced region.
		 */
		let mut collected =
			self.splice.by_ref().collect::<BitVec<T, O>>().into_iter();
		let len = collected.len();
		if len > 0 {
			unsafe {
				self.drain.move_tail(len);
			}
			let filled = self.drain.fill(collected.by_ref());
			debug_assert_eq!(filled, FillStatus::EmptyInput);
			debug_assert_eq!(collected.len(), 0);
		}
	}
}