1use super::LappError;
2
3pub fn skipws(slice: &str) -> &str {
4 let nxt = slice.find(|c: char| ! c.is_whitespace()).unwrap_or(slice.len());
5 &slice[nxt..]
6}
7
8pub fn grab_word<'a>(pslice: &mut &str) -> String {
9 let nxt = pslice.find(|c: char| c.is_whitespace()).unwrap_or(pslice.len());
10 let word = (&pslice[0..nxt]).to_string();
11 *pslice = skipws(&pslice[nxt..]);
12 word
13}
14
15pub fn starts_with(pslice: &mut &str, start: &str) -> bool {
16 if pslice.starts_with(start) {
17 *pslice = &pslice[start.len()..];
18 true
19 } else {
20 false
21 }
22}
23
24pub fn ends_with(pslice: &mut &str, start: &str) -> bool {
25 if pslice.ends_with(start) {
26 *pslice = &pslice[0..(pslice.len() - start.len())];
27 true
28 } else {
29 false
30 }
31}
32
33pub fn grab_upto(pslice: &mut &str, sub: &str) -> Result<String,LappError> {
34 if let Some(idx) = pslice.find(sub) {
35 let s = (&pslice[0..idx].trim()).to_string();
36 *pslice = &pslice[idx+sub.len()..];
37 Ok(s)
38 } else {
39 Err(LappError(format!("cannot find end {:?}",sub)))
40 }
41}
42
43pub fn split_with<'a>(slice: &'a str, needle: &str) -> Option<(&'a str,&'a str)> {
44 if let Some(idx) = slice.find(needle) {
45 Some((
46 &slice[0..idx], &slice[idx+needle.len()..]
47 ))
48 } else {
49 None
50 }
51}
52
53pub fn dedent(s: &str) -> String {
54 let mut lines = s.lines();
55 let mut res = String::new();
56 let mut idx = None;
57 while let Some(line) = lines.next() {
58 if let Some(pos) = line.chars().position(|c| ! c.is_whitespace()) {
59 idx = Some(pos);
60 res += &line[pos..];
61 res.push('\n');
62 break;
63 }
64 }
65 if let Some(pos) = idx {
66 while let Some(line) = lines.next() {
67 res += if line.len() >= pos { &line[pos..] } else { line };
68 res.push('\n');
69 }
70 }
71 res
72}