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
//! Types representing the version number of a library.

use core_extensions::{SelfOps, StringExt};

use std::{
    error,
    fmt::{self, Display},
    num::ParseIntError,
};

use crate::std_types::RStr;

/// The `<major>.<minor>.<patch>` version of a library,
///
/// # Post 1.0 major version
///
/// Major versions are mutually incompatible for both users and implementors.
///
/// Minor allow users to have a version less than or equal to that of the implementor,
/// and disallows implementors from making changes that would break
/// any previous minor release (with the same major number).
///
/// Patch cannot change the api/abi of the library at all,fixes only.
///
/// # Pre 1.0 version
///
/// Minor versions are mutually incompatible for both users and implementors.
///
/// Patch cannot change the api/abi of the library at all,fixes only.
///
/// # Example
///
/// ```
/// use abi_stable::sabi_types::VersionStrings;
///
/// let v1_0_0 = VersionStrings::new("1.0.0").parsed().unwrap();
/// let v1_0_5 = VersionStrings::new("1.0.5").parsed().unwrap();
/// let v1_1_0 = VersionStrings::new("1.1.0").parsed().unwrap();
/// let v2_0_0 = VersionStrings::new("1.0.5").parsed().unwrap();
///
/// assert!(v1_0_0.is_compatible(v1_0_5), "'{}' '{}'", v1_0_0, v1_0_5);
/// assert!(v1_0_5.is_compatible(v1_1_0), "'{}' '{}'", v1_0_5, v1_1_0);
/// assert!(!v1_1_0.is_compatible(v2_0_0), "'{}' '{}'", v1_1_0, v2_0_0);
///
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[repr(transparent)]
pub struct VersionStrings {
    /// The `major.minor.patch` version string
    pub version: RStr<'static>,
}

/// The parsed (`<major>.<minor>.<patch>`) version number of a library.
///
/// # Post 1.0 major version
///
/// Major versions are mutually incompatible for both users and implementors.
///
/// Minor allow users to have a version less than or equal to that of the implementor,
/// and disallows implementors from making changes that would break
/// any previous minor release (with the same major number).
///
/// Patch cannot change the api/abi of the library at all,fixes only.
///
/// # Example
///
/// ```
/// use abi_stable::sabi_types::VersionNumber;
///
/// let v0_1_0 = VersionNumber {
///     major: 0,
///     minor: 1,
///     patch: 0,
/// };
/// let v0_1_5 = VersionNumber {
///     major: 0,
///     minor: 1,
///     patch: 5,
/// };
/// let v0_1_8 = VersionNumber {
///     major: 0,
///     minor: 1,
///     patch: 8,
/// };
/// let v0_2_0 = VersionNumber {
///     major: 0,
///     minor: 2,
///     patch: 0,
/// };
///
/// assert!(v0_1_0.is_compatible(v0_1_5), "'{}' '{}'", v0_1_0, v0_1_5);
/// assert!(v0_1_5.is_compatible(v0_1_8), "'{}' '{}'", v0_1_5, v0_1_8);
/// assert!(!v0_1_8.is_compatible(v0_2_0), "'{}' '{}'", v0_1_8, v0_2_0);
///
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)]
#[repr(C)]
pub struct VersionNumber {
    ///
    pub major: u32,
    ///
    pub minor: u32,
    ///
    pub patch: u32,
}

impl VersionStrings {
    /// Constructs a VersionStrings from a string with the
    /// "major.minor.patch" format,where each one is a valid number.
    ///
    /// This does not check whether the string is correctly formatted,
    /// that check is done inside `VersionStrings::parsed`.
    ///
    /// # Example
    ///
    /// ```
    /// use abi_stable::sabi_types::VersionStrings;
    ///
    /// static VERSION: VersionStrings = VersionStrings::new("0.1.2");
    ///
    /// ```
    pub const fn new(version: &'static str) -> Self {
        Self {
            version: RStr::from_str(version),
        }
    }

    /// Attempts to convert a `VersionStrings` into a `VersionNumber`
    ///
    /// # Errors
    ///
    /// This returns a `ParseVersionError` if the string is not correctly formatted.
    ///
    /// # Example
    ///
    /// ```
    /// use abi_stable::sabi_types::{VersionNumber, VersionStrings};
    ///
    /// static VERSION: VersionStrings = VersionStrings::new("0.1.2");
    ///
    /// assert_eq!(
    ///     VERSION.parsed(),
    ///     Ok(VersionNumber {
    ///         major: 0,
    ///         minor: 1,
    ///         patch: 2
    ///     })
    /// );
    ///
    /// let err_version = VersionStrings::new("0.a.2.b");
    /// assert!(err_version.parsed().is_err());
    ///
    /// ```
    pub fn parsed(self) -> Result<VersionNumber, ParseVersionError> {
        VersionNumber::new(self)
    }
}

impl VersionNumber {
    /// Attempts to convert a `VersionStrings` into a `VersionNumber`
    ///
    /// # Errors
    ///
    /// This returns a `ParseVersionError` if the string is not correctly formatted.
    ///
    /// # Example
    ///
    /// ```
    /// use abi_stable::sabi_types::{VersionNumber, VersionStrings};
    ///
    /// static VERSION: VersionStrings = VersionStrings::new("10.5.20");
    ///
    /// assert_eq!(
    ///     VersionNumber::new(VERSION),
    ///     Ok(VersionNumber {
    ///         major: 10,
    ///         minor: 5,
    ///         patch: 20
    ///     })
    /// );
    ///
    /// let err_version = VersionStrings::new("not a version number");
    /// assert!(VersionNumber::new(err_version).is_err());
    ///
    /// ```
    pub fn new(vn: VersionStrings) -> Result<Self, ParseVersionError> {
        let mut iter = vn.version.splitn(3, '.');

        VersionNumber {
            major: iter
                .next()
                .unwrap_or("")
                .parse()
                .map_err(|x| ParseVersionError::new(vn, "major", x))?,
            minor: iter
                .next()
                .unwrap_or("")
                .parse()
                .map_err(|x| ParseVersionError::new(vn, "minor", x))?,
            patch: iter
                .next()
                .unwrap_or("")
                .split_while(|x| ('0'..='9').contains(&x))
                .find(|x| x.key)
                .map_or("0", |x| x.str)
                .parse()
                .map_err(|x| ParseVersionError::new(vn, "patch", x))?,
        }
        .piped(Ok)
    }

    /// Whether the `self` version number is compatible with the
    /// `library_implementor` version number.
    ///
    /// This uses modified semver rules where:
    ///
    /// - For 0.y.z ,y is interpreted as a major version,
    ///     z is interpreted as the minor version,
    ///
    /// - For x.y.z ,x>=1,y is interpreted as a minor version.
    ///
    /// - Libraries are compatible so long as they are the same
    ///     major version with a minor_version >=`self`.
    ///
    /// # Example
    ///
    /// ```
    /// use abi_stable::sabi_types::VersionNumber;
    ///
    /// let v0_1_0 = VersionNumber {
    ///     major: 0,
    ///     minor: 1,
    ///     patch: 0,
    /// };
    /// let v0_1_5 = VersionNumber {
    ///     major: 0,
    ///     minor: 1,
    ///     patch: 5,
    /// };
    /// let v0_1_8 = VersionNumber {
    ///     major: 0,
    ///     minor: 1,
    ///     patch: 8,
    /// };
    /// let v0_2_0 = VersionNumber {
    ///     major: 0,
    ///     minor: 2,
    ///     patch: 0,
    /// };
    ///
    /// assert!(v0_1_0.is_compatible(v0_1_5), "'{}' '{}'", v0_1_0, v0_1_5);
    /// assert!(v0_1_5.is_compatible(v0_1_8), "'{}' '{}'", v0_1_5, v0_1_8);
    /// assert!(!v0_1_8.is_compatible(v0_2_0), "'{}' '{}'", v0_1_8, v0_2_0);
    ///
    /// ```
    pub const fn is_compatible(self, library_implementor: VersionNumber) -> bool {
        if self.major == 0 && library_implementor.major == 0 {
            self.minor == library_implementor.minor && self.patch <= library_implementor.patch
        } else {
            self.major == library_implementor.major && self.minor <= library_implementor.minor
        }
    }
    /// Whether the `self` version number is compatible with the
    /// library version number.
    ///
    /// This uses the same semver rules as cargo:
    ///
    /// - For 0.y.z ,y is interpreted as a major version,
    ///     z is interpreted as the minor version,
    ///
    /// - For x.y.z ,x>=1,y is interpreted as a minor version.
    ///
    /// - Libraries are compatible so long as they are the same
    ///     major version irrespective of their minor version.
    ///
    /// # Example
    ///
    /// ```
    /// use abi_stable::sabi_types::VersionNumber;
    ///
    /// let v0_1_0 = VersionNumber {
    ///     major: 0,
    ///     minor: 1,
    ///     patch: 0,
    /// };
    /// let v0_1_5 = VersionNumber {
    ///     major: 0,
    ///     minor: 1,
    ///     patch: 5,
    /// };
    /// let v0_1_8 = VersionNumber {
    ///     major: 0,
    ///     minor: 1,
    ///     patch: 8,
    /// };
    /// let v0_2_0 = VersionNumber {
    ///     major: 0,
    ///     minor: 2,
    ///     patch: 0,
    /// };
    /// let v0_2_8 = VersionNumber {
    ///     major: 0,
    ///     minor: 2,
    ///     patch: 8,
    /// };
    /// let v1_0_0 = VersionNumber {
    ///     major: 1,
    ///     minor: 0,
    ///     patch: 0,
    /// };
    /// let v1_5_0 = VersionNumber {
    ///     major: 1,
    ///     minor: 5,
    ///     patch: 0,
    /// };
    /// let v2_0_0 = VersionNumber {
    ///     major: 2,
    ///     minor: 0,
    ///     patch: 0,
    /// };
    ///
    /// fn is_compat_assert(l: VersionNumber, r: VersionNumber, are_they_compat: bool) {
    ///     assert_eq!(l.is_loosely_compatible(r), are_they_compat);
    ///     assert_eq!(r.is_loosely_compatible(l), are_they_compat);
    /// }
    ///
    /// is_compat_assert(v0_1_0, v0_1_5, true);
    /// is_compat_assert(v0_1_5, v0_1_8, true);
    /// is_compat_assert(v1_0_0, v1_5_0, true);
    /// is_compat_assert(v0_1_8, v0_2_0, false);
    /// is_compat_assert(v0_2_8, v1_0_0, false);
    /// is_compat_assert(v2_0_0, v1_0_0, false);
    /// is_compat_assert(v2_0_0, v1_5_0, false);
    ///
    /// ```
    pub const fn is_loosely_compatible(self, library_implementor: VersionNumber) -> bool {
        if self.major == 0 && library_implementor.major == 0 {
            self.minor == library_implementor.minor
        } else {
            self.major == library_implementor.major
        }
    }
}

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

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

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/// Instantiates a [`VersionStrings`] with the
/// major.minor.patch version of the library where it is invoked.
///
/// [`VersionStrings`]: ./sabi_types/version/struct.VersionStrings.html
#[macro_export]
macro_rules! package_version_strings {
    () => {{
        $crate::sabi_types::VersionStrings::new(env!("CARGO_PKG_VERSION"))
    }};
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/// When the `VersionStrings` could not be converted into a `VersionNumber`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseVersionError {
    version_strings: VersionStrings,
    which_field: &'static str,
    parse_error: ParseIntError,
}

impl ParseVersionError {
    const fn new(
        version_strings: VersionStrings,
        which_field: &'static str,
        parse_error: ParseIntError,
    ) -> Self {
        Self {
            version_strings,
            which_field,
            parse_error,
        }
    }

    /// Gets back the `VersionStrings` that could not be parsed into a `VersionNumber`.
    pub const fn version_strings(&self) -> VersionStrings {
        self.version_strings
    }
}

impl Display for ParseVersionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "\nInvalid version string:'{}'\nerror at the {} field:{}",
            self.version_strings, self.which_field, self.parse_error,
        )
    }
}

impl error::Error for ParseVersionError {}