summaryrefslogtreecommitdiff
path: root/src/string/strverscmp.c
blob: 6f37cc6801fa8094cbdbc9080cf8f3b74661502e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#define _GNU_SOURCE
#include <ctype.h>
#include <string.h>

int strverscmp(const char *l, const char *r)
{
	int haszero=1;
	while (*l==*r) {
		if (!*l) return 0;

		if (*l=='0') {
			if (haszero==1) {
				haszero=0;
			}
		} else if (isdigit(*l)) {
			if (haszero==1) {
				haszero=2;
			}
		} else {
			haszero=1;
		}
		l++; r++;
	}
	if (haszero==1 && (*l=='0' || *r=='0')) {
		haszero=0;
	}
	if ((isdigit(*l) && isdigit(*r) ) && haszero) {
		size_t lenl=0, lenr=0;
		while (isdigit(l[lenl]) ) lenl++;
		while (isdigit(r[lenr]) ) lenr++;
		if (lenl==lenr) {
			return (*l -  *r);
		} else if (lenl>lenr) {
			return 1;
		} else {
			return -1;
		}
	} else {
		return (*l -  *r);
	}
}