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
use super::{Chunks, Rope};

pub struct Bytes<'a> {
  index: usize,
  current: Option<&'a [u8]>,
  chunks: Chunks<'a>,
}

unsafe impl<'a> Sync for Bytes<'a> {}
unsafe impl<'a> Send for Bytes<'a> {}

impl<'a> From<&'a Rope> for Bytes<'a> {
  #[inline]
  fn from(rope: &'a Rope) -> Bytes<'a> {
    let mut chunks = Chunks::from(rope);

    Bytes {
      index: 0,
      current: chunks.next().map(|s| s.as_bytes()),
      chunks: chunks,
    }
  }
}

impl<'a> Iterator for Bytes<'a> {
  type Item = u8;

  #[inline]
  fn next(&mut self) -> Option<Self::Item> {
    if let Some(ref bytes) = self.current {
      match bytes.get(self.index) {
        Some(ch) => {
          self.index += 1;
          return Some(*ch);
        }
        None => {
          self.index = 0;
        }
      }
    } else {
      return None;
    }

    self.current = self.chunks.next().map(|s| s.as_bytes());
    self.next()
  }
}