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
use anyhow::Result;
#[cfg(feature = "proptest")]
use proptest::{strategy::Strategy, string::string_regex};
use semver::Version;
use serde::{
    de::Deserializer,
    ser::{SerializeSeq, Serializer},
    Deserialize, Serialize,
};
use std::{borrow::Borrow, collections::BTreeMap, ops::Deref, str::FromStr, sync::Arc};
#[cfg(feature = "proptest")]
use test_strategy::Arbitrary;
use thiserror::Error;

/// CrateName as allowed for Rust package names.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "proptest", derive(Arbitrary))]
#[serde(try_from = "String")]
pub struct CrateName(
    #[cfg_attr(feature = "proptest", strategy(string_regex("[a-zA-Z_-]+").unwrap().prop_map(|p| p.into())))]
     Arc<str>,
);

/// Error validating an identifier.
#[derive(Error, Debug)]
pub enum CrateNameError {
    #[error("identifier cannot be empty")]
    Empty,
    #[error("identifier too long ({length} bytes)")]
    TooLong { length: usize },
    #[error("identifier contains illegal character {character:?} at {index}")]
    InvalidCharacter { character: char, index: usize },
}

impl CrateName {
    /// Creates a new [`CrateName`] from a string-like value.
    ///
    /// This tries to apply the same rules as <https://crates.io> does to identifiers,
    /// which are listed
    /// [here](https://doc.rust-lang.org/cargo/reference/registry-index.html#name-restrictions).
    ///
    /// - Cannot be empty
    /// - Cannot be longer than 64 bytes
    /// - Can only contain alphanumeric characters, dashes and hyphens
    pub fn new<S: Into<Arc<str>>>(name: S) -> Result<Self, CrateNameError> {
        let name = name.into();

        if name.len() == 0 {
            return Err(CrateNameError::Empty);
        }

        if name.len() > 64 {
            return Err(CrateNameError::TooLong { length: name.len() });
        }

        for (index, character) in name.chars().enumerate() {
            match character {
                // numbers are allowed
                '0'..='9' => continue,
                // alphabetic characters are allowed
                'a'..='z' | 'A'..='Z' => continue,
                // for symbols, only dashes and underscores allowed
                '-' | '_' => continue,
                _ => return Err(CrateNameError::InvalidCharacter { index, character }),
            }
        }

        Ok(Self(name))
    }
}

impl std::fmt::Display for CrateName {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(fmt)
    }
}

impl Borrow<str> for CrateName {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl TryFrom<String> for CrateName {
    type Error = CrateNameError;
    fn try_from(input: String) -> Result<Self, Self::Error> {
        Self::new(input)
    }
}

impl Deref for CrateName {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl FromStr for CrateName {
    type Err = CrateNameError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::new(input)
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "proptest", derive(Arbitrary))]
pub struct CrateVersion {
    pub krate: CrateName,
    #[cfg_attr(feature = "proptest", strategy(crate::proptest::version()))]
    pub version: Version,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "proptest", derive(Arbitrary))]
pub struct CrateMetadata {
    pub name: CrateName,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
//#[cfg_attr(feature = "proptest", derive(Arbitrary))]
pub struct CrateInfo {
    pub metadata: CrateMetadata,
    //#[strategy(crate::proptest::version())]
    pub versions: BTreeMap<Version, VersionInfo>,
}

#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "proptest", derive(Arbitrary))]
pub struct Checksum(#[serde(with = "hex")] [u8; 32]);

impl Checksum {
    pub fn sha2_256(bytes: &[u8]) -> Self {
        use sha2::Digest;
        let mut hasher = sha2::Sha256::new();
        hasher.update(bytes);
        Self(hasher.finalize().into())
    }
}

#[derive(Error, Debug)]
pub enum ChecksumParseError {
    #[error(transparent)]
    HexDecode(#[from] hex::FromHexError),
    #[error("length mismatch, data was {0:} bytes")]
    LengthMismatch(usize),
}

impl FromStr for Checksum {
    type Err = ChecksumParseError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let result = hex::decode(input)?;
        Ok(Self(result.try_into().map_err(|e: Vec<u8>| {
            ChecksumParseError::LengthMismatch(e.len())
        })?))
    }
}

impl std::fmt::Debug for Checksum {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "Checksum(\"{}\")", hex::encode(self.0))
    }
}

impl std::fmt::Display for Checksum {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{}", hex::encode(self.0))
    }
}

impl From<[u8; 32]> for Checksum {
    fn from(raw: [u8; 32]) -> Self {
        Self(raw)
    }
}

impl From<&[u8; 32]> for Checksum {
    fn from(raw: &[u8; 32]) -> Self {
        Self(*raw)
    }
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "proptest", derive(Arbitrary))]
pub struct VersionInfo {
    #[serde(rename = "crate")]
    pub krate: CrateName,
    #[cfg_attr(feature = "proptest", strategy(crate::proptest::version()))]
    pub version: Version,
    pub yanked: bool,
    pub checksum: Checksum,
}

#[cfg(all(test, feature = "proptest"))]
mod proptests {
    #[allow(unused)]
    use super::CrateName;
    use test_strategy::proptest;

    #[proptest]
    fn identifier(identifier: CrateName) {
        CrateName::new(identifier.0).unwrap();
    }
}