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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Lenient parser for Semantic Version numbers.
#![deny(
    bad_style,
    const_err,
    dead_code,
    improper_ctypes,
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    no_mangle_generic_items,
    non_shorthand_field_patterns,
    overflowing_literals,
    path_statements,
    patterns_in_fns_without_body,
    private_in_public,
    rust_2018_idioms,
    trivial_casts,
    trivial_numeric_casts,
    unconditional_recursion,
    unsafe_code,
    unused_allocation,
    unused_comparisons,
    unused_extern_crates,
    unused_import_braces,
    unused_parens,
    unused_qualifications,
    unused_results,
    unused,
    while_true
)]

/// Trait to abstract over version building.
///
/// The methods to implement in this trait represent the components of [`semver::Version`],
/// but allow for parsing into a custom type.
///
/// The trait is generic over the lifetime of the input string, so that one could
/// parse into a version without having to allocate.
///
/// Most methods have a default implementation that does nothing and ignores the input.
/// This can be used to implement some form of validation without needing to keep the result.
pub trait VersionBuilder<'input> {
    /// The return type of the final version.
    type Out;

    /// Construct a new version builder.
    ///
    /// The function must not fail and the version (if returned from [`VersionBuilder::build`] at this point)
    /// should represent something akin to "0.0.0"
    fn new() -> Self;

    /// Set the major version component.
    ///
    /// This method is the only required component and will be called
    /// before [`VersionBuilder::build`].
    #[allow(unused)]
    fn set_major(&mut self, major: u64) {}

    /// Set the minor version component.
    ///
    /// This component is optional and might not be called
    /// before [`VersionBuilder::build`].
    #[allow(unused)]
    fn set_minor(&mut self, minor: u64) {}

    /// Set the patch version component.
    ///
    /// This component is optional and might not be called
    /// before [`VersionBuilder::build`].
    #[allow(unused)]
    fn set_patch(&mut self, patch: u64) {}

    /// Add additional numeric components following patch and preceding pre-release.
    ///
    /// For a version like `1.2.3.4.5`, this would call add_additional with `4` and `5`.
    ///
    /// For strict semver versions, those values are invalid.
    /// For lenient semver, those values are better represented as build than pre-release,
    /// although they might be "in the same block" as pre-release.
    /// In terms of comparing versions, the values added here should still have an impact.
    ///
    /// This component is optional and might not be called
    /// before [`VersionBuilder::build`].
    #[allow(unused)]
    fn add_additional(&mut self, num: u64) {}

    /// The pre-release metadata.
    ///
    /// The string might represent any alpha-numeric identifier,
    /// including numbers with or without leading zeroes.
    /// It is up to the implementor to parse those into more specific
    /// identifiers, if required.
    ///
    /// This component is optional and might not be called
    /// before [`VersionBuilder::build`].
    ///
    /// This method might be called multiple times,
    /// although the default implementation produces only one identifier.
    #[allow(unused)]
    fn add_pre_release(&mut self, pre_release: &'input str) {}

    /// The build identifier.
    ///
    /// The string might represent any alpha-numeric identifier,
    /// including numbers with or without leading zeroes.
    /// It is up to the implementor to parse those into more specific
    /// identifiers, if required.
    ///
    /// This component is optional and might not be called
    /// before [`VersionBuilder::build`].
    ///
    /// This method might be called multiple times,
    /// although the default implementation produces only one identifier.
    #[allow(unused)]
    fn add_build(&mut self, build: &'input str) {}

    /// Construct the final version.
    fn build(self) -> Self::Out;
}

#[cfg(feature = "semver")]
impl<'input> VersionBuilder<'input> for semver::Version {
    type Out = Self;

    fn new() -> Self {
        semver::Version::new(0, 0, 0)
    }

    fn set_major(&mut self, major: u64) {
        self.major = major;
    }

    fn set_minor(&mut self, minor: u64) {
        self.minor = minor;
    }

    fn set_patch(&mut self, patch: u64) {
        self.patch = patch;
    }

    fn add_additional(&mut self, num: u64) {
        if self.build.is_empty() {
            self.build = semver::BuildMetadata::new(&format!("{}", num)).unwrap();
        } else {
            let build = self.build.as_str();
            let build = format!("{}.{}", build, num);
            self.build = semver::BuildMetadata::new(&build).unwrap();
        }
    }

    fn add_pre_release(&mut self, pre_release: &'input str) {
        self.pre = semver::Prerelease::new(&sanitize_pre_release(pre_release)).unwrap();
    }

    fn add_build(&mut self, build: &'input str) {
        let build = if self.build.is_empty() {
            semver::BuildMetadata::new(&sanitize_build(build))
        } else {
            let build = format!("{}.{}", self.build, build);
            semver::BuildMetadata::new(&sanitize_build(build))
        };
        self.build = build.unwrap();
    }

    fn build(self) -> Self::Out {
        self
    }
}

#[cfg(any(test, feature = "semver011"))]
impl<'input> VersionBuilder<'input> for semver011::Version {
    type Out = Self;

    fn new() -> Self {
        semver011::Version::new(0, 0, 0)
    }

    fn set_major(&mut self, major: u64) {
        self.major = major;
    }

    fn set_minor(&mut self, minor: u64) {
        self.minor = minor;
    }

    fn set_patch(&mut self, patch: u64) {
        self.patch = patch;
    }

    fn add_additional(&mut self, num: u64) {
        self.build.push(semver011::Identifier::Numeric(num))
    }

    fn add_pre_release(&mut self, pre_release: &'input str) {
        self.pre.extend(split_pre_release_011(pre_release));
    }

    fn add_build(&mut self, build: &'input str) {
        self.build.extend(split_build_011(build));
    }

    fn build(self) -> Self::Out {
        self
    }
}

#[cfg(feature = "semver010")]
impl<'input> VersionBuilder<'input> for semver010::Version {
    type Out = Self;

    fn new() -> Self {
        semver010::Version::new(0, 0, 0)
    }

    fn set_major(&mut self, major: u64) {
        self.major = major;
    }

    fn set_minor(&mut self, minor: u64) {
        self.minor = minor;
    }

    fn set_patch(&mut self, patch: u64) {
        self.patch = patch;
    }

    fn add_additional(&mut self, num: u64) {
        self.build.push(semver010::Identifier::Numeric(num))
    }

    fn add_pre_release(&mut self, pre_release: &'input str) {
        self.pre.extend(split_pre_release_010(pre_release));
    }

    fn add_build(&mut self, build: &'input str) {
        self.build.extend(split_build_010(build));
    }

    fn build(self) -> Self::Out {
        self
    }
}

/// Sanitizes an input to be a valid pre-release identifier for [`semver::Version`].
///
/// This includes:
///   - Replacing every non-supported character with `-`
///   - Removing trailing zeroes from all-numeric identifier segments
///   - Collapsing empty segments
#[cfg(feature = "semver")]
pub fn sanitize_pre_release<'s>(
    s: impl Into<std::borrow::Cow<'s, str>>,
) -> std::borrow::Cow<'s, str> {
    remove_empty_segments(remove_leading_zeroes(remove_illegal_characters(s)))
}

/// Sanitizes an input to be a valid build identifier for [`semver::Version`].
///
/// This includes:
///   - Replacing every non-supported character with `-`
///   - Collapsing empty segments
#[cfg(feature = "semver")]
pub fn sanitize_build<'s>(s: impl Into<std::borrow::Cow<'s, str>>) -> std::borrow::Cow<'s, str> {
    remove_empty_segments(remove_illegal_characters(s))
}

/// Splits a single input into valid pre-release identifiers for [`semver011::Version`].
#[cfg(feature = "semver011")]
#[inline]
pub fn split_pre_release_011(s: &str) -> impl Iterator<Item = semver011::Identifier> + '_ {
    s.split(['.', '-'].as_ref()).map(try_num_semver011)
}

/// Splits a single input into valid pre-release identifiers for [`semver010::Version`].
#[cfg(feature = "semver010")]
#[inline]
pub fn split_pre_release_010(s: &str) -> impl Iterator<Item = semver010::Identifier> + '_ {
    s.split(['.', '-'].as_ref()).map(try_num_semver010)
}

/// Splits a single input into valid build identifiers for [`semver011::Version`].
#[cfg(feature = "semver011")]
#[inline]
pub fn split_build_011(s: &str) -> impl Iterator<Item = semver011::Identifier> + '_ {
    s.split(['.', '-', '+'].as_ref()).map(try_num_semver011)
}

/// Splits a single input into valid build identifiers for [`semver010::Version`].
#[cfg(feature = "semver010")]
#[inline]
pub fn split_build_010(s: &str) -> impl Iterator<Item = semver010::Identifier> + '_ {
    s.split(['.', '-', '+'].as_ref()).map(try_num_semver010)
}

#[cfg(feature = "semver")]
fn remove_illegal_characters<'s>(
    s: impl Into<std::borrow::Cow<'s, str>>,
) -> std::borrow::Cow<'s, str> {
    fn illegal_char(c: char) -> bool {
        !matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '.')
    }
    let s = s.into();
    if s.contains(illegal_char) {
        s.replace(illegal_char, "-").into()
    } else {
        s
    }
}

#[cfg(feature = "semver")]
fn remove_leading_zeroes<'s>(s: impl Into<std::borrow::Cow<'s, str>>) -> std::borrow::Cow<'s, str> {
    fn illegal_zero(s: &str) -> bool {
        s.len() > 1 && s.starts_with('0') && s.bytes().all(|b| b.is_ascii_digit())
    }
    let mut s = s.into();
    if s.split('.').any(illegal_zero) {
        let st: &mut String = s.to_mut();
        let mut start = 0;
        while start < st.len() {
            let mut end = match st[start..].find('.') {
                Some(end) => end + start,
                None => st.len(),
            };

            if illegal_zero(&st[start..end]) {
                match st[start..end].find(|c| c > '0') {
                    Some(leading_zeroes) => {
                        let _ = st.drain(start..start + leading_zeroes);
                        end -= leading_zeroes;
                    }
                    None => {
                        st.replace_range(start..end, "0");
                        end = start + 1;
                    }
                }
            }
            start = end + 1;
        }
    }

    s
}

#[cfg(feature = "semver")]
fn remove_empty_segments<'s>(s: impl Into<std::borrow::Cow<'s, str>>) -> std::borrow::Cow<'s, str> {
    let mut s = s.into();

    if !s.is_empty() && s.split('.').any(str::is_empty) {
        let start = match s.find(|c| c != '.') {
            Some(start) => start,
            None => {
                s.to_mut().clear();
                return s;
            }
        };
        let mut end = match s.rfind(|c| c != '.') {
            Some(end) => end + 1,
            None => {
                s.to_mut().clear();
                return s;
            }
        };

        let st: &mut String = s.to_mut();
        if start > 0 {
            let _ = st.drain(..start);
            end -= start;
        }
        if end < st.len() {
            let _ = st.drain(end..);
        }

        let mut pos = 0;
        while pos < st.len() {
            let next = match st[pos..].find('.') {
                Some(next) => next + pos,
                None => st.len(),
            };

            if next == pos {
                let _ = st.remove(pos);
            } else {
                pos = next + 1;
            }
        }
    }

    s
}

#[cfg(any(test, feature = "semver011"))]
fn try_num_semver011(s: &str) -> semver011::Identifier {
    try_num(s).map_err(String::from).map_or_else(
        semver011::Identifier::AlphaNumeric,
        semver011::Identifier::Numeric,
    )
}

#[cfg(feature = "semver010")]
fn try_num_semver010(s: &str) -> semver010::Identifier {
    try_num(s).map_err(String::from).map_or_else(
        semver010::Identifier::AlphaNumeric,
        semver010::Identifier::Numeric,
    )
}

#[cfg(any(test, feature = "semver011", feature = "semver010"))]
fn try_num(s: &str) -> Result<u64, &str> {
    match s.parse::<u64>() {
        Ok(num) if !s.starts_with('0') || s == "0" => Ok(num),
        _ => Err(s),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sanitize_pre_release() {
        assert_eq!(
            "a-b.0.1010.-001",
            &sanitize_pre_release("a+b.000..01010...?001..")
        );
    }

    #[test]
    fn test_sanitize_build() {
        assert_eq!(
            "a-b.000.01010.-001",
            &sanitize_build("a+b.000..01010...?001..")
        );
    }

    #[test]
    fn test_remove_illegal_characters() {
        assert_eq!("a-b", &remove_illegal_characters("a+b"));
        assert_eq!("a-b", &remove_illegal_characters("a?b"));
        assert_eq!("a-b", &remove_illegal_characters("a*b"));
        assert_eq!("a-b", &remove_illegal_characters("a!b"));
        assert_eq!("a-b", &remove_illegal_characters("a🙈b"));
    }

    #[test]
    fn test_remove_leading_zeroes() {
        assert_eq!("0", &remove_leading_zeroes("0"));
        assert_eq!("0", &remove_leading_zeroes("000000000"));
        assert_eq!("1", &remove_leading_zeroes("1"));
        assert_eq!("1", &remove_leading_zeroes("01"));
        assert_eq!("1", &remove_leading_zeroes("0001"));
        assert_eq!("101", &remove_leading_zeroes("101"));
        assert_eq!("101", &remove_leading_zeroes("0101"));
        assert_eq!("101", &remove_leading_zeroes("000101"));
        assert_eq!("0a", &remove_leading_zeroes("0a"));
        assert_eq!("00a", &remove_leading_zeroes("00a"));
        assert_eq!("0.0.0", &remove_leading_zeroes("0.0.0"));
        assert_eq!("0.0.0", &remove_leading_zeroes("0.0000.0"));
        assert_eq!("0.11.0", &remove_leading_zeroes("0.0011.0"));
        assert_eq!("0.11.101", &remove_leading_zeroes("0.0011.0101"));
    }

    #[test]
    fn test_remove_empty_segments() {
        assert_eq!("123", &remove_empty_segments("123"));
        assert_eq!("123", &remove_empty_segments(".123"));
        assert_eq!("123", &remove_empty_segments("..123"));
        assert_eq!("123", &remove_empty_segments("....123"));
        assert_eq!("abc.123", &remove_empty_segments("abc.123"));
        assert_eq!("abc.123", &remove_empty_segments("abc..123"));
        assert_eq!("abc.123", &remove_empty_segments("abc...123"));
        assert_eq!("abc.123", &remove_empty_segments("abc.....123"));
        assert_eq!("123", &remove_empty_segments("123."));
        assert_eq!("123", &remove_empty_segments("123.."));
        assert_eq!("123", &remove_empty_segments("123...."));
        assert_eq!("abc.123", &remove_empty_segments("abc.123."));
        assert_eq!("abc.123", &remove_empty_segments("abc.123.."));
        assert_eq!("abc.123", &remove_empty_segments("abc.123...."));
        assert_eq!("", &remove_empty_segments("."));
        assert_eq!("", &remove_empty_segments(".."));
        assert_eq!("", &remove_empty_segments("...."));
    }
}