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

//! # Range

#![deprecated(note = "Beta")]

mod impls;
mod kind;

use {
    core::{
        fmt::{self, Display, Formatter},
        ops::RangeInclusive,
    },
    crate::Semver,
    self::kind::Kind,
};

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 protection against flood attack, max length of the string is one of:
///
///     + `255` bytes (on 8-bit machines)
///     + `4096` bytes (on larger machines)
///
/// ## Notes
///
/// Large ranges, such as `[,]`, `(,)`, `[start,]`, `[,end]`... are not supported. Technically it's doable, but using such wild ranges in
/// software development is not recommended.
///
/// ## Examples
///
/// ```
/// 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);
///
/// # dia_semver::Result::Ok(())
/// ```
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct Range {
    range: RangeInclusive<Semver>,
    kind: Kind,
}

impl Range {

    /// # Checks if this range is empty
    pub fn is_empty(&self) -> bool {
        let start = self.range.start();
        let end = self.range.end();
        match &self.kind {
            Kind::InclusiveInclusive => start > end,
            Kind::InclusiveExclusive => start >= end,
            Kind::ExclusiveExclusive => start >= end,
            Kind::ExclusiveInclusive => start >= end,
        }
    }

    /// # Checks if this range contains a semver
    pub fn contains(&self, semver: &Semver) -> bool {
        let start = self.range.start();
        let end = self.range.end();
        match &self.kind {
            Kind::InclusiveInclusive => semver >= start && semver <= end,
            Kind::InclusiveExclusive => semver >= start && semver < end,
            Kind::ExclusiveExclusive => semver > start && semver < end,
            Kind::ExclusiveInclusive => semver > start && semver <= end,
        }
    }

}

impl From<&Semver> for Range {

    fn from(semver: &Semver) -> Self {
        Self {
            range: RangeInclusive::new(semver.clone(), semver.clone()),
            kind: Kind::InclusiveInclusive,
        }
    }

}

impl From<Semver> for Range {

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

}

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

    fn from(range: core::ops::Range<Semver>) -> Self {
        Self {
            range: RangeInclusive::new(range.start, range.end),
            kind: Kind::InclusiveExclusive,
        }
    }

}

impl From<RangeInclusive<Semver>> for Range {

    fn from(range: RangeInclusive<Semver>) -> Self {
        Self {
            range,
            kind: Kind::InclusiveInclusive,
        }
    }

}

impl Display for Range {

    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        let (open, close) = match &self.kind {
            Kind::InclusiveInclusive => (INCLUSIVE_OPEN, INCLUSIVE_CLOSE),
            Kind::InclusiveExclusive => (INCLUSIVE_OPEN, EXCLUSIVE_CLOSE),
            Kind::ExclusiveExclusive => (EXCLUSIVE_OPEN, EXCLUSIVE_CLOSE),
            Kind::ExclusiveInclusive => (EXCLUSIVE_OPEN, INCLUSIVE_CLOSE),
        };

        write!(
            f,
            concat!("{open}", "{start}", ',', ' ', "{end}", "{close}"),
            open=open,
            start=self.range.start().to_short_format(),
            end=self.range.end().to_short_format(),
            close=close,
        )
    }

}