Skip to main content

gm_lib/utils/
text.rs

1use std::cmp::min;
2
3pub fn split_string(s: &str, max_width: usize) -> Vec<&str> {
4    let mut lines = vec![];
5
6    let mut ptr = 0;
7    let s_len = s.len();
8    while ptr < s_len {
9        let next = min(ptr + max_width, s_len);
10        let s = s.get(ptr..next).expect("couldnt slice"); // can't go wrong
11        lines.push(s);
12        ptr = next;
13    }
14
15    if lines.is_empty() {
16        lines.push("");
17    }
18
19    lines
20}
21
22#[cfg(test)]
23mod test {
24    use super::*;
25
26    #[test]
27    fn test_split_string() {
28        assert_eq!(
29            split_string("hello what is up", 6),
30            vec!["hello ", "what i", "s up"]
31        );
32    }
33}