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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
//! A little Rust library that enables you to write multiline strings à la Scala. // https://github.com/scala/scala/blob/39148e4ec34a5c53443dd1b25ceec2308cd097fe/src/library/scala/collection/StringOps.scala#L739-L763 pub trait StripMargin { /// For every line in this string, strip a leading prefix consisting of blanks or control characters, /// followed by `margin_char` from the line. /// /// # Examples /// ```rust /// use stripmargin::StripMargin; /// assert_eq!( /// r#"Hello, /// @ world! /// @"# /// .strip_margin_with('@'), /// "Hello,\n world!\n", /// ); /// ``` /// /// Please note that a non-whitespace margin won't get stripped: /// ```rust /// use stripmargin::StripMargin; /// assert_eq!( /// "Hello * world!".strip_margin_with('*'), /// "Hello * world!", /// ); /// ``` fn strip_margin_with(&self, margin_char: char) -> String; /// Shorthand for `strip_margin_with('|')`. /// /// For every line in this string, strip a leading prefix consisting of blanks or control characters, /// followed by `'|'` from the line. /// /// # Examples /// ```rust /// use stripmargin::StripMargin; /// assert_eq!( /// r#"Hello, /// | world! /// |"# /// .strip_margin(), /// "Hello,\n world!\n", /// ); /// ``` /// /// Please note that a non-whitespace margin won't get stripped: /// ```rust /// use stripmargin::StripMargin; /// assert_eq!( /// "Hello | world!".strip_margin(), /// "Hello | world!", /// ); /// ``` fn strip_margin(&self) -> String { self.strip_margin_with('|') } } impl<S: AsRef<str>> StripMargin for S { fn strip_margin_with(&self, margin_char: char) -> String { self.as_ref() .split('\n') .map(|line| { let mut chars = line.chars().skip_while(|ch| ch.is_whitespace()); match chars.next() { Some(c) if c == margin_char => chars.collect(), _ => line.to_owned(), } }) .collect::<Vec<_>>() .join("\n") } }