2 * This file is part of the PulseView project.
4 * Copyright (C) 2000, 2004 by Martin Pool <mbp sourcefrog net>
6 * This software is provided 'as-is', without any express or implied
7 * warranty. In no event will the authors be held liable for any damages
8 * arising from the use of this software.
10 * Permission is granted to anyone to use this software for any purpose,
11 * including commercial applications, and to alter it and redistribute it
12 * freely, subject to the following restrictions:
14 * 1. The origin of this software must not be misrepresented; you must not
15 * claim that you wrote the original software. If you use this software
16 * in a product, an acknowledgment in the product documentation would be
17 * appreciated but is not required.
18 * 2. Altered source versions must be plainly marked as such, and must not be
19 * misrepresented as being the original software.
20 * 3. This notice may not be removed or altered from any source distribution.
23 // strnatcmp.c -- Perform 'natural order' comparisons of strings in C.
24 // This file has been modified for C++ compatibility.
25 // Original at https://github.com/sourcefrog/natsort/blob/master/strnatcmp.c
27 #ifndef PULSEVIEW_PV_STRNATCMP_HPP
28 #define PULSEVIEW_PV_STRNATCMP_HPP
31 #include <cstddef> /* size_t */
36 static int compare_right(char const *a
, char const *b
)
40 // The longest run of digits wins. That aside, the greatest
41 // value wins, but we can't know that it will until we've scanned
42 // both numbers to know that they have the same magnitude, so we
43 // remember it in bias.
45 if (!isdigit(*a
) && !isdigit(*b
))
58 } else if (!*a
&& !*b
)
65 static int compare_left(char const *a
, char const *b
)
67 // Compare two left-aligned numbers: the first to have a
68 // different value wins.
70 if (!isdigit(*a
) && !isdigit(*b
))
85 static int strnatcmp0(char const *a
, char const *b
, int fold_case
)
87 int ai
, bi
, fractional
, result
;
96 // Skip over leading spaces or zeroes
103 // Process run of digits
104 if (isdigit(ca
) && isdigit(cb
)) {
105 fractional
= (ca
== '0' || cb
== '0');
108 if ((result
= compare_left(a
+ ai
, b
+ bi
)) != 0)
111 if ((result
= compare_right(a
+ ai
, b
+ bi
)) != 0)
117 // The strings compare the same. Perhaps the caller
118 // will want to call strcmp to break the tie
138 // Compare, recognizing numeric strings and being case sensitive
139 int strnatcmp(char const *a
, char const *b
)
141 return strnatcmp0(a
, b
, 0);
144 int strnatcmp(const string a
, const string b
)
146 return strnatcmp0(a
.c_str(), b
.c_str(), 0);
149 // Compare, recognizing numeric strings and ignoring case
150 int strnatcasecmp(char const *a
, char const *b
)
152 return strnatcmp0(a
, b
, 1);
155 int strnatcasecmp(const string a
, const string b
)
157 return strnatcmp0(a
.c_str(), b
.c_str(), 1);
160 #endif // PULSEVIEW_PV_STRNATCMP_HPP