Skip to main content

c/
strverscmp.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// strverscmp() - ported from musl/src/string/strverscmp.c
5// Included from libc/src/lib.rs in the "String/memory functions" section.
6
7/// Compare two version strings using natural ordering.
8///
9/// # Safety
10///
11/// `a` and `b` must point to valid NUL-terminated strings.
12#[no_mangle]
13pub unsafe extern "C" fn strverscmp(a: *const c_char, b: *const c_char) -> c_int {
14    let l = a as *const u8;
15    let r = b as *const u8;
16    let mut i: usize = 0;
17    let mut dp: usize = 0;
18    let mut z: c_int = 1;
19
20    // Find maximal matching prefix and track its maximal digit
21    // suffix and whether those digits are all zeros.
22    while *l.add(i) == *r.add(i) {
23        let c = *l.add(i) as c_int;
24        if c == 0 {
25            return 0;
26        }
27        if isdigit(c) == 0 {
28            dp = i + 1;
29            z = 1;
30        } else if c != b'0' as c_int {
31            z = 0;
32        }
33        i += 1;
34    }
35
36    if (*l.add(dp)).wrapping_sub(b'1') < 9 && (*r.add(dp)).wrapping_sub(b'1') < 9 {
37        // Non-degenerate digit sequences starting with nonzero digits:
38        // longest digit string is greater.
39        let mut j = i;
40        while isdigit(*l.add(j) as c_int) != 0 {
41            if isdigit(*r.add(j) as c_int) == 0 {
42                return 1;
43            }
44            j += 1;
45        }
46        if isdigit(*r.add(j) as c_int) != 0 {
47            return -1;
48        }
49    } else if z != 0
50        && dp < i
51        && (isdigit(*l.add(i) as c_int) != 0 || isdigit(*r.add(i) as c_int) != 0)
52    {
53        // Common prefix of digit sequence is all zeros:
54        // digits order less than non-digits.
55        return (*l.add(i)).wrapping_sub(b'0') as c_int
56            - (*r.add(i)).wrapping_sub(b'0') as c_int;
57    }
58
59    *l.add(i) as c_int - *r.add(i) as c_int
60}