Trait LazyCharIterExt

Source
pub trait LazyCharIterExt {
    type Iter;

    // Required method
    fn chars(&self) -> Self::Iter;
}
Expand description

Iterate over the characters in a given type.

Required Associated Types§

Required Methods§

Source

fn chars(&self) -> Self::Iter

Returns an iterator over the chars of the given type.

Since the underlying type is not guaranteed to be valid UTF-8, the iterator will return Option<Result<char, Utf8Error>> instead of just char

It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided here; check (crates.io)[https://crates.io] instead.

§Examples

Basic usage:

use lazy_char_iter::LazyCharIterExt;

let bread_str: &str = "brød";
let bread_bytes: &[u8] = bread_str.as_bytes();
assert!(bread_bytes.len() == 5); // ø is \xc3\xb8

let mut char_iter = bread_bytes.chars();
assert_eq!(char_iter.next(), Some(Ok('b')));
assert_eq!(char_iter.next(), Some(Ok('r')));
assert_eq!(char_iter.next(), Some(Ok('ø')));
assert_eq!(char_iter.next(), Some(Ok('d')));
assert_eq!(char_iter.next(), None);

Invalid UTF-8 results in an error when the invalid character is hit:

use lazy_char_iter::{LazyCharIterExt, Utf8Error};

let invalid = vec![b'b', b'r', b'\xc3', b'\xc3', b'd'];
let invalid_bytes: &[u8] = invalid.as_slice();

let mut char_iter = invalid_bytes.chars();
assert_eq!(char_iter.next(), Some(Ok('b')));
assert_eq!(char_iter.next(), Some(Ok('r')));
assert_eq!(char_iter.next(), Some(Err(Utf8Error::InvalidEncoding(vec![0xc3, 0xc3]))));

Implementations on Foreign Types§

Source§

impl<'a> LazyCharIterExt for &'a Vec<u8>

Source§

type Iter = LazyCharSliceIter<'a>

Source§

fn chars(&self) -> Self::Iter

Source§

impl<'a> LazyCharIterExt for &'a [u8]

Source§

type Iter = LazyCharSliceIter<'a>

Source§

fn chars(&self) -> Self::Iter

Implementors§