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

//! Iterator types

use crate::{SharedGenString, RefCounter};

/// A Split iterator returned by
/// [split](../struct.SharedGenString.html#method.split).
#[derive(Debug, Clone)]
pub struct Split<R> {
	start: usize,
	len: usize,
	bytes: R,
	byte: u8
}

impl<R> Split<R>
where R: RefCounter {
	pub(crate) fn new(start: usize, len: usize, bytes: R, byte: u8) -> Self {
		Self { start, len, bytes, byte }
	}

	#[inline]
	fn remaning_slice(&self) -> &[u8] {
		// Safe because only we control start and len
		let range = self.start..(self.start + self.len);
		unsafe { self.bytes.get_unchecked(range) }
	}

	// returns index of new byte or self.len
	#[inline]
	fn find_next(&self) -> usize {
		self.remaning_slice()
			.iter()
			.position(|b| b == &self.byte)
			.unwrap_or(self.len)
	}
}

impl<R> Iterator for Split<R>
where R: RefCounter {
	type Item = SharedGenString<R>;

	fn next(&mut self) -> Option<Self::Item> {
		if self.len == 0 {
			return None
		}

		let at = self.find_next();
		let n_at = at + 1; // might out-of-bound

		let n_start = self.start;
		self.start += n_at;
		self.len = self.len.saturating_sub(n_at);
		Some(SharedGenString::new_raw(
			n_start,
			at,
			self.bytes.clone()
		))
	}
}

/// A Lines iterator returned by
/// [lines](../struct.SharedGenString.html#method.lines).
#[derive(Debug, Clone)]
pub struct Lines<R> {
	start: usize,
	len: usize,
	bytes: R
}

impl<R> Lines<R>
where R: RefCounter {
	pub(crate) fn new(start: usize, len: usize, bytes: R) -> Self {
		Self { start, len, bytes }
	}

	#[inline]
	fn remaning_slice(&self) -> &[u8] {
		// Safe because only we control start and len
		let range = self.start..(self.start + self.len);
		unsafe { self.bytes.get_unchecked(range) }
	}

	// returns index of new byte or self.len
	#[inline]
	fn find_next(&self) -> usize {
		self.remaning_slice()
			.iter()
			.position(|&b| b == b'\n')
			.unwrap_or(self.len)
	}
}

impl<R> Iterator for Lines<R>
where R: RefCounter {
	type Item = SharedGenString<R>;

	fn next(&mut self) -> Option<Self::Item> {
		if self.len == 0 {
			return None
		}

		let mut at = self.find_next();
		// + 1 for skipping \n
		let newline_at = at + 1; // could be out-of-bound

		let n_start = self.start;
		self.start += newline_at;
		self.len = self.len.saturating_sub(newline_at);

		// check if should do at - 1 (to remove \r)
		if at >= 1 && self.bytes[n_start + at - 1] == b'\r' {
			at -= 1;
		}

		Some(SharedGenString::new_raw(
			n_start,
			at,
			self.bytes.clone()
		))
	}
}