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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use std::ops::Range;

#[cfg(test)]
mod tests;

pub trait Searchable
where
    Self: Sized,
{
    fn eat_word(&mut self, word: &str) -> Option<Self>;
    fn advance_char(&mut self, by: usize) -> Option<Self>;
    fn search_len(&self) -> usize;
}

#[derive(PartialEq, Clone)]
pub enum Buffer<'code> {
    Cont { chunk: Chunk<'code> },
    Frag(Box<Buffer<'code>>, Box<Buffer<'code>>),
}

impl<'code> std::fmt::Debug for Buffer<'code> {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Self::Cont { chunk } => {
                std::fmt::Debug::fmt(chunk, f)
            }
            Self::Frag(arg0, arg1) => f
                .debug_set()
                .entries([arg0, arg1].iter())
                .finish(),
        }
    }
}

impl<'code> std::fmt::Display for Buffer<'code> {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Buffer::Cont { chunk } => f.write_str(chunk),
            Buffer::Frag(lhs, rhs) => {
                write!(f, "{}{}", lhs, rhs)
            }
        }
    }
}

impl<'code> Buffer<'code> {
    fn search_char_len(&self) -> usize {
        match self {
            Buffer::Cont { chunk } => chunk
                .search_str()
                .unwrap_or("")
                .chars()
                .count(),
            Buffer::Frag(lhs, rhs) => {
                lhs.search_char_len()
                    + rhs.search_char_len()
            }
        }
    }
}

impl<'code> std::ops::Add for Buffer<'code> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (
                Buffer::Cont { chunk: lhs },
                Buffer::Cont { chunk: rhs },
            ) => lhs + rhs,
            (
                Buffer::Cont { chunk: lhs },
                Buffer::Frag(r_lhs, r_rhs),
            ) => Self::Frag(
                Box::new(Buffer::from(lhs) + *r_lhs),
                r_rhs,
            ),
            (
                Buffer::Frag(l_lhs, l_rhs),
                Buffer::Cont { chunk: rhs },
            ) => Self::Frag(
                l_lhs,
                Box::new(*l_rhs + Buffer::from(rhs)),
            ),
            (
                Buffer::Frag(l_lhs, l_rhs),
                Buffer::Frag(r_lhs, r_rhs),
            ) => *l_lhs + *l_rhs + *r_lhs + *r_rhs,
        }
    }
}

impl<'code> std::ops::Add for Chunk<'code> {
    type Output = Buffer<'code>;

    fn add(mut self, rhs: Self) -> Self::Output {
        match self.search_range() {
            Some(lhs_range) => match rhs.search_range() {
                Some(rhs_range) => {
                    // Check if code same and boundaries
                    // align
                    if self.code == rhs.code
                        && (lhs_range.start
                            == rhs_range.end
                            || lhs_range.end
                                == rhs_range.start)
                    {
                        let start = lhs_range
                            .start
                            .min(rhs_range.start);
                        let end = lhs_range
                            .end
                            .max(rhs_range.end);
                        self.range = start..end;
                        Buffer::from(self)
                    }
                    else {
                        let mut return_value = Buffer::Frag(
                            Box::new(Buffer::from(self)),
                            Box::new(Buffer::from(rhs)),
                        );
                        return_value.defrag();
                        return_value
                    }
                }
                None => Buffer::from(self),
            },
            None => Buffer::from(rhs),
        }
    }
}

impl<'code> Buffer<'code> {
    fn defrag(&mut self) {
        // Remove blank nodes
        if let Self::Frag(lhs, rhs) = &self {
            if let Self::Cont { chunk } = lhs.as_ref() {
                if chunk.search_range().is_none() {
                    *self = *rhs.clone();
                }
            }
            else if let Self::Cont { chunk } =
                rhs.as_ref()
            {
                if chunk.search_range().is_none() {
                    *self = *lhs.clone();
                }
            }
        }
    }
}

impl<'code> Searchable for Buffer<'code> {
    fn eat_word(&mut self, word: &str) -> Option<Self> {
        match self {
            Buffer::Cont { chunk } => chunk
                .eat_word(word)
                .map(|chunk| Self::Cont { chunk }),

            Buffer::Frag(lhs, rhs) => {
                // Construct LHS word
                let lhs_word_end =
                    word.len().min(lhs.search_len());
                let lhs_word = &word[0..lhs_word_end];

                // Attempt to eat on LHS
                let mut lhs_temp = *lhs.clone();
                let lhs_new =
                    lhs_temp.eat_word(lhs_word)?;

                // Construct RHS word
                let rhs_word = &word[lhs_word_end..];
                let rhs_word = (!rhs_word.is_empty())
                    .then_some(rhs_word);

                // Attempt to eat on RHS only if RHS has
                // words to eat
                let return_value = match rhs_word {
                    Some(rhs_word) => {
                        // Attempt to eat on RHS
                        let mut rhs_temp = *rhs.clone();
                        let rhs_new =
                            rhs_temp.eat_word(rhs_word)?;

                        // Reset self
                        // LHS can be disregarded because it
                        // has been consumed
                        *self = rhs_temp;

                        // Create return value and defrag
                        let mut return_value =
                            lhs_new + rhs_new;
                        return_value.defrag();
                        return_value
                    }
                    None => {
                        *lhs = Box::new(lhs_temp);
                        self.defrag();
                        lhs_new
                    }
                };

                // Defrag and return
                Some(return_value)
            }
        }
    }

    fn advance_char(&mut self, by: usize) -> Option<Self> {
        match self {
            Buffer::Cont { chunk } => chunk
                .advance_char(by)
                .map(|chunk| Self::Cont { chunk }),

            Buffer::Frag(lhs, rhs) => {
                // Construct LHS search length
                let by_lhs = lhs.search_char_len().min(by);

                // Attempt to advance on LHS
                let mut lhs_temp = *lhs.clone();
                let lhs_new =
                    lhs_temp.advance_char(by_lhs)?;

                // Construct RHS search length
                let by_rhs = by
                    .checked_sub(by_lhs)
                    .and_then(|value| {
                        (!value.eq(&0)).then_some(value)
                    });

                // Get return value
                let return_value = match by_rhs {
                    // If RHS word exists
                    Some(by_rhs) => {
                        // Construct RHS
                        let mut rhs_temp = *rhs.clone();
                        let rhs_new = rhs_temp
                            .advance_char(by_rhs)?;

                        // Reset self
                        // LHS can be disregarded because it
                        // has been consumed
                        *self = rhs_temp;

                        // Create return value and defrag
                        let mut return_value =
                            lhs_new + rhs_new;
                        return_value.defrag();
                        return_value
                    }
                    None => {
                        *lhs = Box::new(lhs_temp);
                        self.defrag();
                        lhs_new
                    }
                };

                // Defrag and return
                Some(return_value)
            }
        }
    }

    fn search_len(&self) -> usize {
        match self {
            Self::Cont { chunk } => chunk.search_len(),
            Self::Frag(lhs, rhs) => {
                lhs.search_len() + rhs.search_len()
            }
        }
    }
}

impl<'code> From<&'code str> for Buffer<'code> {
    fn from(code: &'code str) -> Self {
        Self::Cont {
            chunk: Chunk::from(code),
        }
    }
}

impl<'code> From<Chunk<'code>> for Buffer<'code> {
    fn from(chunk: Chunk<'code>) -> Self {
        Self::Cont { chunk }
    }
}

#[derive(PartialEq)]
pub struct Chunk<'code> {
    code: &'code str,
    range: Range<usize>,
}

impl<'code> ::std::ops::Deref for Chunk<'code> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        let range = self.search_range().unwrap_or(0..0);
        &self.code[range]
    }
}

impl<'code> From<&'code str> for Chunk<'code> {
    fn from(code: &'code str) -> Self {
        Self {
            code,
            range: 0..code.len(),
        }
    }
}

impl<'code> std::fmt::Debug for Chunk<'code> {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self.search_range() {
            Some(range) => {
                write!(
                    f,
                    "[{:?}] {}",
                    range,
                    &self.code[range.clone()],
                )
            }
            None => f.write_str("None"),
        }
    }
}

impl<'code> std::fmt::Display for Chunk<'code> {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        f.write_str(self.search_str().unwrap_or(""))
    }
}

impl<'code> Searchable for Chunk<'code> {
    fn eat_word(&mut self, word: &str) -> Option<Self> {
        self.search_str()?
            .starts_with(word)
            .then_some(())?;
        self.advance_by(word.len())
    }

    fn advance_char(&mut self, by: usize) -> Option<Self> {
        let search_str = self.search_str()?;
        let by = by.checked_sub(1)?;
        let mut len = None::<usize>;
        for (count, character) in
            search_str.chars().enumerate()
        {
            // Break if count exceeded
            if count > by {
                break;
            }
            let char_len = character.len_utf8();
            len = match len {
                Some(len) => Some(char_len + len),
                None => Some(char_len),
            }
        }
        let len = len?;
        self.advance_by(len)
    }

    fn search_len(&self) -> usize {
        let search_range =
            self.search_range().unwrap_or(0..0);
        search_range.end - search_range.start
    }
}

impl<'code> Chunk<'code> {
    pub fn range_end(&self) -> usize {
        self.range.end.min(self.code.len())
    }

    pub fn search_range(&self) -> Option<Range<usize>> {
        // Check for overflow
        let search_start = (self.range.start
            < self.code.len())
        .then_some(self.range.start)?;

        // Get range end
        let search_end = self.range_end();

        // Check if the end is larger than start
        (search_end > search_start)
            .then_some(search_start..search_end)
    }

    pub fn search_str(&self) -> Option<&str> {
        // Basic sanity check
        let search_range = self.search_range()?;
        Some(&self.code[search_range])
    }

    pub fn advance_by(
        &mut self,
        by: usize,
    ) -> Option<Self> {
        // Recalculate by
        let by = self.range.start + by;

        // Return one
        if by > self.range_end() {
            None
        }
        // Return none if past code end
        else {
            // Create eaten token
            let mut eaten = self.clone();
            eaten.range.end = by;

            // Move self
            self.range.start = by;

            // Return eaten token
            Some(eaten)
        }
    }
}

impl<'code> Clone for Chunk<'code> {
    fn clone(&self) -> Self {
        Self {
            code: self.code,
            range: self.range.clone(),
        }
    }
}