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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#[derive(Debug, PartialEq, Eq)]
// Struct that represents a range of text in a source code file content
pub struct Range {
    pub start: LineColumn,
    pub end: LineColumn,
}

/// Lines and Columns start form 1
///
/// 12345678910   15   20   25...
/// hello_world
///
/// {line: 1, column: 1} -> {line: 1, column: 6} => "hello"
/// {line: 1, column: 2} -> {line: 1, column: 6} => "ello"
/// {line: 1, column: 1} -> {line: 1, column: 1} => ""
#[derive(Debug, PartialEq, Eq)]
pub struct LineColumn {
    pub line: usize,
    pub column: usize,
}

/// Given a source file, extract a substring from it at the given range
pub fn extract_range(s: &str, range: &Range) -> String {
    let mut result = String::new();
    for (i, line) in s.lines().enumerate() {
        let line_number = i + 1;

        if line_number >= range.start.line && line_number <= range.end.line {
            if !result.is_empty() {
                result.push('\n');
            }

            for (j, char) in line.chars().enumerate() {
                let column = j + 1;
                if !((line_number == range.start.line && column < range.start.column)
                    || (line_number == range.end.line && column >= range.end.column))
                {
                    result.push(char)
                }
            }
        }
    }

    result
}

/// Given a source code file content and a Vec<Range>, split content
/// into chunks while also removing the content within provided ranges, so that
/// it can later be replaced with something else.
pub fn split_by_ranges(content: String, ranges: Vec<&Range>) -> Vec<String> {
    let mut iter = ranges.iter().peekable();

    // ranges must be pre-sorted
    while let Some(range) = iter.next() {
        if let Some(next_range) = iter.peek() {
            #[allow(clippy::all)]
            if range.end.line >= next_range.start.line {
                panic!("overlapping ranges! can be only one inline snapshot macro per line");
            }
        }
    }

    let mut ranges_iter = ranges.into_iter();
    let mut chunks = vec![];
    let mut next_chunk = String::new();
    let mut next_range = ranges_iter.next();

    for (i, line) in content.lines().enumerate() {
        let line_number = i + 1;

        if let Some(range) = next_range {
            match line_number {
                n if n < range.start.line => {
                    next_chunk.push_str(line);
                    next_chunk.push('\n');
                }
                n if n == range.start.line => {
                    let chars = line.chars().collect::<Vec<_>>();

                    let mut chars_before = chars;
                    let mut rest = chars_before.split_off(range.start.column - 1);
                    let str_before: String = chars_before.iter().collect();
                    next_chunk.push_str(&str_before);

                    // The range is in a single line
                    if n == range.end.line {
                        let chars_after = rest.split_off(range.end.column - 1 - chars_before.len());
                        let str_after: String = chars_after.iter().collect();

                        chunks.push(next_chunk);
                        next_chunk = String::new();
                        next_range = ranges_iter.next();

                        next_chunk.push_str(&str_after);
                        next_chunk.push('\n');
                    }
                }
                n if n > range.start.line && n < range.end.line => {}
                n if n == range.end.line => {
                    chunks.push(next_chunk);
                    next_chunk = String::new();
                    next_range = ranges_iter.next();

                    let mut chars = line.chars().collect::<Vec<_>>();
                    let after_chars = chars.split_off(range.end.column - 1);
                    let after_str: String = after_chars.iter().collect();
                    next_chunk.push_str(&after_str);
                    next_chunk.push('\n');
                }
                _ => panic!(
                    "invalid range or file. Line: `{}` Range: {:?}",
                    line_number, range
                ),
            };
        } else {
            next_chunk.push_str(line);
            next_chunk.push('\n');
        }
    }
    chunks.push(next_chunk);
    chunks
}

#[cfg(test)]
mod tests {
    use super::*;

    const CONTENT: &str = r##"
Hello World
Random Subset
1234567
"##;

    #[test]
    fn extracting_range() {
        k9_stable::assert_equal!(
            extract_range(
                CONTENT,
                &Range {
                    start: LineColumn { line: 2, column: 1 },
                    end: LineColumn { line: 2, column: 6 }
                }
            )
            .as_str(),
            "Hello"
        );
    }

    #[test]
    fn empty_range() {
        k9_stable::assert_equal!(
            extract_range(
                CONTENT,
                &Range {
                    start: LineColumn { line: 2, column: 1 },
                    end: LineColumn { line: 2, column: 1 }
                }
            )
            .as_str(),
            ""
        );
    }

    #[test]
    fn overflow() {
        k9_stable::assert_equal!(
            extract_range(
                CONTENT,
                &Range {
                    start: LineColumn {
                        line: 99,
                        column: 1
                    },
                    end: LineColumn {
                        line: 199,
                        column: 1
                    }
                }
            )
            .as_str(),
            ""
        );
    }
}