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
// Copyright 2018 Gerrit Viljoen

// This file is part of prange.
//
// prange is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// prange is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with prange.  If not, see <http://www.gnu.org/licenses/>.

//! Parse numeric ranges for indexing.
//!
//! Inclusive-inclusive 1-based integer ranges. Parsed from strings.
//!
//! # Examples
//!
//! ```ignore
//! "2"         => [2]
//! "1-5"       => [1, 2, 3, 4, 5]
//! "1-3,5-6"   => [1, 2, 3, 5, 6]
//! "-3"        => [1, 2, 3]
//! "1-"        => [1, 2, 3, ..]
//! "1-3,2-4,7" => [1, 2, 3, 2, 3, 4, 7]
//! ```

#[cfg(test)]
mod test;

use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
use std::ops::Range;
use std::str::FromStr;

pub fn parse<T>(x: &T) -> Result<RangeIter, ParseError>
where T: AsRef<str> {
    if x.as_ref().is_empty() {
        return Ok(RangeIter{ranges: Vec::new()})
    }
    let x2 = x.as_ref().to_string() + ",";
    let mut res = Vec::new();
    let mut tok1 = String::new();
    let mut tok2 = String::new();
    let mut first = true;
    for (i, x) in x2.chars().enumerate() {
        match x {
            ',' => {
                if tok1.is_empty() && tok2.is_empty() {
                    if first {
                        return Err(ParseError::EmptyRange(i))
                    } else {
                        return Err(ParseError::InvalidRange(i))
                    }
                }
                let num1 = if tok1.is_empty() {
                    1
                } else {
                    match u64::from_str(&tok1) {
                        Ok(x) => x,
                        Err(x) => return Err(ParseError::Integer(i, x))
                    }
                };
                let num2 = if first {
                    num1 + 1
                } else if tok2.is_empty() {
                    u64::max_value()
                } else {
                    match u64::from_str(&tok2) {
                        Ok(x) => x + 1,
                        Err(x) => return Err(ParseError::Integer(i, x))
                    }
                };
                res.push(Range{start: num1, end: num2});
                tok1.clear();
                tok2.clear();
                first = true;
            },
            '-' => {
                if first {
                    first = false
                } else {
                    return Err(ParseError::InvalidRange(i))
                }
            },
            '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => {
                if first {
                    tok1.push(x)
                } else {
                    tok2.push(x)
                }
            },
            x => return Err(ParseError::IllegalChar(i, x))
        }
    }
    res.reverse();
    Ok(RangeIter{ranges: res})
}

#[derive(Debug)]
pub struct RangeIter {
    ranges: Vec<Range<u64>>
}

impl Iterator for RangeIter {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        if self.ranges.is_empty() {
            None
        } else {
            let x = self.ranges.last_mut().unwrap().next();
            if x.is_none() {
                self.ranges.pop();
                self.next()
            } else {
                x
            }
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    IllegalChar(usize, char),
    EmptyRange(usize),
    InvalidRange(usize),
    Integer(usize, ParseIntError)
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

impl Error for ParseError {
    fn description(&self) -> &str {
        use self::ParseError::*;
        match *self {
            IllegalChar(..) => "input contains invalid characters",
            EmptyRange(..) => "input contains an empty range",
            InvalidRange(..) => "input contains an invalid range",
            Integer(_, ref x) => x.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        use self::ParseError::*;
        match *self {
            IllegalChar(..) => None,
            EmptyRange(..) => None,
            InvalidRange(..) => None,
            Integer(_, ref x) => Some(x),
        }
    }
}