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
//! A namespace looks like `abc::def::ghi`.
//!
//! Namespaces are more subtle than one would naively assume. For namespaces to be genuinely
//! extensible, they cannot know anything beyond their scope. This means that they don't have an
//! absolute index. They can be positioned relative to another namespace only by a 'sliding'
//! match. This matching can potentially be ambiguous, so if multiple matches occur an error is
//! returned. Namespaces can never be empty.

use std::cmp::Ordering;
use std::fmt;
use std::ops::Index;

// Separator
// The separator length is fixed at 2.

const SEP1: char = ':';
const SEP2: char = ':';

#[derive(Debug, PartialEq)]
pub enum NSErr {
    Parse(String, usize),
    NoMatch,
    NoRemainder,
    MultipleMatch,
    Remove,
    OutOfBounds,
}

impl fmt::Display for NSErr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            NSErr::Parse(s, pos)   => write!(f, "Could not parse \"{}\" at position {}.", s, pos),
            NSErr::NoMatch         => write!(f, "No match."),
            NSErr::MultipleMatch   => write!(f, "Multiple matches."),
            NSErr::Remove          => write!(f, "Removed too many segments."),
            NSErr::NoRemainder     => write!(f, "No remainder."),
            NSErr::OutOfBounds     => write!(f, "Index out of bounds."),
        }
    }
}


// Parser state.
enum PS {
    SegmentStart,
    Segment,
    Separator,
}

// To work with a Namespace we can use an iterator of of `Slice`s into `s`.
// These are generated by the `Iterator`'s `next()` function.
//
/// `Namespace` cannot be empty. It always contains at least one segment.
///
#[derive(Clone, Hash)]
pub struct Namespace {
    // Contains the string passed in by new() with separators removed.
    pub s:          String,

    // Contains usize pointers into the Vec representation of s.
    pub segments:   Vec<usize>,
}

impl Namespace {

    /// ```
    /// let ns = Namespace::new("a::b::c").unwrap();
    /// ```
    ///
    pub fn new(s: &str) -> Result<Self, NSErr> {
        let mut parser_state            = PS::SegmentStart;
        let mut leftpos                 = 0usize;
        let mut segments: Vec<usize>    = Vec::new();

        for (pos, ch) in s.char_indices() {
            match (&parser_state, ch) {

                (_, '\n') => {
                    return Err(NSErr::Parse(s.to_string(), pos))
                },

                (PS::SegmentStart, SEP1) => {
                    return Err(NSErr::Parse(s.to_string(), pos))
                },

                // Required if SEP2 != SEP1
                //
                // (PS::SegmentStart, SEP2) => {
                //     return Err(NSErr::Parse(s.to_string(), pos))
                // },

                (PS::SegmentStart, ch) => {
                    if ch.is_whitespace() {
                        return Err(NSErr::Parse(s.to_string(), pos));
                    } else {
                        leftpos = pos;
                        parser_state = PS::Segment;
                    }
                },

                // First ':' in separator.
                (PS::Segment, SEP1) => {
                    parser_state = PS::Separator;
                },

                (PS::Segment, _) => {},

                // Second ':' in separator.
                (PS::Separator, SEP2) => {
                    segments.push(leftpos);
                    leftpos = pos + 1;
                    parser_state = PS::SegmentStart;
                },

                (PS::Separator, _) => {
                    return Err(NSErr::Parse(s.to_string(), pos))
                },
            }
        }
        // Save last segment.
        match parser_state {
            PS::Segment => { segments.push(leftpos) },
            _           => { return Err(NSErr::Parse(s.to_string(), s.len())) },
        };
        Ok(Namespace {
            s:          s.to_string(),
            segments:   segments,
        })
    }


    /// Returns the number of segments.
    ///
    pub fn len(&self) -> usize {
        self.segments.len()
    }

    /// Appends a new namespace to the end of `Self`. For example,
    ///
    /// ```
    /// let ns1 = Namespace::new("a::b").unwrap();
    /// let ns2 = Namespace::new("b::c").unwrap();
    /// let ns = ns1.append(&ns2);
    ///
    /// assert!(ns, "a::b::b::c");
    /// ```
    pub fn append(&self, other: &Namespace) -> Namespace {

        // Append strings.
        let mut s = self.s.clone();
        s.push(SEP1);
        s.push(SEP2);
        s.push_str(&other.s);

        let mut segs = self.segments.clone();
        for n in other.segments.clone().iter() {
            segs.push(n + self.s.len() + 2)
        }

        Namespace {
            s:          s,
            segments:   segs,
        }
    }

    /// Appends a new namespace at index. Returns an error if the `n > self.len()`.
    ///
    /// ```rust
    /// let ns1 = Namespace::new("a::b::c").unwrap();
    /// let ns2 = Namespace::new("d").unwrap();
    /// assert_eq!(ns1.append_at(&ns2, 1), "a::d");
    /// ```
    pub fn append_at(&self, other: &Namespace, n: usize) -> Result<Namespace, NSErr> {
        if n > self.len() {
            Err(NSErr::OutOfBounds)
        } else if n == 0 {
            Ok(other.clone())
        } else {
            Ok(self.truncate(n).unwrap().append(other))
        }
    }

    /// Remove `n` segments from the right-hand side of `Self`. Namespaces cannot be empty so
    /// returns an error if all segments are removed.
    ///
    /// ```rust
    /// assert_eq!(
    ///     Namespace::new("a::b::c").unwrap()
    ///         .remove(2)
    ///         .unwrap()
    ///         .to_string(),
    ///     "a"
    /// );
    /// ```
    ///
    pub fn remove(&self, n: usize) -> Result<Namespace, NSErr> {
        if n == 0 {
            // No-op.
            Ok(self.clone())
        } else if n < self.len() {
            let segs = self.len() - 1 - n;
            Ok(Namespace {
                s:          self.s[0..(self.segments[segs + 1] - 2)].to_string(),
                segments:   self.segments[0..=segs].to_vec(),
            })
        } else {
            Err(NSErr::Remove)
        }
    }

    /// Truncate the namespace to the first `n` segments. In other words truncate to length `n`.
    /// Returns an error if `n > self.len()`.
    ///
    pub fn truncate(&self, n: usize) -> Result<Namespace, NSErr> {
        let out = self.clone();
        if n == 0 || n > self.len() {
            Err(NSErr::OutOfBounds)
        } else {
            out.remove(self.len() - n)
        }
    }

    /// Tries to find a sliding match. Returns the index of the position in self aligned to the
    /// first segment of other. Note that this value can be negative. If there are no matches
    /// returns an empty `Vec`.
    ///
    /// ```rust
    /// let ns1 = Namespace::new("a::b::c").unwrap();
    /// let ns2 = Namespace::new("c::d").unwrap();
    /// assert_eq!(
    ///     ns1.sliding_match(&ns),
    ///     vec!(2)
    /// );
    /// ```
    ///
    pub fn sliding_match(&self, other: &Namespace) -> Vec<isize> {
        let slen = self.len() as isize;
        let olen = other.len() as isize;

        let mut v: Vec<isize> = Vec::with_capacity(slen.max(olen) as usize);
    
        for offset in (0 - olen + 1)..slen {
            if self.offset_match(other, offset) { v.push(offset) }
        };
        v
    }

    /// The offset is the index of the position in self aligned to the first segment of other.
    /// Returns true if all aligned segments match.
    ///
    pub fn offset_match(&self, other: &Namespace, offset: isize) -> bool {
        //        ls       rs
        //        v        v
        // self  [        ]
        // other     [         ]
        //            ^         ^
        //            lo        ro
        let ls = 0;
        let rs = self.len() as isize;
        let lo = offset;
        let ro = other.len() as isize + offset;

        for i in ls.max(lo)..rs.min(ro) {
            if self[i as usize] != other[(i - offset) as usize] { return false }
        };
        true
    }

    #[test]
    fn test_sliding_match() {
        let ns = Namespace::new("a::b::c").unwrap();

        let other = Namespace::new("c::b::a").unwrap();
        assert_eq!(
            ns.sliding_match(&other)[1],
            2
        );
    
        let other = Namespace::new("a").unwrap();
        assert_eq!(
            ns.sliding_match(&other)[0],
            0
        );
    
        let other = Namespace::new("a::b::c").unwrap();
        assert_eq!(
            ns.sliding_match(&other)[0],
            0
        );
    
        let other = Namespace::new("x::y").unwrap();
        assert!(
            ns.sliding_match(&other).is_empty()
        );
    }

    /// Returns the remainder of `other`. If there is no match, multiple matches or no remainder,
    /// returns an error.
    ///
    /// ```rust
    /// let ns1 = Namespace::new("a::b::c").unwrap();
    /// let ns2 = Namespace::new("c::d::e").unwrap();
    /// assert_eq!(
    ///     ns.remainder(&ns2).unwrap().to_string(),
    ///     "d::e"
    /// );
    /// ```
    pub fn remainder(&self, other: &Namespace) -> Result<Namespace, NSErr> {
         let offset = check_unique(&self.sliding_match(&other))?;

         // The only valid condition is:
         //
         //                offset
         //                |         other.len()
         //                v         |
         // self:    [         ]     v
         // other:        [         ]
         //                     ^
         //                     |
         //                     rem_ix
         //
         if offset + other.len() as isize > self.len() as isize {
            let rem_ix = self.len() - offset as usize;
            Ok(
                Namespace {
                    s:          String::from(&other.s[other.segments[rem_ix]..]),
                    segments:   other.segments[rem_ix..].to_vec(),
                }
            )
         } else {
             Err(NSErr::NoRemainder)
         }
    }

    /// If there is a unique sliding_match, returns `self` appended with the the remainder of
    /// `other`, otherwise returns an error.
    ///
    /// ```rust
    /// let ns = Namespace::new("a::b").unwrap();
    /// let other = Namespace::new("b::c").unwrap();
    /// ns.sliding_join(&other);
    /// assert_eq!(
    ///     ns.sliding_join(&other).unwrap().to_string(),
    ///     "a::b::c",
    /// );
    /// ```
    ///
    pub fn sliding_join(&self, other: &Namespace) -> Result<Namespace, NSErr> {
         let ns = self.clone();
         Ok(ns.append(&self.remainder(other)?))
    }

    pub fn iter(&self) -> NamespaceIter {
        NamespaceIter {
            ns:     &self,
            index:  0usize,
        }
    }
}

impl Index<usize> for Namespace {
    type Output = str;

    fn index(&self, n: usize) -> &Self::Output {
        match n.cmp(&(self.segments.len() - 1)) {
            Ordering::Less      => &self.s[self.segments[n]..self.segments[n + 1] - 2],
            Ordering::Equal     => &self.s[self.segments[n]..],               
            Ordering::Greater   => panic!("Index on Namespace out of bounds."),
        }
    }
}

#[test]
fn test_index_1() {
    let ns = Namespace::new("a::bc::d").unwrap();
    assert_eq!(
        ns[0],
        "a"
    );
}

pub struct NamespaceIter<'a> {
    ns:     &'a Namespace,
    index:  usize,
}

// Think implement a whole lot of functions<&Segment> for Namespace.

impl<'a> Iterator for NamespaceIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let i = self.index;
        self.index += 1;

        if i < self.ns.len() {
            Some(&self.ns[i])
        } else {
            None
        }
    }
}

impl fmt::Display for Namespace {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.s)
    }
}

impl fmt::Debug for Namespace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

// If namespaces are not the same length returns false
impl PartialEq for Namespace {
    fn eq(&self, other: &Namespace) -> bool {
        self.s == other.s
    }
}

impl Eq for Namespace {}

// Supplement to slide_match() which checks that there is only one match, otherwise returns an
// error.
fn check_unique(v: &Vec<isize>) -> Result<isize, NSErr> {
    match v.len() {
        0 => Err(NSErr::NoMatch),
        1 => Ok(v[0]),
        _ => Err(NSErr::MultipleMatch),
    }
}