What to do?

Read lines from some content and iterate over each line.

Source code

 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
use std::str;

struct LineIter<'a> {
  content: &'a str,
  offset: usize,
  length: usize,
}

impl<'a> LineIter<'a> {
  fn new(content: &'a str) -> Self {
    LineIter {
      content,
      offset: 0,
      length: content.len(),
    }
  }
}

impl<'a> Iterator for LineIter<'a> {
  type Item = &'a str;

  fn next(&mut self) -> Option<&'a str> {
    if self.offset >= self.length {
      return None;
    }

    let offsetted = &self.content[self.offset..];
    let bytes = offsetted.as_bytes();

    if let Some(i) = bytes.iter().position(|&b| b == b'\n') {
      self.offset += i + 1;

      let sub = if bytes[i - 1] == b'\r' {
        &offsetted[0..i - 1]
      } else {
        &offsetted[0..i]
      };
      Some(sub)
    } else {
      self.offset = self.length;
      Some(&offsetted)
    }
  }
}

fn main() {
  let content = "* Rust \n ** Line  \r\n  *** Iterator \n!";
  println!("First line: {}", LineIter::new(&content).next().unwrap());
  for line in LineIter::new(&content) {
    println!("{}", line);
  }

  for line in content.lines() {
    println!("{}", line);
  }

  println!("First line: {}", content.lines().next().unwrap());
}

Output

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
cargo run 
   Compiling org_parser v0.1.0 (/home/x/x/x)
    Finished dev [unoptimized + debuginfo] target(s) in 0.17s
     Running `target/debug/xxx`
First line: * Rust 
* Rust 
 ** Line  
  *** Iterator 
!
* Rust 
 ** Line  
  *** Iterator 
!
First line: * Rust

Ref