xref: /openbmc/linux/arch/s390/boot/string.c (revision d58106c3)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ctype.h>
3 #include <linux/kernel.h>
4 #include <linux/errno.h>
5 #include "../lib/string.c"
6 
7 int strncmp(const char *cs, const char *ct, size_t count)
8 {
9 	unsigned char c1, c2;
10 
11 	while (count) {
12 		c1 = *cs++;
13 		c2 = *ct++;
14 		if (c1 != c2)
15 			return c1 < c2 ? -1 : 1;
16 		if (!c1)
17 			break;
18 		count--;
19 	}
20 	return 0;
21 }
22 
23 char *skip_spaces(const char *str)
24 {
25 	while (isspace(*str))
26 		++str;
27 	return (char *)str;
28 }
29 
30 char *strim(char *s)
31 {
32 	size_t size;
33 	char *end;
34 
35 	size = strlen(s);
36 	if (!size)
37 		return s;
38 
39 	end = s + size - 1;
40 	while (end >= s && isspace(*end))
41 		end--;
42 	*(end + 1) = '\0';
43 
44 	return skip_spaces(s);
45 }
46 
47 /* Works only for digits and letters, but small and fast */
48 #define TOLOWER(x) ((x) | 0x20)
49 
50 static unsigned int simple_guess_base(const char *cp)
51 {
52 	if (cp[0] == '0') {
53 		if (TOLOWER(cp[1]) == 'x' && isxdigit(cp[2]))
54 			return 16;
55 		else
56 			return 8;
57 	} else {
58 		return 10;
59 	}
60 }
61 
62 /**
63  * simple_strtoull - convert a string to an unsigned long long
64  * @cp: The start of the string
65  * @endp: A pointer to the end of the parsed string will be placed here
66  * @base: The number base to use
67  */
68 
69 unsigned long long simple_strtoull(const char *cp, char **endp,
70 				   unsigned int base)
71 {
72 	unsigned long long result = 0;
73 
74 	if (!base)
75 		base = simple_guess_base(cp);
76 
77 	if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x')
78 		cp += 2;
79 
80 	while (isxdigit(*cp)) {
81 		unsigned int value;
82 
83 		value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10;
84 		if (value >= base)
85 			break;
86 		result = result * base + value;
87 		cp++;
88 	}
89 	if (endp)
90 		*endp = (char *)cp;
91 
92 	return result;
93 }
94 
95 long simple_strtol(const char *cp, char **endp, unsigned int base)
96 {
97 	if (*cp == '-')
98 		return -simple_strtoull(cp + 1, endp, base);
99 
100 	return simple_strtoull(cp, endp, base);
101 }
102 
103 int kstrtobool(const char *s, bool *res)
104 {
105 	if (!s)
106 		return -EINVAL;
107 
108 	switch (s[0]) {
109 	case 'y':
110 	case 'Y':
111 	case '1':
112 		*res = true;
113 		return 0;
114 	case 'n':
115 	case 'N':
116 	case '0':
117 		*res = false;
118 		return 0;
119 	case 'o':
120 	case 'O':
121 		switch (s[1]) {
122 		case 'n':
123 		case 'N':
124 			*res = true;
125 			return 0;
126 		case 'f':
127 		case 'F':
128 			*res = false;
129 			return 0;
130 		default:
131 			break;
132 		}
133 	default:
134 		break;
135 	}
136 
137 	return -EINVAL;
138 }
139