1#pragma once
2
3/* Copyright © 2005-2014 Rich Felker, et al.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25#include "config.h"
26
27#include <ctype.h>
28#include <string.h>
29#include <dirent.h>
30
31#if !defined(HAVE_VERSIONSORT) || defined(TEST_VERSIONSORT)
32static inline int
33libinput_strverscmp(const char *l0, const char *r0)
34{
35	const unsigned char *l = (const void *)l0;
36	const unsigned char *r = (const void *)r0;
37	size_t i, dp, j;
38	int z = 1;
39
40	/* Find maximal matching prefix and track its maximal digit
41	 * suffix and whether those digits are all zeros. */
42	for (dp=i=0; l[i]==r[i]; i++) {
43		int c = l[i];
44		if (!c) return 0;
45		if (!isdigit(c)) dp=i+1, z=1;
46		else if (c!='0') z=0;
47	}
48
49	if (l[dp]!='0' && r[dp]!='0') {
50		/* If we're not looking at a digit sequence that began
51		 * with a zero, longest digit string is greater. */
52		for (j=i; isdigit(l[j]); j++)
53			if (!isdigit(r[j])) return 1;
54		if (isdigit(r[j])) return -1;
55	} else if (z && dp<i && (isdigit(l[i]) || isdigit(r[i]))) {
56		/* Otherwise, if common prefix of digit sequence is
57		 * all zeros, digits order less than non-digits. */
58		return (unsigned char)(l[i]-'0') - (unsigned char)(r[i]-'0');
59	}
60
61	return l[i] - r[i];
62}
63#endif
64
65/* Defined with libinput_ names for testing from platforms with native functions. */
66
67#ifndef HAVE_VERSIONSORT
68static inline int
69strverscmp(const char *l0, const char *r0)
70{
71	return libinput_strverscmp(l0, r0);
72}
73
74static inline int
75versionsort(const struct dirent **a, const struct dirent **b)
76{
77	return libinput_strverscmp((*a)->d_name, (*b)->d_name);
78}
79#endif
80