db_dump/
versions.rs

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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! <b style="font-variant:small-caps">versions.csv</b>

use crate::crates::CrateId;
use crate::ignore::IgnoredStr;
use crate::users::UserId;
use chrono::{DateTime, Utc};
use semver::{BuildMetadata, Op, Version, VersionReq};
use serde::de::{Deserialize, Deserializer, Unexpected, Visitor};
use serde_derive::{Deserialize, Serialize};
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::BTreeMap as Map;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;

/// Primary key of **versions.csv**.
#[derive(Serialize, Deserialize, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
#[serde(transparent)]
#[cfg_attr(not(doc), repr(transparent))]
pub struct VersionId(pub u32);

/// One row of **versions.csv**.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Row {
    /// PRIMARY KEY
    pub id: VersionId,
    pub crate_id: CrateId,
    pub num: Version,
    pub updated_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
    pub downloads: u64,
    pub features: Map<String, Vec<String>>,
    pub yanked: bool,
    pub license: String,
    pub crate_size: Option<u64>,
    pub published_by: Option<UserId>,
    pub checksum: Option<[u8; 32]>,
    pub links: Option<String>,
    pub rust_version: Option<Version>,
    pub has_lib: bool,
    pub bin_names: Vec<String>,
    pub edition: Option<u16>,
}

impl<'de> Deserialize<'de> for Row {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Row {
            id: VersionId,
            crate_id: CrateId,
            #[serde(deserialize_with = "version")]
            num: Version,
            #[serde(default)]
            #[allow(dead_code)]
            num_no_build: IgnoredStr,
            #[serde(deserialize_with = "crate::datetime::de")]
            updated_at: DateTime<Utc>,
            #[serde(deserialize_with = "crate::datetime::de")]
            created_at: DateTime<Utc>,
            downloads: u64,
            #[serde(deserialize_with = "features_map")]
            features: Map<String, Vec<String>>,
            #[serde(deserialize_with = "crate::bool::de")]
            yanked: bool,
            license: String,
            crate_size: Option<u64>,
            published_by: Option<UserId>,
            #[serde(deserialize_with = "checksum", default)]
            checksum: Option<[u8; 32]>,
            #[serde(default)]
            links: Option<String>,
            #[serde(default, deserialize_with = "rust_version")]
            rust_version: Option<Version>,
            #[serde(default, deserialize_with = "has_lib")]
            has_lib: bool,
            #[serde(default, deserialize_with = "bin_names")]
            bin_names: Vec<String>,
            edition: Option<u16>,
        }

        let Row {
            id,
            crate_id,
            num,
            num_no_build: _,
            updated_at,
            created_at,
            downloads,
            features,
            yanked,
            license,
            crate_size,
            published_by,
            checksum,
            links,
            rust_version,
            has_lib,
            bin_names,
            edition,
        } = Row::deserialize(deserializer)?;
        Ok(Self {
            id,
            crate_id,
            num,
            updated_at,
            created_at,
            downloads,
            features,
            yanked,
            license,
            crate_size,
            published_by,
            checksum,
            links,
            rust_version,
            has_lib,
            bin_names,
            edition,
        })
    }
}

impl Ord for Row {
    fn cmp(&self, other: &Self) -> Ordering {
        VersionId::cmp(&self.id, &other.id)
    }
}

impl PartialOrd for Row {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for Row {}

impl PartialEq for Row {
    fn eq(&self, other: &Self) -> bool {
        VersionId::eq(&self.id, &other.id)
    }
}

impl Hash for Row {
    fn hash<H: Hasher>(&self, state: &mut H) {
        VersionId::hash(&self.id, state);
    }
}

impl Borrow<VersionId> for Row {
    fn borrow(&self) -> &VersionId {
        &self.id
    }
}

fn compat(string: &str) -> Option<Version> {
    let deprecated = match string {
        "0.0.1-001" => "0.0.1-1",
        "0.3.0-alpha.01" => "0.3.0-alpha.1",
        "0.4.0-alpha.00" => "0.4.0-alpha.0",
        "0.4.0-alpha.01" => "0.4.0-alpha.1",
        _ => return None,
    };
    Some(deprecated.parse().unwrap())
}

struct VersionVisitor;

impl<'de> Visitor<'de> for VersionVisitor {
    type Value = Version;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("semver version")
    }

    fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        match string.parse() {
            Ok(version) => Ok(version),
            Err(err) => {
                if let Some(version) = compat(string) {
                    Ok(version)
                } else {
                    Err(serde::de::Error::custom(format_args!(
                        "{}: {}",
                        err, string,
                    )))
                }
            }
        }
    }
}

fn version<'de, D>(deserializer: D) -> Result<Version, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_str(VersionVisitor)
}

struct FeaturesMapVisitor;

impl<'de> Visitor<'de> for FeaturesMapVisitor {
    type Value = Map<String, Vec<String>>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("features map")
    }

    fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        serde_json::from_str(string).map_err(serde::de::Error::custom)
    }
}

fn features_map<'de, D>(deserializer: D) -> Result<Map<String, Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_str(FeaturesMapVisitor)
}

struct ChecksumVisitor;

impl<'de> Visitor<'de> for ChecksumVisitor {
    type Value = Option<[u8; 32]>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("checksum as 64-character hex string")
    }

    fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        match string.len() {
            0 => Ok(None),
            64 => {
                let mut checksum = [0u8; 32];
                for i in 0..32 {
                    match u8::from_str_radix(&string[i * 2..][..2], 16) {
                        Ok(byte) => checksum[i] = byte,
                        Err(_) => return Err(E::invalid_value(Unexpected::Str(string), &self)),
                    }
                }
                Ok(Some(checksum))
            }
            _ => Err(E::invalid_value(Unexpected::Str(string), &self)),
        }
    }
}

fn checksum<'de, D>(deserializer: D) -> Result<Option<[u8; 32]>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_str(ChecksumVisitor)
}

struct RustVersionVisitor;

impl<'de> Visitor<'de> for RustVersionVisitor {
    type Value = Option<Version>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a compiler version number")
    }

    fn visit_str<E>(self, string: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        match VersionReq::from_str(string) {
            Ok(mut req) if req.comparators.len() == 1 => {
                let req = req.comparators.pop().unwrap();
                if req.op == Op::Caret {
                    Ok(Some(Version {
                        major: req.major,
                        minor: req.minor.unwrap_or(0),
                        patch: req.patch.unwrap_or(0),
                        pre: req.pre,
                        build: BuildMetadata::EMPTY,
                    }))
                } else {
                    Ok(None)
                }
            }
            Ok(_) => Ok(None),
            Err(parse_error) => Err(E::custom(parse_error)),
        }
    }

    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(self)
    }

    fn visit_none<E>(self) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(None)
    }
}

fn rust_version<'de, D>(deserializer: D) -> Result<Option<Version>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_option(RustVersionVisitor)
}

#[derive(Deserialize)]
#[serde(transparent)]
struct HasLib(#[serde(deserialize_with = "crate::bool::de")] bool);

fn has_lib<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: Deserializer<'de>,
{
    match Deserialize::deserialize(deserializer)? {
        Some(HasLib(has_lib)) => Ok(has_lib),
        None => Ok(false),
    }
}

fn bin_names<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    crate::set::optional(deserializer, "binary names set")
}