1 /* -*- mode: c; c-file-style: "k&r" -*-
3 strnatcmp.c -- Perform 'natural order' comparisons of strings in C.
4 Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>
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.
25 #include "apr_strings.h"
26 #include "apr_lib.h" /* for apr_is*() */
29 # define UNUSED __attribute__((__unused__))
34 /* based on "strnatcmp.c,v 1.6 2000/04/20 07:30:11 mbp Exp $" */
37 compare_right(char const *a, char const *b)
41 /* The longest run of digits wins. That aside, the greatest
42 value wins, but we can't know that it will until we've scanned
43 both numbers to know that they have the same magnitude, so we
44 remember it in BIAS. */
46 if (!apr_isdigit(*a) && !apr_isdigit(*b))
48 else if (!apr_isdigit(*a))
50 else if (!apr_isdigit(*b))
58 } else if (!*a && !*b)
67 compare_left(char const *a, char const *b)
69 /* Compare two left-aligned numbers: the first to have a
70 different value wins. */
72 if (!apr_isdigit(*a) && !apr_isdigit(*b))
74 else if (!apr_isdigit(*a))
76 else if (!apr_isdigit(*b))
88 static int strnatcmp0(char const *a, char const *b, int fold_case)
92 int fractional, result;
95 ca = a[ai]; cb = b[bi];
97 /* skip over leading spaces or zeros */
98 while (apr_isspace(ca))
101 while (apr_isspace(cb))
104 /* process run of digits */
105 if (apr_isdigit(ca) && apr_isdigit(cb)) {
106 fractional = (ca == '0' || cb == '0');
109 if ((result = compare_left(a+ai, b+bi)) != 0)
112 if ((result = compare_right(a+ai, b+bi)) != 0)
118 /* The strings compare the same. Perhaps the caller
119 will want to call strcmp to break the tie. */
124 ca = apr_toupper(ca);
125 cb = apr_toupper(cb);
139 APR_DECLARE(int) apr_strnatcmp(char const *a, char const *b)
141 return strnatcmp0(a, b, 0);
145 /* Compare, recognizing numeric string and ignoring case. */
146 APR_DECLARE(int) apr_strnatcasecmp(char const *a, char const *b)
148 return strnatcmp0(a, b, 1);