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
//! Utilities for indexing objects in memory, such as the source code object.

use super::Source;
use std::{
    cmp::Ordering,
    convert::TryFrom,
    fmt,
    ops::{
        Range,
        RangeFrom,
        RangeFull,
        RangeInclusive,
        RangeTo,
        RangeToInclusive,
    },
    slice,
};

/// Builder of an [`IndexArray`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct IndexArrayBuilder {
    /// 8 bit indices, which will be sorted by the end.
    as_u8: Vec<u8>,
    /// 16 bit indices, which will be sorted by the end.
    as_u16: Vec<u16>,
    /// 32 bit indices, which will be sorted by the end.
    as_u32: Vec<u32>,
    /// 64 bit indices, which will be sorted by the end.
    as_u64: Vec<u64>,
}

impl IndexArrayBuilder {
    /// Creates a new builder with no elements.
    pub fn new() -> Self {
        Self::default()
    }

    /// The length of this builder.
    pub fn len(&self) -> usize {
        self.as_u8.len()
            + self.as_u16.len()
            + self.as_u32.len()
            + self.as_u64.len()
    }

    /// Pushes a new index onto the builder.
    pub fn push(&mut self, index: usize) -> &mut Self {
        if let Ok(i) = u8::try_from(index) {
            self.as_u8.push(i);
        } else if let Ok(i) = u16::try_from(index) {
            self.as_u16.push(i);
        } else if let Ok(i) = u32::try_from(index) {
            self.as_u32.push(i);
        } else if let Ok(i) = u64::try_from(index) {
            self.as_u64.push(i);
        } else {
            panic!("Index {} is too big", index);
        }
        self
    }

    /// Finishes the builder and creates and [`IndexArray`].
    pub fn finish(mut self) -> IndexArray {
        self.as_u8.sort();
        self.as_u16.sort();
        self.as_u32.sort();
        self.as_u64.sort();

        IndexArray {
            as_u8: self.as_u8.into(),
            as_u16: self.as_u16.into(),
            as_u32: self.as_u32.into(),
            as_u64: self.as_u64.into(),
        }
    }
}

impl From<IndexArrayBuilder> for IndexArray {
    fn from(builder: IndexArrayBuilder) -> Self {
        builder.finish()
    }
}

/// A smart ordered array of indices, which tries to use space as little as
/// possible.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct IndexArray {
    /// Indices that fit 8 bits.
    as_u8: Box<[u8]>,
    /// Indices that fit 16 bits.
    as_u16: Box<[u16]>,
    /// Indices that fit 32 bits.
    as_u32: Box<[u32]>,
    /// Indices that fit 64 bits.
    as_u64: Box<[u64]>,
}

impl IndexArray {
    /// Length of this array.
    pub fn len(&self) -> usize {
        self.as_u8.len()
            + self.as_u16.len()
            + self.as_u32.len()
            + self.as_u64.len()
    }

    /// Gets an index stored in the array given this meta-index.
    ///
    /// # Panics
    /// Panics if out of bounds.
    pub fn index(&self, meta_index: usize) -> usize {
        match self.get(meta_index) {
            Some(index) => index,
            None => panic!(
                "Meta index was {}, but length is {}",
                meta_index,
                self.len()
            ),
        }
    }

    /// Gets an index stored in the array given this meta-index, returning
    /// `None` if out of bounds.
    pub fn get(&self, mut meta_index: usize) -> Option<usize> {
        if let Some(&i) = self.as_u8.get(meta_index) {
            return Some(i as usize);
        }
        meta_index -= self.as_u8.len();
        if let Some(&i) = self.as_u16.get(meta_index) {
            return Some(i as usize);
        }
        meta_index -= self.as_u16.len();
        if let Some(&i) = self.as_u32.get(meta_index) {
            return Some(i as usize);
        }
        meta_index -= self.as_u32.len();
        self.as_u64.get(meta_index).map(|&i| i as usize)
    }

    /// Performs a binary search on this index array. `Ok` means it was found,
    /// `Err` means it was not found, but we have the position where it would
    /// be.
    pub fn binary_search(&self, elem: usize) -> Result<usize, usize> {
        let mut low = 0;
        let mut high = self.len();
        let mut error = 0;
        while low < high {
            let mid = low + (high - low) / 2;
            match self.index(mid).cmp(&elem) {
                Ordering::Equal => return Ok(mid),
                Ordering::Greater => {
                    high = mid;
                    error = high
                },
                Ordering::Less => {
                    low = mid + 1;
                    error = low;
                },
            }
        }
        Err(error)
    }

    /// Iterates over the indices stored in this array.
    pub fn iter(&self) -> IndexArrayIter {
        IndexArrayIter {
            as_u8: self.as_u8.iter(),
            as_u16: self.as_u16.iter(),
            as_u32: self.as_u32.iter(),
            as_u64: self.as_u64.iter(),
        }
    }
}

impl<'array> IntoIterator for &'array IndexArray {
    type Item = usize;
    type IntoIter = IndexArrayIter<'array>;

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

/// Iterator over an array of indices. Double-ended and sized.
#[derive(Debug)]
pub struct IndexArrayIter<'array> {
    as_u8: slice::Iter<'array, u8>,
    as_u16: slice::Iter<'array, u16>,
    as_u32: slice::Iter<'array, u32>,
    as_u64: slice::Iter<'array, u64>,
}

impl<'array> Iterator for IndexArrayIter<'array> {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(&i) = self.as_u8.next() {
            return Some(i as usize);
        }
        if let Some(&i) = self.as_u16.next() {
            return Some(i as usize);
        }
        if let Some(&i) = self.as_u32.next() {
            return Some(i as usize);
        }
        self.as_u64.next().map(|&i| i as usize)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.as_u8.len()
            + self.as_u16.len()
            + self.as_u32.len()
            + self.as_u64.len();
        (len, Some(len))
    }
}

impl<'array> DoubleEndedIterator for IndexArrayIter<'array> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if let Some(&i) = self.as_u64.next() {
            return Some(i as usize);
        }
        if let Some(&i) = self.as_u32.next() {
            return Some(i as usize);
        }
        if let Some(&i) = self.as_u16.next() {
            return Some(i as usize);
        }
        self.as_u8.next().map(|&i| i as usize)
    }
}

impl<'array> ExactSizeIterator for IndexArrayIter<'array> {}

/// An index on a source code.
pub trait SourceIndex: fmt::Debug {
    /// Output of the indexing operation.
    type Output: ?Sized;

    /// Indexes the source code and returns `None` if out of bounds.
    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output>;

    /// Indexes the source code and panics if out of bounds.
    fn index<'src>(&self, src: &'src Source) -> &'src Self::Output {
        match self.get(src) {
            Some(out) => out,
            None => panic!(
                "Index {:?} is not valid when accessing source {} of length {}",
                self,
                src.name(),
                src.len()
            ),
        }
    }
}

impl SourceIndex for usize {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        (*self .. self.checked_add(1)?).get(src)
    }
}

impl SourceIndex for Range<usize> {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        let start = src.inner.segments.get(self.start)?;
        let end = src.inner.segments.get(self.end)?;
        src.contents().get(start .. end)
    }
}

impl SourceIndex for RangeTo<usize> {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        (0 .. self.end).get(src)
    }
}

impl SourceIndex for RangeFrom<usize> {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        (self.start .. src.len()).get(src)
    }
}

impl SourceIndex for RangeInclusive<usize> {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        (*self.start() .. self.end().checked_add(1)?).get(src)
    }
}

impl SourceIndex for RangeToInclusive<usize> {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        (0 .. self.end.checked_add(1)?).get(src)
    }
}

impl SourceIndex for RangeFull {
    type Output = str;

    fn get<'src>(&self, src: &'src Source) -> Option<&'src Self::Output> {
        Some(src.contents())
    }
}

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

    #[test]
    fn binary_search() {
        let mut builder = IndexArrayBuilder::default();
        builder.push(1).push(2).push(4).push(7).push(8).push(9);
        let array = builder.finish();
        assert_eq!(array.binary_search(0), Err(0));
        assert_eq!(array.binary_search(1), Ok(0));
        assert_eq!(array.binary_search(2), Ok(1));
        assert_eq!(array.binary_search(3), Err(2));
        assert_eq!(array.binary_search(4), Ok(2));
        assert_eq!(array.binary_search(5), Err(3));
        assert_eq!(array.binary_search(6), Err(3));
        assert_eq!(array.binary_search(7), Ok(3));
        assert_eq!(array.binary_search(8), Ok(4));
        assert_eq!(array.binary_search(9), Ok(5));
        assert_eq!(array.binary_search(10), Err(6));
    }
}