reusable_memory/borrow/
manual_specialization.rs

1//! This module contains sort of manual "specializations" for pushing from iterators.
2
3use super::ReusableMemoryBorrow;
4
5impl<'mem, T> ReusableMemoryBorrow<'mem, T> {
6	/// Pushes new values from `iter: impl Iterator` while possible.
7	///
8	/// Returns the remaining iterator if `self.len()` reaches capacity.
9	///
10	/// Note that the returned iterator might be exhausted.
11	/// Use [`push_from_iter_peeking`](#method.push_from_iter_peeking)
12	/// to only return `Err` when `iter` is not exhausted.
13	pub fn push_from_iter<I: Iterator<Item = T>>(&mut self, mut iter: I) -> Result<(), I> {
14		while self.len() < self.capacity().get() {
15			match iter.next() {
16				Some(value) => self.push(value).unwrap(),
17				None => return Ok(())
18			}
19		}
20
21		Err(iter)
22	}
23
24	/// Pushes new values from `iter: impl Iterator` and peeks ahead.
25	///
26	/// Returns the remaining iterator (wrapped in `Peekable`)
27	/// if `self.len()` reaches capacity and it is not exhausted.
28	pub fn push_from_iter_peeking<I: Iterator<Item = T>>(
29		&mut self, mut iter: I
30	) -> Result<(), std::iter::Peekable<I>> {
31		while self.len() < self.capacity().get() {
32			match iter.next() {
33				Some(value) => self.push(value).unwrap(),
34				None => return Ok(())
35			}
36		}
37
38		let mut iter = iter.peekable();
39		if iter.peek().is_none() {
40			return Ok(())
41		}
42
43		Err(iter)
44	}
45
46	pub fn push_from_iter_size_hint<I: Iterator<Item = T>>(&mut self, iter: I) -> Result<(), I> {
47		let hint = iter.size_hint();
48		let hinted_max = hint.1.unwrap_or(hint.0);
49
50		if hinted_max > self.capacity().get() - self.len() {
51			return Err(iter)
52		}
53
54		self.push_from_iter(iter)
55	}
56
57	/// Pushes new values from `iter: impl ExactSizeIterator`.
58	///
59	/// Returns the iterator if there is not enough capacity.
60	pub fn push_from_exact_iter<I: ExactSizeIterator<Item = T>>(
61		&mut self, iter: I
62	) -> Result<(), I> {
63		if self.len() + iter.len() > self.capacity.get() {
64			return Err(iter)
65		}
66
67		for elem in iter {
68			self.push(elem).unwrap()
69		}
70
71		Ok(())
72	}
73}