3 * Original code downloaded from: http://sourcefrog.net/projects/natsort/
5 strnatcmp.c -- Perform 'natural order' comparisons of strings in C.
6 Copyright (C) 2000, 2004 by Martin Pool <mbp sourcefrog net>
8 SPDX-License-Identifier: Zlib
12 /* partial change history:
14 * 2004-10-10 mbp: Lift out character type dependencies into macros.
16 * Eric Sosman pointed out that ctype functions take a parameter whose
17 * value must be that of an unsigned int, even on platforms that have
18 * negative chars in their default char type.
22 * Modified 2014-10-29 to use the g_ascii_XXX() routines; this avoids
23 * locale-dependent behavior. The routine names were changed to
24 * ws_ascii_XXX() to reflect this.
27 #include "strnatcmp.h"
31 /* These are defined as macros to make it easier to adapt this code to
32 * different characters types or comparison functions. */
34 nat_isdigit(nat_char a
)
36 return g_ascii_isdigit(a
);
41 nat_isspace(nat_char a
)
43 return g_ascii_isspace(a
);
48 nat_toupper(nat_char a
)
50 return g_ascii_toupper(a
);
55 compare_right(nat_char
const *a
, nat_char
const *b
)
59 /* The longest run of digits wins. That aside, the greatest
60 value wins, but we can't know that it will until we've scanned
61 both numbers to know that they have the same magnitude, so we
62 remember it in BIAS. */
64 if (!nat_isdigit(*a
) && !nat_isdigit(*b
))
66 else if (!nat_isdigit(*a
))
68 else if (!nat_isdigit(*b
))
76 } else if (!*a
&& !*b
)
85 compare_left(nat_char
const *a
, nat_char
const *b
)
87 /* Compare two left-aligned numbers: the first to have a
88 different value wins. */
90 if (!nat_isdigit(*a
) && !nat_isdigit(*b
))
92 else if (!nat_isdigit(*a
))
94 else if (!nat_isdigit(*b
))
106 static int strnatcmp0(nat_char
const *a
, nat_char
const *b
, int fold_case
)
110 int fractional
, result
;
121 ca
= a
[ai
]; cb
= b
[bi
];
123 /* skip over leading spaces or zeros */
124 while (nat_isspace(ca
))
127 while (nat_isspace(cb
))
130 /* process run of digits */
131 if (nat_isdigit(ca
) && nat_isdigit(cb
)) {
132 fractional
= (ca
== '0' || cb
== '0');
135 if ((result
= compare_left(a
+ai
, b
+bi
)) != 0)
138 if ((result
= compare_right(a
+ai
, b
+bi
)) != 0)
144 /* The strings compare the same. Perhaps the caller
145 will want to call strcmp to break the tie. */
150 ca
= nat_toupper(ca
);
151 cb
= nat_toupper(cb
);
164 int ws_ascii_strnatcmp(nat_char
const *a
, nat_char
const *b
)
166 return strnatcmp0(a
, b
, 0);
170 /* Compare, recognizing numeric string and ignoring case. */
171 int ws_ascii_strnatcasecmp(nat_char
const *a
, nat_char
const *b
)
173 return strnatcmp0(a
, b
, 1);
178 * Editor modelines - https://www.wireshark.org/tools/modelines.html
183 * indent-tabs-mode: nil
186 * vi: set shiftwidth=4 tabstop=8 expandtab:
187 * :indentSize=4:tabSize=8:noTabs=true: