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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::{
    cmp::Ordering,
    fmt, io,
    io::BufRead,
    iter,
    ops::{Add, AddAssign, Sub, SubAssign},
};

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Text {
    lines: Vec<String>,
}

impl Text {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn newline() -> Self {
        Self {
            lines: vec![String::new(), String::new()],
        }
    }

    pub fn from_buf_reader<R>(reader: R) -> io::Result<Self>
    where
        R: BufRead,
    {
        Ok(Self {
            lines: reader.lines().collect::<Result<_, _>>()?,
        })
    }

    pub fn is_empty(&self) -> bool {
        self.length() == Length::zero()
    }

    pub fn length(&self) -> Length {
        Length {
            line_count: self.lines.len() - 1,
            byte_count: self.lines.last().unwrap().len(),
        }
    }

    pub fn to_single_char(&self) -> Option<char> {
        if self.lines.len() > 1 {
            return None;
        }
        let mut chars = self.lines[0].chars();
        match (chars.next(), chars.next()) {
            (Some(char), None) => Some(char),
            _ => None,
        }
    }

    pub fn as_lines(&self) -> &[String] {
        &self.lines
    }

    pub fn slice(&self, start: Position, length: Length) -> Self {
        let end = start + length;
        let mut lines = Vec::new();
        if start.line_index == end.line_index {
            lines.push(self.lines[start.line_index][start.byte_index..end.byte_index].to_string());
        } else {
            lines.reserve(end.line_index - start.line_index + 1);
            lines.push(self.lines[start.line_index][start.byte_index..].to_string());
            lines.extend(
                self.lines[start.line_index + 1..end.line_index]
                    .iter()
                    .cloned(),
            );
            lines.push(self.lines[end.line_index][..end.byte_index].to_string());
        }
        Text { lines }
    }

    pub fn apply_change(&mut self, change: Change) {
        match change {
            Change::Insert(position, text) => self.insert(position, text),
            Change::Delete(start, length) => self.delete(start, length),
        }
    }

    pub fn into_lines(self) -> Vec<String> {
        self.lines
    }

    fn insert(&mut self, point: Position, mut text: Self) {
        if text.length().line_count == 0 {
            self.lines[point.line_index].replace_range(
                point.byte_index..point.byte_index,
                text.lines.first().unwrap(),
            );
        } else {
            text.lines
                .first_mut()
                .unwrap()
                .replace_range(..0, &self.lines[point.line_index][..point.byte_index]);
            text.lines
                .last_mut()
                .unwrap()
                .push_str(&self.lines[point.line_index][point.byte_index..]);
            self.lines
                .splice(point.line_index..point.line_index + 1, text.lines);
        }
    }

    fn delete(&mut self, start: Position, length: Length) {
        let end = start + length;
        if start.line_index == end.line_index {
            self.lines[start.line_index].replace_range(start.byte_index..end.byte_index, "");
        } else {
            let mut line = self.lines[start.line_index][..start.byte_index].to_string();
            line.push_str(&self.lines[end.line_index][end.byte_index..]);
            self.lines
                .splice(start.line_index..end.line_index + 1, iter::once(line));
        }
    }
}

impl Default for Text {
    fn default() -> Self {
        Self {
            lines: vec![String::new()],
        }
    }
}

impl fmt::Display for Text {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (last_line, remaining_lines) = self.lines.split_last().unwrap();
        for line in remaining_lines {
            writeln!(f, "{}", line)?;
        }
        write!(f, "{}", last_line)
    }
}

impl From<char> for Text {
    fn from(char: char) -> Self {
        Self {
            lines: vec![String::from(char)],
        }
    }
}

impl From<&str> for Text {
    fn from(string: &str) -> Self {
        Self {
            lines: string.lines().map(|string| string.to_owned()).collect(),
        }
    }
}

impl From<&String> for Text {
    fn from(string: &String) -> Self {
        string.as_str().into()
    }
}

impl From<String> for Text {
    fn from(string: String) -> Self {
        string.as_str().into()
    }
}

impl FromIterator<char> for Text {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = char>,
    {
        Text::from(iter.into_iter().collect::<String>())
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Edit {
    pub change: Change,
    pub drift: Drift,
}

impl Edit {
    pub fn invert(self, text: &Text) -> Self {
        Self {
            change: self.change.invert(text),
            drift: self.drift,
        }
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Change {
    Insert(Position, Text),
    Delete(Position, Length),
}

impl Change {
    pub fn invert(self, text: &Text) -> Self {
        match self {
            Self::Insert(position, text) => Change::Delete(position, text.length()),
            Self::Delete(start, length) => Change::Insert(start, text.slice(start, length)),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Position {
    pub line_index: usize,
    pub byte_index: usize,
}

impl Position {
    pub fn zero() -> Self {
        Self::default()
    }

    pub fn apply_edit(self, edit: &Edit) -> Self {
        match edit.change {
            Change::Insert(point, ref text) => match self.cmp(&point) {
                Ordering::Less => self,
                Ordering::Equal => match edit.drift {
                    Drift::Before => point + text.length() + (self - point),
                    Drift::After => self,
                },
                Ordering::Greater => point + text.length() + (self - point),
            },
            Change::Delete(start, length) => {
                let end = start + length;
                if self < start {
                    self
                } else {
                    start + (self - end.min(self))
                }
            }
        }
    }
}

impl Add<Length> for Position {
    type Output = Self;

    fn add(self, length: Length) -> Self::Output {
        if length.line_count == 0 {
            Self {
                line_index: self.line_index,
                byte_index: self.byte_index + length.byte_count,
            }
        } else {
            Self {
                line_index: self.line_index + length.line_count,
                byte_index: length.byte_count,
            }
        }
    }
}

impl AddAssign<Length> for Position {
    fn add_assign(&mut self, length: Length) {
        *self = *self + length;
    }
}

impl Sub for Position {
    type Output = Length;

    fn sub(self, other: Self) -> Self::Output {
        if self.line_index == other.line_index {
            Length {
                line_count: 0,
                byte_count: self.byte_index - other.byte_index,
            }
        } else {
            Length {
                line_count: self.line_index - other.line_index,
                byte_count: self.byte_index,
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Length {
    pub line_count: usize,
    pub byte_count: usize,
}

impl Length {
    pub fn zero() -> Length {
        Self::default()
    }
}

impl Add for Length {
    type Output = Length;

    fn add(self, other: Self) -> Self::Output {
        if other.line_count == 0 {
            Self {
                line_count: self.line_count,
                byte_count: self.byte_count + other.byte_count,
            }
        } else {
            Self {
                line_count: self.line_count + other.line_count,
                byte_count: other.byte_count,
            }
        }
    }
}

impl AddAssign for Length {
    fn add_assign(&mut self, other: Self) {
        *self = *self + other;
    }
}

impl Sub for Length {
    type Output = Length;

    fn sub(self, other: Self) -> Self::Output {
        if self.line_count == other.line_count {
            Self {
                line_count: 0,
                byte_count: self.byte_count - other.byte_count,
            }
        } else {
            Self {
                line_count: self.line_count - other.line_count,
                byte_count: self.byte_count,
            }
        }
    }
}

impl SubAssign for Length {
    fn sub_assign(&mut self, other: Self) {
        *self = *self - other;
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Drift {
    Before,
    After,
}