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
// License: see LICENSE file at root directory of main branch

//! # Range

mod impls;

use {
    alloc::borrow::Cow,
    core::{
        fmt::{self, Display, Formatter},
        ops::{Bound, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
    },
    crate::Semver,
};

const INCLUSIVE_OPEN: char = '[';
const INCLUSIVE_CLOSE: char = ']';
const EXCLUSIVE_OPEN: char = '(';
const EXCLUSIVE_CLOSE: char = ')';

/// # Range
///
/// A range can be respresented in string, following these rules:
///
/// - Start and end are placed inside one of `[]`, `[)`..., separated by a comma.
/// - `[` and `]` are inclusive.
/// - `(` and `)` are exclusive.
/// - White spaces can be included. They will be ignored by parser.
/// - For unbounded ranges, start and/or end indexes must be inclusive.
///
/// - For protection against flood attack, max length of the string is one of:
///
///     + `255` bytes (on 8-bit machines)
///     + `4096` bytes (on larger machines)
///
/// ## Examples
///
/// ```
/// use core::ops::RangeBounds;
/// use core::str::FromStr;
/// use dia_semver::{Range, Semver};
///
/// // An empty range
/// let range = Range::from(Semver::new(0, 1, 2)..Semver::new(0, 0, 0));
/// assert!(range.is_empty());
///
/// // Only one single semver
/// let range = Range::from(Semver::new(0, 1, 2));
/// assert!(range.contains(&Semver::new(0, 1, 2)));
/// assert!(range.contains(&Semver::new(0, 1, 3)) == false);
///
/// // Inclusive range
/// let range = Range::from_str("[0.1.2, 0.2.0-beta]")?;
/// assert!(range.contains(&Semver::new(0, 1, 3)));
/// assert!(range.contains(&Semver::from_str("0.2.0-alpha")?));
/// assert!(range.contains(&Semver::new(0, 2, 0)) == false);
///
/// // Exclusive range
/// let range = Range::from(Semver::new(0, 1, 2)..Semver::new(0, 2, 0));
/// assert!(range.contains(&Semver::new(0, 2, 0)) == false);
///
/// // Unbounded ranges
/// assert!(Range::from(..).contains(&Semver::new(1, 2, 0)));
/// assert!(Range::from_str("[ , 1]")?.contains(&Semver::from(1_u8)));
/// assert!(Range::from_str("[ , 1)")?.contains(&Semver::from(1_u8)) == false);
///
/// # dia_semver::Result::Ok(())
/// ```
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct Range {
    start: Bound<Semver>,
    end: Bound<Semver>,
}

impl Range {

    /// # Checks if this range is empty
    pub fn is_empty(&self) -> bool {
        match (&self.start, &self.end) {
            (Bound::Included(start), Bound::Included(end)) => start > end,
            (Bound::Included(start), Bound::Excluded(end)) => start >= end,
            (Bound::Included(_), Bound::Unbounded) => false,

            (Bound::Excluded(start), Bound::Included(end)) => start >= end,
            (Bound::Excluded(start), Bound::Excluded(end)) => start >= end,
            (Bound::Excluded(_), Bound::Unbounded) => false,

            (Bound::Unbounded, _) => false,
        }
    }

}

impl From<&Semver> for Range {

    fn from(semver: &Semver) -> Self {
        Self::from(semver.clone())
    }

}

impl From<Semver> for Range {

    fn from(semver: Semver) -> Self {
        Self {
            start: Bound::Included(semver.clone()),
            end: Bound::Included(semver),
        }
    }

}

impl From<core::ops::Range<Semver>> for Range {

    fn from(range: core::ops::Range<Semver>) -> Self {
        Self {
            start: Bound::Included(range.start),
            end: Bound::Excluded(range.end),
        }
    }

}

impl From<RangeInclusive<Semver>> for Range {

    fn from(range: RangeInclusive<Semver>) -> Self {
        let (start, end) = range.into_inner();
        Self {
            start: Bound::Included(start),
            end: Bound::Included(end),
        }
    }

}

impl From<RangeFrom<Semver>> for Range {

    fn from(range: RangeFrom<Semver>) -> Self {
        Self {
            start: Bound::Included(range.start),
            end: Bound::Unbounded,
        }
    }

}

impl From<RangeTo<Semver>> for Range {

    fn from(range: RangeTo<Semver>) -> Self {
        Self {
            start: Bound::Unbounded,
            end: Bound::Excluded(range.end),
        }
    }

}

impl From<RangeToInclusive<Semver>> for Range {

    fn from(range: RangeToInclusive<Semver>) -> Self {
        Self {
            start: Bound::Unbounded,
            end: Bound::Included(range.end),
        }
    }

}

impl From<RangeFull> for Range {

    fn from(_: RangeFull) -> Self {
        Self {
            start: Bound::Unbounded,
            end: Bound::Unbounded,
        }
    }

}

impl Display for Range {

    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        let (open, start) = match &self.start {
            Bound::Included(start) => (INCLUSIVE_OPEN, Cow::Owned(start.to_short_format())),
            Bound::Excluded(start) => (EXCLUSIVE_OPEN, Cow::Owned(start.to_short_format())),
            Bound::Unbounded => (INCLUSIVE_OPEN, Cow::Borrowed(concat!())),
        };
        let (close, end) = match &self.end {
            Bound::Included(end) => (INCLUSIVE_CLOSE, Cow::Owned(end.to_short_format())),
            Bound::Excluded(end) => (EXCLUSIVE_CLOSE, Cow::Owned(end.to_short_format())),
            Bound::Unbounded => (INCLUSIVE_CLOSE, Cow::Borrowed(concat!())),
        };
        write!(
            f,
            concat!("{open}", "{start}", ',', ' ', "{end}", "{close}"),
            open=open, start=start, end=end, close=close,
        )
    }

}

impl RangeBounds<Semver> for Range {

    fn start_bound(&self) -> Bound<&Semver> {
        // TODO: use Bound::as_ref() when it is stabilized
        match &self.start {
            Bound::Included(start) => Bound::Included(start),
            Bound::Excluded(start) => Bound::Excluded(start),
            Bound::Unbounded => Bound::Unbounded,
        }
    }

    fn end_bound(&self) -> Bound<&Semver> {
        // TODO: use Bound::as_ref() when it is stabilized
        match &self.end {
            Bound::Included(end) => Bound::Included(end),
            Bound::Excluded(end) => Bound::Excluded(end),
            Bound::Unbounded => Bound::Unbounded,
        }
    }

}