gem_version 1.0.0

Ruby's Gem::Version comparison logic in Rust
Documentation
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
//! Implement Ruby's [`Gem::Version`](https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/lib/rubygems/version.rb)
//! comparison logic in Rust.
//!
//! See also: [Gem::Version tests](https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/test/rubygems/test_gem_version.rb)
//!
//! The main use case is for the Heroku Ruby buildpack <https://github.com/heroku/buildpacks-ruby>
//! and associated ecosystem of managing Ruby logic inside of Rust.
//!
//! ## Install
//!
//! Add it to your Cargo.toml:
//!
//! ```shell
//! $ cargo add gem_version
//! ```
//!
//! ## Use
//!
//! ```
//! use std::str::FromStr;
//! use gem_version::GemVersion;
//!
//! let version = GemVersion::from_str("1.0.0").unwrap();
//! assert!(version < GemVersion::from_str("2.0.0").unwrap());
//! ```
//!
//! ## Diverging behavior
//!
//! Ruby's [`Gem::Version`](https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/lib/rubygems/version.rb)
//! reference implementation converts `-` to `.pre.`
//! ([commit](https://github.com/ruby/rubygems/commit/df88d165d89cc7ece9b746589e58d93b76a33628)).
//! This means the value you put in is not the value you get out:
//!
//! ```ruby
//! puts Gem::Version.new("1.0.0-alpha1")
//! # => "1.0.0.pre.alpha1"
//! ```
//!
//! It seems the coupling between comparison logic and representation was accidental
//! at the time of introduction. This library diverges by showing the original string
//! (and decoupling that from the comparison representation):
//!
//! ```
//! use std::str::FromStr;
//! use gem_version::GemVersion;
//!
//! let version = GemVersion::from_str("1.0.0-alpha1").unwrap();
//!
//! // Version does not have `.pre.` in it:
//! assert_eq!("1.0.0-alpha1", &version.to_string());
//!
//! // But it performs comparisons as if it did:
//! assert_eq!(
//!     GemVersion::from_str("1.0.0.pre.alpha1").unwrap(),
//!     version
//! );
//! ```
//!
//! If you want the upstream (reference) behavior that also changes the display output,
//! you can make a newtype that uses `replace("-", ".pre.")` on the input `String`.

use std::cmp;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

/// See module docs for a usage example
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct GemVersion {
    version: String,
    segments: Vec<VersionSegment>,
}

impl fmt::Display for GemVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.version)
    }
}

fn validation_regex() -> &'static regex::Regex {
    static VALIDATION_REGEX: OnceLock<regex::Regex> = OnceLock::new();
    VALIDATION_REGEX.get_or_init(|| {
        regex::Regex::new(
            "^\\s*([0-9]+(?:\\.[0-9a-zA-Z]+)*(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?)?\\s*$",
        )
        .expect("Internal error: Bad Regex")
    })
}

fn segment_regex() -> &'static regex::Regex {
    static SEGMENT_REGEX: OnceLock<regex::Regex> = OnceLock::new();
    SEGMENT_REGEX.get_or_init(|| {
        regex::Regex::new("[0-9]+|[a-zA-Z]+").expect("Internal Error: Invalid Regular Expression!")
    })
}

impl TryFrom<String> for GemVersion {
    type Error = VersionError;

    fn try_from(version_string: String) -> Result<Self, Self::Error> {
        Self::from_str(&version_string)
    }
}

impl From<GemVersion> for String {
    fn from(version: GemVersion) -> String {
        version.to_string()
    }
}

impl FromStr for GemVersion {
    type Err = VersionError;

    fn from_str(version_string: &str) -> Result<Self, Self::Err> {
        if version_string.trim().is_empty() {
            Ok(GemVersion {
                version: String::from("0"),
                segments: vec![VersionSegment::U32(0)],
            })
        } else if validation_regex().is_match(version_string) {
            let version = version_string.trim().to_string();
            let for_segments = version.replace('-', ".pre.");

            let (segments_l, segments_r) = segment_regex()
                .find_iter(&for_segments)
                .map(|regex_match| {
                    regex_match.as_str().parse::<u32>().ok().map_or_else(
                        || VersionSegment::String(regex_match.as_str().to_string()),
                        VersionSegment::U32,
                    )
                })
                .fold(
                    (vec![], vec![]),
                    |(mut acc_segments_l, mut acc_segments_r), item| {
                        match item {
                            item @ VersionSegment::U32(_) if acc_segments_r.is_empty() => {
                                acc_segments_l.push(item);
                            }
                            _ => acc_segments_r.push(item),
                        }

                        (acc_segments_l, acc_segments_r)
                    },
                );

            let is_zero_segment = |v: &VersionSegment| *v == VersionSegment::U32(0);
            let segments_l = drop_right_while(segments_l, is_zero_segment);
            let segments_r = drop_right_while(segments_r, is_zero_segment);

            let mut segments = segments_l;
            segments.extend(segments_r);

            Ok(GemVersion { version, segments })
        } else {
            Err(VersionError::InvalidVersion(String::from(version_string)))
        }
    }
}

impl PartialEq<GemVersion> for GemVersion {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for GemVersion {}

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

impl Ord for GemVersion {
    fn cmp(&self, other: &Self) -> Ordering {
        let max = cmp::max(self.segments.len(), other.segments.len());
        let default = VersionSegment::U32(0);

        for index in 0..max {
            let segment_l = self.segments.get(index).unwrap_or(&default);
            let segment_r = other.segments.get(index).unwrap_or(&default);

            match segment_l.cmp(segment_r) {
                Ordering::Equal => {}
                ord => return ord,
            }
        }

        Ordering::Equal
    }
}

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

#[derive(Debug, Eq, PartialEq)]
pub enum VersionError {
    InvalidVersion(String),
}

impl std::error::Error for VersionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

impl fmt::Display for VersionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VersionError::InvalidVersion(version) => {
                write!(f, "Invalid version string: {version}")
            }
        }
    }
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
enum VersionSegment {
    String(String),
    U32(u32),
}

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

impl Ord for VersionSegment {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (VersionSegment::U32(a), VersionSegment::U32(b)) => a.cmp(b),
            (VersionSegment::U32(_), VersionSegment::String(_)) => Ordering::Greater,
            (VersionSegment::String(_), VersionSegment::U32(_)) => Ordering::Less,
            // We have yet to verify that the sorting rules for strings are the same between
            // Rust's and Ruby's standard library. Tests seem to pass, but here be dragons!
            (VersionSegment::String(a), VersionSegment::String(b)) => a.cmp(b),
        }
    }
}

fn drop_right_while<A>(mut v: Vec<A>, pred: impl Fn(&A) -> bool) -> Vec<A> {
    while v.last().is_some_and(&pred) {
        v.pop();
    }
    v
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    // https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/test/rubygems/test_gem_version.rb#L83-L89
    fn test_initialize() {
        for version in &["1.0", "1.0 ", " 1.0 ", "1.0\n", "\n1.0\n", "1.0"] {
            assert_eq!(v(version), v("1.0"));
        }
    }

    #[test]
    // https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/test/rubygems/test_gem_version.rb#L111-L115
    fn empty_version() {
        assert_eq!(v(""), v("0"));
        assert_eq!(v("   "), v("0"));
        assert_eq!(v(" "), v("0"));
    }

    #[test]
    // https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/test/rubygems/test_gem_version.rb#L140-L162
    fn spaceship() {
        assert_eq!(v("1.0"), v("1.0.0"));
        assert_eq!(v("1"), v("1.0.0"));

        assert!(v("1.0") > v("1.0.a"));
        assert!(v("1.8.2") > v("0.0.0"));
        assert!(v("1.8.2") > v("1.8.2.a"));
        assert!(v("1.8.2.b") > v("1.8.2.a"));
        assert!(v("1.8.2.a") < v("1.8.2"));
        assert!(v("1.8.2.a10") > v("1.8.2.a9"));
        assert_eq!(v(""), v("0"));

        assert_eq!(v("0.beta.1"), v("0.0.beta.1"));
        assert!(v("0.0.beta") < v("0.0.beta.1"));
        assert!(v("0.0.beta") < v("0.beta.1"));

        assert!(v("5.a") < v("5.0.0.rc2"));
        assert!(v("5.x") > v("5.0.0.rc2"));

        assert_eq!(v("1.9.3"), v("1.9.3"));
        assert!(v("1.9.3") > v("1.9.2.99"));
        assert!(v("1.9.3") < v("1.9.3.1"));
    }

    #[test]
    // https://github.com/rubygems/rubygems/blob/ecc8e895b69063562b9bf749b353948e051e4171/test/rubygems/test_gem_version.rb#L91-L109
    fn invalid_versions() {
        assert_eq!(
            "junk".parse::<GemVersion>(),
            Err(VersionError::InvalidVersion(String::from("junk")))
        );
        assert_eq!(
            "1.0\n2.0".parse::<GemVersion>(),
            Err(VersionError::InvalidVersion(String::from("1.0\n2.0")))
        );
        assert_eq!(
            "1..2".parse::<GemVersion>(),
            Err(VersionError::InvalidVersion(String::from("1..2")))
        );
        assert_eq!(
            "1.2\\ 3.4".parse::<GemVersion>(),
            Err(VersionError::InvalidVersion(String::from("1.2\\ 3.4")))
        );
        assert_eq!(
            "2.3422222.222.222222222.22222.ads0as.dasd0.ddd2222.2.qd3e.".parse::<GemVersion>(),
            Err(VersionError::InvalidVersion(String::from(
                "2.3422222.222.222222222.22222.ads0as.dasd0.ddd2222.2.qd3e."
            )))
        );
    }

    #[test]
    fn display_preserves_original_string() {
        assert_eq!("4.0.0.preview2", v("4.0.0.preview2").to_string());
        assert_eq!("4.0.0.preview.2", v("4.0.0.preview.2").to_string());
        assert_eq!("3.1.2", v("3.1.2").to_string());
        assert_eq!("1.0", v("1.0").to_string());
        assert_eq!("1.0.0", v("1.0.0").to_string());
        assert_eq!("0.0.beta.1", v("0.0.beta.1").to_string());
    }

    #[test]
    // https://github.com/ruby/rubygems/blob/dc7307cabf8768e39a08c68f86c149a683b327be/test/rubygems/test_gem_version.rb#L69-L73
    fn equality_with_split_prerelease_segment() {
        assert_eq!(v("1.2"), v("1.2"));
        assert_ne!(v("1.2"), v("1.3"));
        // "b1" is split into segments [b, 1] by the segment regex, same as "b.1"
        assert_eq!(v("1.2.b1"), v("1.2.b.1"));
    }

    #[test]
    // https://github.com/ruby/rubygems/blob/dc7307cabf8768e39a08c68f86c149a683b327be/test/rubygems/test_gem_version.rb#L111-L115
    fn empty_version_display() {
        assert_eq!("0", v("").to_string());
        assert_eq!("0", v("   ").to_string());
        assert_eq!("0", v(" ").to_string());
    }

    #[test]
    fn uppercase_letters_not_silently_dropped() {
        // Regression: the segment regex `[0-9]+|[a-z]+` silently drops
        // uppercase letters (e.g., "Preview2" is parsed as "review2")
        assert_ne!(v("1.0.0.Preview2"), v("1.0.0.review2"));
        assert_ne!(v("1.0.0.preview2"), v("1.0.0.Preview2"));
        assert_ne!(v("1.0P"), v("1.0p"));
        assert!(v("1.0.0.Preview2") < v("1.0.0.preview2"));
    }

    #[test]
    fn serde_roundtrip() {
        let original = v("3.1.2");
        let serialized = serde_json::to_string(&original).unwrap();
        assert_eq!(serialized, "\"3.1.2\"");

        let deserialized: GemVersion = serde_json::from_str(&serialized).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn ord_enables_sorting() {
        let mut versions = vec![v("3.0"), v("1.0"), v("2.0")];
        versions.sort();
        assert_eq!(versions, vec![v("1.0"), v("2.0"), v("3.0")]);
    }

    #[test]
    // https://github.com/ruby/rubygems/blob/dc7307cabf8768e39a08c68f86c149a683b327be/test/rubygems/test_gem_version.rb#L194-L201
    fn semver_comparison() {
        assert!(v("1.0.0-alpha") < v("1.0.0-alpha.1"));
        assert!(v("1.0.0-alpha.1") < v("1.0.0-beta.2"));
        assert!(v("1.0.0-beta.2") < v("1.0.0-beta.11"));
        assert!(v("1.0.0-beta.11") < v("1.0.0-rc.1"));
        assert!(v("1.0.0-rc1") < v("1.0.0"));
        assert!(v("1.0.0-1") < v("1"));
    }

    #[test]
    // Diverges from upstream.
    // Upstream replaces `-` with `.pre.` in the display introduced in https://github.com/ruby/rubygems/commit/df88d165d89cc7ece9b746589e58d93b76a33628
    // and still on main https://github.com/ruby/rubygems/blob/dc7307cabf8768e39a08c68f86c149a683b327be/lib/rubygems/version.rb#L219-L222.
    //
    // This preserves the comparison behavior, but changes the display behavior
    fn test_version_display() {
        for version in &["1.0.0-alpha", "1.0.0-beta.2", "1.0.0-1"] {
            let gem = v(version);
            // Does NOT change display
            assert_eq!(version, &&gem.to_string());

            // Preserves equality logic
            assert_eq!(v(&version.replace('-', ".pre.")), gem);
        }
    }

    #[test]
    fn hash_consistent_with_eq() {
        use std::collections::hash_map::DefaultHasher;
        use std::collections::HashSet;
        use std::hash::{Hash, Hasher};

        fn hash_version(v: &GemVersion) -> u64 {
            let mut hasher = DefaultHasher::new();
            v.hash(&mut hasher);
            hasher.finish()
        }

        // Equal versions must produce the same hash
        assert_eq!(hash_version(&v("1.0")), hash_version(&v("1.0.0")));

        // Different versions should (almost certainly) produce different hashes
        assert_ne!(hash_version(&v("1.0")), hash_version(&v("2.0")));

        // GemVersion works in a HashSet
        let mut set = HashSet::new();
        set.insert(v("1.0"));
        set.insert(v("1.0.0"));
        assert_eq!(set.len(), 1);
    }

    // Test helper method
    fn v(s: &str) -> GemVersion {
        s.parse().unwrap()
    }
}