/src/mpv/misc/natural_sort.c
Line | Count | Source |
1 | | /* |
2 | | * This file is part of mpv. |
3 | | * |
4 | | * mpv is free software; you can redistribute it and/or |
5 | | * modify it under the terms of the GNU Lesser General Public |
6 | | * License as published by the Free Software Foundation; either |
7 | | * version 2.1 of the License, or (at your option) any later version. |
8 | | * |
9 | | * mpv is distributed in the hope that it will be useful, |
10 | | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
11 | | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
12 | | * GNU Lesser General Public License for more details. |
13 | | * |
14 | | * You should have received a copy of the GNU Lesser General Public |
15 | | * License along with mpv. If not, see <http://www.gnu.org/licenses/>. |
16 | | */ |
17 | | |
18 | | #include "misc/ctype.h" |
19 | | |
20 | | #include "natural_sort.h" |
21 | | |
22 | | // Comparison function for an ASCII-only "natural" sort. Case is ignored and |
23 | | // numbers are ordered by value regardless of padding. Two filenames that differ |
24 | | // only in the padding of numbers will be considered equal and end up in |
25 | | // arbitrary order. Bytes outside of A-Z/a-z/0-9 will by sorted by byte value. |
26 | | int mp_natural_sort_cmp(const char *name1, const char *name2) |
27 | 0 | { |
28 | 0 | while (name1[0] && name2[0]) { |
29 | 0 | if (mp_isdigit(name1[0]) && mp_isdigit(name2[0])) { |
30 | 0 | while (name1[0] == '0') |
31 | 0 | name1++; |
32 | 0 | while (name2[0] == '0') |
33 | 0 | name2++; |
34 | 0 | const char *end1 = name1, *end2 = name2; |
35 | 0 | while (mp_isdigit(*end1)) |
36 | 0 | end1++; |
37 | 0 | while (mp_isdigit(*end2)) |
38 | 0 | end2++; |
39 | | // With padding stripped, a number with more digits is bigger. |
40 | 0 | if ((end1 - name1) < (end2 - name2)) |
41 | 0 | return -1; |
42 | 0 | if ((end1 - name1) > (end2 - name2)) |
43 | 0 | return 1; |
44 | | // Same length, lexicographical works. |
45 | 0 | while (name1 < end1) { |
46 | 0 | if (name1[0] < name2[0]) |
47 | 0 | return -1; |
48 | 0 | if (name1[0] > name2[0]) |
49 | 0 | return 1; |
50 | 0 | name1++; |
51 | 0 | name2++; |
52 | 0 | } |
53 | 0 | } else { |
54 | 0 | if ((unsigned char)mp_tolower(name1[0]) < (unsigned char)mp_tolower(name2[0])) |
55 | 0 | return -1; |
56 | 0 | if ((unsigned char)mp_tolower(name1[0]) > (unsigned char)mp_tolower(name2[0])) |
57 | 0 | return 1; |
58 | 0 | name1++; |
59 | 0 | name2++; |
60 | 0 | } |
61 | 0 | } |
62 | 0 | if (name2[0]) |
63 | 0 | return -1; |
64 | 0 | if (name1[0]) |
65 | 0 | return 1; |
66 | 0 | return 0; |
67 | 0 | } |