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

//! # `FromStr`

use {
    core::{
        ops::RangeInclusive,
        str::FromStr,
    },
    crate::{
        Error,
        Range,
        Semver,
        range::Kind,
    },
};

/// # Mark size in bytes
const MARK_SIZE: usize = 1;

#[derive(Debug)]
enum OpenMark {
    Inclusive,
    Exclusive,
}

#[derive(Debug)]
enum CloseMark {
    Inclusive,
    Exclusive,
}

#[test]
fn test_mark() {
    for c in &[
        crate::range::INCLUSIVE_OPEN,
        crate::range::INCLUSIVE_CLOSE,
        crate::range::EXCLUSIVE_OPEN,
        crate::range::EXCLUSIVE_CLOSE,
    ] {
        assert_eq!(c.len_utf8(), MARK_SIZE);
    }
}

impl FromStr for Range {

    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        #[cfg(target_pointer_width = "8")]
        const MAX_LEN: usize = 255;

        #[cfg(not(target_pointer_width = "8"))]
        const MAX_LEN: usize = 4096;

        if s.len() > MAX_LEN {
            return Err(err!("String is too long, max length supported: {} bytes", MAX_LEN));
        }

        let err = || err!("Invalid range: {:?}", s);

        let open_mark = match s.chars().next() {
            Some(crate::range::INCLUSIVE_OPEN) => OpenMark::Inclusive,
            Some(crate::range::EXCLUSIVE_OPEN) => OpenMark::Exclusive,
            _ => return Err(err()),
        };
        let close_mark = if s.ends_with(crate::range::INCLUSIVE_CLOSE) {
            CloseMark::Inclusive
        } else if s.ends_with(crate::range::EXCLUSIVE_CLOSE) {
            CloseMark::Exclusive
        } else {
            return Err(err());
        };

        let mut parts = s[MARK_SIZE .. s.len() - MARK_SIZE].trim().split(',');
        match (parts.next().map(|from| Semver::from_str(from)), parts.next().map(|to| Semver::from_str(to)), parts.next()) {
            (Some(Ok(from)), Some(Ok(to)), None) => Ok(Self {
                range: RangeInclusive::new(from, to),
                kind: match (open_mark, close_mark) {
                    (OpenMark::Inclusive, CloseMark::Inclusive) => Kind::InclusiveInclusive,
                    (OpenMark::Inclusive, CloseMark::Exclusive) => Kind::InclusiveExclusive,
                    (OpenMark::Exclusive, CloseMark::Exclusive) => Kind::ExclusiveExclusive,
                    (OpenMark::Exclusive, CloseMark::Inclusive) => Kind::ExclusiveInclusive,
                },
            }),
            _ => Err(err()),
        }
    }

}