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
// Copyright 2017 The UNIC Project Developers.
//
// See the COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::{char, cmp};

#[cfg(feature = "std")]
use std::collections::Bound;

use self::cmp::Ordering;
use CharIter;

/// A range of unicode code points.
///
/// The most idiomatic way to construct this range is through the use of the `chars!` macro:
///
/// ```
/// #[macro_use] extern crate unic_char_range;
/// use unic_char_range::CharRange;
///
/// # fn main() {
/// assert_eq!(chars!('a'..='z'), CharRange::closed('a', 'z'));
/// assert_eq!(chars!('a'..'z'), CharRange::open_right('a', 'z'));
/// assert_eq!(chars!(..), CharRange::all());
/// # }
/// ```
///
/// If constructed in reverse order, such that `self.high` is ordered before `self.low`,
/// the range is empty. If you want to iterate in decreasing order, use `.iter().rev()`.
/// All empty ranges are considered equal no matter the internal state.
#[derive(Copy, Clone, Debug, Eq)]
pub struct CharRange {
    /// The lowest character in this range (inclusive).
    pub low: char,

    /// The highest character in this range (inclusive).
    pub high: char,
}

/// Constructors
impl CharRange {
    /// Construct a closed range of characters.
    ///
    /// If `stop` is ordered before `start`, the resulting range will be empty.
    ///
    /// # Example
    ///
    /// ```
    /// # use unic_char_range::*;
    /// assert_eq!(
    ///     CharRange::closed('a', 'd').iter().collect::<Vec<_>>(),
    ///     vec!['a', 'b', 'c', 'd']
    /// )
    /// ```
    pub fn closed(start: char, stop: char) -> CharRange {
        CharRange {
            low: start,
            high: stop,
        }
    }

    /// Construct a half open (right) range of characters.
    ///
    /// # Example
    ///
    /// ```
    /// # use unic_char_range::*;
    /// assert_eq!(
    ///     CharRange::open_right('a', 'd').iter().collect::<Vec<_>>(),
    ///     vec!['a', 'b', 'c']
    /// )
    /// ```
    pub fn open_right(start: char, stop: char) -> CharRange {
        let mut iter = CharRange::closed(start, stop).iter();
        let _ = iter.next_back();
        iter.into()
    }

    /// Construct a half open (left) range of characters.
    ///
    /// # Example
    ///
    /// ```
    /// # use unic_char_range::*;
    /// assert_eq!(
    ///     CharRange::open_left('a', 'd').iter().collect::<Vec<_>>(),
    ///     vec!['b', 'c', 'd']
    /// )
    /// ```
    pub fn open_left(start: char, stop: char) -> CharRange {
        let mut iter = CharRange::closed(start, stop).iter();
        let _ = iter.next();
        iter.into()
    }

    /// Construct a fully open range of characters.
    ///
    /// # Example
    ///
    /// ```
    /// # use unic_char_range::*;
    /// assert_eq!(
    ///     CharRange::open('a', 'd').iter().collect::<Vec<_>>(),
    ///     vec!['b', 'c']
    /// )
    /// ```
    pub fn open(start: char, stop: char) -> CharRange {
        let mut iter = CharRange::closed(start, stop).iter();
        let _ = iter.next();
        let _ = iter.next_back();
        iter.into()
    }

    #[cfg(feature = "std")]
    /// Construct a range of characters from bounds.
    pub fn bound(start: Bound<char>, stop: Bound<char>) -> CharRange {
        let start = if start == Bound::Unbounded {
            Bound::Included('\0')
        } else {
            start
        };
        let stop = if stop == Bound::Unbounded {
            Bound::Included(char::MAX)
        } else {
            stop
        };
        match (start, stop) {
            (Bound::Included(start), Bound::Included(stop)) => CharRange::closed(start, stop),
            (Bound::Excluded(start), Bound::Excluded(stop)) => CharRange::open(start, stop),
            (Bound::Included(start), Bound::Excluded(stop)) => CharRange::open_right(start, stop),
            (Bound::Excluded(start), Bound::Included(stop)) => CharRange::open_left(start, stop),
            (Bound::Unbounded, _) | (_, Bound::Unbounded) => unreachable!(),
        }
    }

    /// Construct a range over all characters.
    pub fn all() -> CharRange {
        CharRange::closed('\0', char::MAX)
    }
}

/// Collection-like fn
impl CharRange {
    /// Does this range include a character?
    ///
    /// # Examples
    ///
    /// ```
    /// # use unic_char_range::CharRange;
    /// assert!(   CharRange::closed('a', 'g').contains('d'));
    /// assert!( ! CharRange::closed('a', 'g').contains('z'));
    ///
    /// assert!( ! CharRange:: open ('a', 'a').contains('a'));
    /// assert!( ! CharRange::closed('z', 'a').contains('g'));
    /// ```
    pub fn contains(&self, ch: char) -> bool {
        self.low <= ch && ch <= self.high
    }

    /// Determine the ordering of this range and a character.
    ///
    /// # Panics
    ///
    /// Panics if the range is empty. This fn may be adjusted in the future to not panic
    /// in optimized builds. Even if so, an empty range will never compare as `Ordering::Equal`.
    // TODO: Rename `cmp()` to not collid with `std::cmp::Ord::cmp`
    #[cfg_attr(feature = "clippy", allow(should_implement_trait))]
    pub fn cmp(&self, ch: char) -> Ordering {
        // possible optimization: only assert this in debug builds
        assert!(!self.is_empty(), "Cannot compare empty range's ordering");
        if self.high < ch {
            Ordering::Less
        } else if self.low > ch {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    }

    /// How many characters are in this range?
    pub fn len(&self) -> usize {
        self.iter().len()
    }

    /// Is this range empty?
    pub fn is_empty(&self) -> bool {
        self.low > self.high
    }

    /// Create an iterator over this range.
    pub fn iter(&self) -> CharIter {
        (*self).into()
    }
}

impl IntoIterator for CharRange {
    type Item = char;
    type IntoIter = CharIter;

    fn into_iter(self) -> CharIter {
        self.iter()
    }
}

impl PartialEq<CharRange> for CharRange {
    fn eq(&self, other: &CharRange) -> bool {
        (self.is_empty() && other.is_empty()) || (self.low == other.low && self.high == other.high)
    }
}