Fix mysterious crashes such as #7049
[ardour.git] / libs / pbd / pbd / natsort.h
1 /*
2  * Copyright 2016 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2, or (at your option)
7  * any later version.
8  *
9  * This program 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 General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #ifndef PBD_NATSORT
20 #define PBD_NATSORT
21
22 #include <ctype.h>
23 #include <stdlib.h>
24
25 namespace PBD {
26
27 inline bool
28 naturally_less (const char* a, const char* b)
29 {
30         const char* d_a = NULL;
31         const char* d_b = NULL;
32
33         for (;*a && *b; ++a, ++b) {
34                 if (isdigit (*a) && isdigit (*b) && !d_a) {
35                         d_a = a; d_b = b;
36                         continue;
37                 }
38                 if (d_a) {
39                         const int ia = atoi (d_a);
40                         const int ib = atoi (d_b);
41                         if (ia != ib) {
42                                 return ia < ib;
43                         }
44                 }
45                 d_a = d_b = NULL;
46                 if (*a == *b) {
47                         continue;
48                 }                                                                                                                                                                                          
49                 return *a < *b;
50         }
51
52         if (d_a) {
53                 return atoi (d_a) < atoi (d_b);
54         }
55
56         /* if we reach here, either strings are same length and equal
57          * or one is longer than the other.
58          */
59
60         if (*a) { return false; }
61         if (*b) { return true; }
62         return false; // equal
63 }
64
65 } // namespace PBD
66
67 #endif // PBD_NATSORT