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
#[cfg(feature = "serde")]
extern crate serde;

use std::{fmt, iter, ops};

/// An offset into text.
/// Offset is represented as `u32` storing number of utf8-bytes,
/// but most of the clients should treat it like opaque measure.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct TextUnit(u32);

impl TextUnit {
    //TODO: rename to `from_char`: this is not ocaml!
    /// `TextUnit` equal to the length of this char.
    #[inline(always)]
    pub fn of_char(c: char) -> TextUnit {
        TextUnit(c.len_utf8() as u32)
    }

    /// `TextUnit` equal to the length of this string.
    ///
    /// # Panics
    /// Panics if the length of the string is greater than `u32::max_value()`
    #[inline(always)]
    pub fn of_str(s: &str) -> TextUnit {
        if s.len() > u32::max_value() as usize {
            panic!("string is to long")
        }
        TextUnit(s.len() as u32)
    }

    #[inline(always)]
    pub fn checked_sub(self, other: TextUnit) -> Option<TextUnit> {
        self.0.checked_sub(other.0).map(TextUnit)
    }

    #[inline(always)]
    pub fn from_usize(size: usize) -> TextUnit {
        #[cfg(debug_assertions)]
        {
            if size > u32::max_value() as usize {
                panic!("overflow when converting to TextUnit: {}", size)
            }
        }
        (size as u32).into()
    }

    #[inline(always)]
    pub fn to_usize(self) -> usize {
        u32::from(self) as usize
    }
}

impl fmt::Debug for TextUnit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <Self as fmt::Display>::fmt(self, f)
    }
}

impl fmt::Display for TextUnit {
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<TextUnit> for u32 {
    #[inline(always)]
    fn from(tu: TextUnit) -> u32 {
        tu.0
    }
}

impl From<u32> for TextUnit {
    #[inline(always)]
    fn from(tu: u32) -> TextUnit {
        TextUnit(tu)
    }
}

macro_rules! unit_ops_impls {
    ($T:ident, $f:ident, $op:tt, $AT:ident, $af:ident) => {

impl ops::$T<TextUnit> for TextUnit {
    type Output = TextUnit;
    #[inline(always)]
    fn $f(self, rhs: TextUnit) -> TextUnit {
        TextUnit(self.0 $op rhs.0)
    }
}

impl<'a> ops::$T<&'a TextUnit> for TextUnit {
    type Output = TextUnit;
    #[inline(always)]
    fn $f(self, rhs: &'a TextUnit) -> TextUnit {
        ops::$T::$f(self, *rhs)
    }
}

impl<'a> ops::$T<TextUnit> for &'a TextUnit {
    type Output = TextUnit;
    #[inline(always)]
    fn $f(self, rhs: TextUnit) -> TextUnit {
        ops::$T::$f(*self, rhs)
    }
}

impl<'a, 'b> ops::$T<&'a TextUnit> for &'b TextUnit {
    type Output = TextUnit;
    #[inline(always)]
    fn $f(self, rhs: &'a TextUnit) -> TextUnit {
        ops::$T::$f(*self, *rhs)
    }
}

impl ops::$AT<TextUnit> for TextUnit {
    #[inline(always)]
    fn $af(&mut self, rhs: TextUnit) {
        self.0 = self.0 $op rhs.0
    }
}

impl<'a> ops::$AT<&'a TextUnit> for TextUnit {
    #[inline(always)]
    fn $af(&mut self, rhs: &'a TextUnit) {
        ops::$AT::$af(self, *rhs)
    }
}
    };
}

macro_rules! range_ops_impls {
    ($T:ident, $f:ident, $op:tt, $AT:ident, $af:ident) => {

impl ops::$T<TextUnit> for TextRange {
    type Output = TextRange;
    #[inline(always)]
    fn $f(self, rhs: TextUnit) -> TextRange {
        TextRange::from_to(
            self.start() $op rhs,
            self.end() $op rhs,
        )
    }
}

impl<'a> ops::$T<&'a TextUnit> for TextRange {
    type Output = TextRange;
    #[inline(always)]
    fn $f(self, rhs: &'a TextUnit) -> TextRange {
        TextRange::from_to(
            self.start() $op rhs,
            self.end() $op rhs,
        )
    }
}

impl<'a> ops::$T<TextUnit> for &'a TextRange {
    type Output = TextRange;
    #[inline(always)]
    fn $f(self, rhs: TextUnit) -> TextRange {
        TextRange::from_to(
            self.start() $op rhs,
            self.end() $op rhs,
        )
    }
}

impl<'a, 'b> ops::$T<&'a TextUnit> for &'b TextRange {
    type Output = TextRange;
    #[inline(always)]
    fn $f(self, rhs: &'a TextUnit) -> TextRange {
        TextRange::from_to(
            self.start() $op rhs,
            self.end() $op rhs,
        )
    }
}

impl ops::$AT<TextUnit> for TextRange {
    #[inline(always)]
    fn $af(&mut self, rhs: TextUnit) {
        *self = *self $op rhs
    }
}

impl<'a> ops::$AT<&'a TextUnit> for TextRange {
    #[inline(always)]
    fn $af(&mut self, rhs: &'a TextUnit) {
        *self = *self $op rhs
    }
}
    };
}

unit_ops_impls!(Add, add, +, AddAssign, add_assign);
unit_ops_impls!(Sub, sub, -, SubAssign, sub_assign);
range_ops_impls!(Add, add, +, AddAssign, add_assign);
range_ops_impls!(Sub, sub, -, SubAssign, sub_assign);

impl<'a> iter::Sum<&'a TextUnit> for TextUnit {
    fn sum<I: Iterator<Item = &'a TextUnit>>(iter: I) -> TextUnit {
        iter.fold(TextUnit::from(0), ops::Add::add)
    }
}

impl iter::Sum<TextUnit> for TextUnit {
    fn sum<I: Iterator<Item = TextUnit>>(iter: I) -> TextUnit {
        iter.fold(TextUnit::from(0), ops::Add::add)
    }
}

/// A range in the text, represented as a pair of `TextUnit`s.
///
/// # Panics
/// Slicing a `&str` with `TextRange` panics if the result is
/// not a valid utf8 string.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TextRange {
    start: TextUnit,
    end: TextUnit,
}

impl fmt::Debug for TextRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        <Self as fmt::Display>::fmt(self, f)
    }
}

impl fmt::Display for TextRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}; {})", self.start(), self.end())
    }
}

impl TextRange {
    /// The left-inclusive range (`[from..to)`) between to points in the text
    #[inline(always)]
    pub fn from_to(from: TextUnit, to: TextUnit) -> TextRange {
        assert!(from <= to, "Invalid text range [{}; {})", from, to);
        TextRange {
            start: from,
            end: to,
        }
    }

    /// The left-inclusive range (`[offset..offset + len)`) between to points in the text
    #[inline(always)]
    pub fn offset_len(offset: TextUnit, len: TextUnit) -> TextRange {
        TextRange::from_to(offset, offset + len)
    }

    // TODO: pass by value
    /// The inclusive start of this range
    #[inline(always)]
    pub fn start(&self) -> TextUnit {
        self.start
    }

    /// The exclusive end of this range
    #[inline(always)]
    pub fn end(&self) -> TextUnit {
        self.end
    }

    /// The length of this range
    #[inline(always)]
    pub fn len(&self) -> TextUnit {
        self.end - self.start
    }

    /// Is this range empty of any content?
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.start() == self.end()
    }

    #[inline(always)]
    pub fn is_subrange(&self, other: &TextRange) -> bool {
        other.start() <= self.start() && self.end() <= other.end()
    }

    #[inline(always)]
    pub fn checked_sub(self, other: TextUnit) -> Option<TextRange> {
        let res = TextRange::offset_len(self.start().checked_sub(other)?, self.len());
        Some(res)
    }
}

impl ops::RangeBounds<TextUnit> for TextRange {
    fn start_bound(&self) -> ops::Bound<&TextUnit> {
        ops::Bound::Included(&self.start)
    }

    fn end_bound(&self) -> ops::Bound<&TextUnit> {
        ops::Bound::Excluded(&self.end)
    }
}

impl ops::Index<TextRange> for str {
    type Output = str;

    fn index(&self, index: TextRange) -> &str {
        &self[index.start().0 as usize..index.end().0 as usize]
    }
}

impl ops::Index<TextRange> for String {
    type Output = str;

    fn index(&self, index: TextRange) -> &str {
        &self.as_str()[index]
    }
}

#[cfg(feature = "serde")]
mod serde_impls {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use {TextRange, TextUnit};

    impl Serialize for TextUnit {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            self.0.serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for TextUnit {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let value = Deserialize::deserialize(deserializer)?;
            Ok(TextUnit(value))
        }
    }

    impl Serialize for TextRange {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            (self.start, self.end).serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for TextRange {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let (start, end) = Deserialize::deserialize(deserializer)?;
            Ok(TextRange { start, end })
        }
    }
}

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

    #[test]
    fn test_sum() {
        let xs: Vec<TextUnit> = vec![0.into(), 1.into(), 2.into()];
        assert_eq!(xs.iter().sum::<TextUnit>(), 3.into());
        assert_eq!(xs.into_iter().sum::<TextUnit>(), 3.into());
    }

    #[test]
    fn test_ops() {
        let r = TextRange::from_to(10.into(), 20.into());
        let u: TextUnit = 5.into();
        assert_eq!(r + u, TextRange::from_to(15.into(), 25.into()),);
        assert_eq!(r - u, TextRange::from_to(5.into(), 15.into()),);
    }

    #[test]
    fn test_checked_ops() {
        let x: TextUnit = 1.into();
        assert_eq!(x.checked_sub(1.into()), Some(0.into()));
        assert_eq!(x.checked_sub(2.into()), None);

        let r = TextRange::from_to(1.into(), 2.into());
        assert_eq!(
            r.checked_sub(1.into()),
            Some(TextRange::from_to(0.into(), 1.into()))
        );
        assert_eq!(x.checked_sub(2.into()), None);
    }

    #[test]
    fn test_subrange() {
        let r1 = TextRange::from_to(2.into(), 4.into());
        let r2 = TextRange::from_to(2.into(), 3.into());
        let r3 = TextRange::from_to(1.into(), 3.into());
        assert!(r2.is_subrange(&r1));
        assert!(!r3.is_subrange(&r1));
    }
}