Skip to main content

braid_core/vendor/rle/
rlerun.rs

1use std::ops::Range;
2use crate::vendor::rle::{HasLength, MergableSpan, SplitableSpanHelpers};
3
4/// A splitablespan which contains a single element repeated N times. This is used in some examples.
5#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, Default)]
6pub struct RleRun<T: Clone + Eq> {
7    pub val: T,
8    pub len: usize,
9}
10
11impl<T: Clone + Eq> RleRun<T> {
12    pub fn new(val: T, len: usize) -> Self {
13        Self { val, len }
14    }
15
16    pub fn single(val: T) -> Self {
17        Self { val, len: 1 }
18    }
19}
20
21impl<T: Clone + Eq> HasLength for RleRun<T> {
22    fn len(&self) -> usize { self.len }
23}
24
25impl<T: Clone + Eq> SplitableSpanHelpers for RleRun<T> {
26    fn truncate_h(&mut self, at: usize) -> Self {
27        let remainder = self.len - at;
28        self.len = at;
29        Self { val: self.val.clone(), len: remainder }
30    }
31}
32
33impl<T: Clone + Eq> MergableSpan for RleRun<T> {
34    fn can_append(&self, other: &Self) -> bool {
35        self.val == other.val || self.len == 0
36    }
37
38    fn append(&mut self, other: Self) {
39        self.len += other.len;
40        self.val = other.val; // Needed when we use default() - which gives it a length of 0.
41    }
42}
43
44/// Distinct RLE run. Each distinct run expresses some value between each (start, end) pair.
45#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, Default)]
46pub struct RleDRun<T> {
47    pub start: usize,
48    pub end: usize,
49    pub val: T,
50}
51
52impl<T: Clone> RleDRun<T> {
53    pub fn new(range: Range<usize>, val: T) -> Self {
54        Self {
55            start: range.start,
56            end: range.end,
57            val,
58        }
59    }
60}
61
62impl<T: Clone> HasLength for RleDRun<T> {
63    fn len(&self) -> usize { self.end - self.start }
64}
65
66impl<T: Clone> SplitableSpanHelpers for RleDRun<T> {
67    fn truncate_h(&mut self, at: usize) -> Self {
68        let split_point = self.start + at;
69        debug_assert!(split_point < self.end);
70        let remainder = Self { start: split_point, end: self.end, val: self.val.clone() };
71        self.end = split_point;
72        remainder
73    }
74}
75
76impl<T: Clone + Eq> MergableSpan for RleDRun<T> {
77    fn can_append(&self, other: &Self) -> bool {
78        self.end == other.start && self.val == other.val
79    }
80
81    fn append(&mut self, other: Self) {
82        self.end = other.end;
83    }
84}
85
86
87// impl<T: Copy + std::fmt::Debug> Searchable for RleDRun<T> {
88//     type Item = T;
89//
90//     fn get_offset(&self, _loc: Self::Item) -> Option<usize> {
91//         unimplemented!()
92//     }
93//
94//     fn at_offset(&self, offset: usize) -> Self::Item {
95//         Some(
96//     }
97// }