Skip to content

Iter focused #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 148 additions & 0 deletions src/ascii_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ extern crate core;

use self::core::{fmt, mem};
use self::core::ops::{Index, IndexMut, Range, RangeTo, RangeFrom, RangeFull};
use self::core::slice::{Iter, IterMut};
#[cfg(feature = "std")]
use std::error::Error;
#[cfg(feature = "std")]
Expand Down Expand Up @@ -139,6 +140,32 @@ impl AsciiStr {
self.len() == 0
}

/// Returns an iterator over the characters of the `AsciiStr`.
#[inline]
pub fn chars(&self) -> Chars {
self.slice.iter()
}

/// Returns an iterator over the characters of the `AsciiStr` which allows you to modify the
/// value of each `AsciiChar`.
#[inline]
pub fn chars_mut(&mut self) -> CharsMut {
self.slice.iter_mut()
}

/// Returns an iterator over the lines of the `AsciiStr`, which are themselves `AsciiStr`s.
///
/// Lines are ended with either `LineFeed` (`\n`), or `CarriageReturn` then `LineFeed` (`\r\n`).
///
/// The final line ending is optional.
#[inline]
pub fn lines(&self) -> Lines {
Lines {
current_index: 0,
string: self
}
}

/// Returns an ASCII string slice with leading and trailing whitespace removed.
///
/// # Examples
Expand Down Expand Up @@ -388,6 +415,82 @@ impl AsciiExt for AsciiStr {
}
}

impl<'a> IntoIterator for &'a AsciiStr {
type Item = &'a AsciiChar;
type IntoIter = Chars<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.chars()
}
}

impl<'a> IntoIterator for &'a mut AsciiStr {
type Item = &'a mut AsciiChar;
type IntoIter = CharsMut<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.chars_mut()
}
}

/// An immutable iterator over the characters of an `AsciiStr`.
pub type Chars<'a> = Iter<'a, AsciiChar>;

/// A mutable iterator over the characters of an `AsciiStr`.
pub type CharsMut<'a> = IterMut<'a, AsciiChar>;

/// An iterator over the lines of the internal character array.
#[derive(Clone, Debug)]
pub struct Lines<'a> {
current_index: usize,
string: &'a AsciiStr
}

impl<'a> Iterator for Lines<'a> {
type Item = &'a AsciiStr;

fn next(&mut self) -> Option<Self::Item> {
let curr_idx = self.current_index;
let len = self.string.len();
if curr_idx >= len {
return None;
}

let mut next_idx = None;
let mut linebreak_skip = 0;

for i in curr_idx..(len-1) {
match (self.string[i], self.string[i + 1]) {
(AsciiChar::CarriageReturn, AsciiChar::LineFeed) => {
next_idx = Some(i);
linebreak_skip = 2;
break;
}
(AsciiChar::LineFeed, _) => {
next_idx = Some(i);
linebreak_skip = 1;
break;
}
_ => {}
}
}

let next_idx = match next_idx {
Some(i) => i,
None => return None
};
let line = &self.string[curr_idx..next_idx];

self.current_index = next_idx + linebreak_skip;

if line.is_empty() && self.current_index == self.string.len() {
// This is a trailing line break
None
} else {
Some(line)
}
}
}

/// Error that is returned when a sequence of `u8` are not all ASCII.
///
Expand Down Expand Up @@ -604,6 +707,51 @@ mod tests {
assert_eq!(b, "A@A");
}

#[test]
fn chars_iter() {
let chars = &[b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd', b'\0'];
let ascii = AsciiStr::from_ascii(chars).unwrap();
for (achar, byte) in ascii.chars().zip(chars.iter()) {
assert_eq!(achar, byte);
}
}

#[test]
fn chars_iter_mut() {
let mut chars = &mut [b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd', b'\0'];
let mut ascii = chars.as_mut_ascii_str().unwrap();

*ascii.chars_mut().next().unwrap() = AsciiChar::H;

assert_eq!(ascii[0], b'H');
}

#[test]
fn lines_iter() {
use super::core::iter::Iterator;
let lines: [&str; 3] = ["great work", "cool beans", "awesome stuff"];
let joined = "great work\ncool beans\r\nawesome stuff\n";
let ascii = AsciiStr::from_ascii(joined.as_bytes()).unwrap();
for (asciiline, line) in ascii.lines().zip(&lines) {
assert_eq!(asciiline, *line);
}

let trailing_line_break = b"\n";
let ascii = AsciiStr::from_ascii(&trailing_line_break).unwrap();
for _ in ascii.lines() {
unreachable!();
}

let empty_lines = b"\n\r\n\n\r\n";
let mut ensure_iterated = false;
let ascii = AsciiStr::from_ascii(&empty_lines).unwrap();
for line in ascii.lines() {
ensure_iterated = true;
assert!(line.is_empty());
}
assert!(ensure_iterated);
}

#[test]
#[cfg(feature = "std")]
fn fmt_ascii_str() {
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ mod ascii_string;

pub use free_functions::{caret_encode, caret_decode};
pub use ascii_char::{AsciiChar, ToAsciiChar, ToAsciiCharError};
pub use ascii_str::{AsciiStr, AsAsciiStr, AsMutAsciiStr, AsAsciiStrError};
pub use ascii_str::{AsciiStr, AsAsciiStr, AsMutAsciiStr, AsAsciiStrError, Chars, CharsMut, Lines};
#[cfg(feature = "std")]
pub use ascii_string::{AsciiString, IntoAsciiString, FromAsciiError};