summaryrefslogtreecommitdiff
path: root/src/chomp/set.rs
blob: 8f97e8a1e0d3e21e06587cf1b4ea43886c5c5555 (plain)
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
use std::{collections::BTreeSet, convert::TryInto};

// From 1.50 std::core::iter::range lines 425--450
fn step_char_forward(c : char) -> Option<char> {
    let start = u32::from(c);
    let mut res = start.checked_add(1)?;

    if start < 0xD800 && 0xD800 <= res {
        res = start.checked_add(0x800)?;
    }

    res.try_into().ok()
}

fn step_char_backward(c : char) -> Option<char> {
    let start = u32::from(c);
    let mut res = start.checked_sub(1)?;

    if start >= 0xE000 && 0xE000 > res {
        res = start.checked_sub(0x800)?;
    }

    res.try_into().ok()
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
pub struct FirstSet {
    inner: Vec<(char, char)>,
}

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

    pub fn of_str(s: &str) -> Self {
        Self {
            inner: s.chars().next().into_iter().map(|c| (c, c)).collect(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    pub fn union(self, mut other: Self) -> Self {
        let mut out = Vec::new();
        let mut iters = [self.into_iter().peekable(), other.into_iter().peekable()];

        'outer: loop {
            // Look at the next two ranges, and find the minimum next character
            let (min, mut max) = match (iters[0].peek(), iters[1].peek()) {
                // Both inputs exhausted
                (None, None) => break,
                // Add remainder to output
                (None, Some(_)) => {
                    out.extend(iters[1]);
                    break
                }
                (Some(_), None) => {
                    out.extend(iters[0]);
                    break
                }
                // The interesting case
                (Some((left, left_max)), Some((right, right_max))) => {
                    if left > right {
                        iters.swap(0, 1);
                        (*right, *right_max)
                    } else {
                        (*left, *left_max)
                    }
                }
            };

            max = match step_char_forward(max) {
                Some(c) => c,
                None => {
                    // assert!(max == char::MAX)
                    // This swallows all other ranges
                    out.push((min, max));
                    break;
                }
            };

            // There are a few cases:
            // - No overlap:
            //    ----
            //         ----
            // - Extend:
            //    ----
            //     ----
            // - Swallow:
            //    ---------
            //       ----
            // We loop until there is no overlap.
            // For extend, we step the left and swap.
            // For swallow, we step the right only
            while let Some((other_min, other_max)) = iters[1].peek() {
                if *other_min > max {
                    // No overlap
                    break;
                }

                // max is one past range, other_max is in range, so we use >=
                if *other_max >= max {
                    // Extend
                    iters[0].next();
                    iters.swap(0, 1);
                    max = match step_char_forward(*other_max) {
                        Some(c) => c,
                        None => { out.push((min, max)); break 'outer }
                    };
                } else {
                    // Swallow
                    iters[1].next();
                }
            }

            let end = step_char_backward(max).expect("char + 1 - 1 != char");
            out.push((min, end));
            iters[0].next();
        }

        Self {inner: out}
    }

    pub fn intersect(&self, other: &Self) -> Self {
        todo!()
        // Self {
        //     inner: self.inner.intersection(&other.inner).copied().collect(),
        // }
    }
}

impl IntoIterator for FirstSet {
    type Item = (char, char);

    type IntoIter = <Vec<(char, char)> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.into_iter()
    }
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
pub struct FlastSet {
    inner: BTreeSet<char>,
}

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

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    pub fn union_first(mut self, mut other: FirstSet) -> Self {
        // self.inner.append(&mut other.inner);
        // self
        todo!()
    }

    pub fn union(mut self, mut other: Self) -> Self {
        self.inner.append(&mut other.inner);
        self
    }

    pub fn intersect_first(&self, other: &FirstSet) -> Self {
        // Self {
        //     inner: self.inner.intersection(&other.inner).copied().collect(),
        // }
        todo!()
    }

    pub fn intersect(&self, other: &Self) -> Self {
        Self {
            inner: self.inner.intersection(&other.inner).copied().collect(),
        }
    }
}

impl IntoIterator for FlastSet {
    type Item = char;

    type IntoIter = <BTreeSet<char> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.into_iter()
    }
}

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

    #[test]
    fn test_first_union_none() {
        let left = FirstSet { inner: vec![('A', 'Z'), ('a', 'z')]};
        let right = FirstSet {inner: vec![]};
        assert_eq!(left.union(right), left)
    }

    #[test]
    fn test_first_union_shallow() {
        let left = FirstSet { inner: vec![('A', 'Z'), ('a', 'z')]};
        let right = FirstSet {inner: vec![('b', 'y')]};
        assert_eq!(left.union(right), left)
    }

    #[test]
    fn test_first_union_extend() {
        let left = FirstSet { inner: vec![('A', 'Z'), ('a', 'z')]};
        let right = FirstSet {inner: vec![('[', '`')]};
        assert_eq!(left.union(right), FirstSet {inner: vec![('A', 'z')]})
    }
}