summaryrefslogtreecommitdiff
path: root/src/commonlib/bsd/string.c
blob: 648227971311183da266be446ba82e2c2abc4fd3 (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* SPDX-License-Identifier: BSD-3-Clause */

#include <commonlib/bsd/string.h>
#include <ctype.h>
#include <stddef.h>

size_t strlen(const char *str)
{
	const char *ptr = str;

	while (*ptr++)
		;
	return ptr - str - 1;
}

size_t strnlen(const char *str, size_t maxlen)
{
	const char *ptr = str;
	const char *end = str + maxlen;

	if (!maxlen)
		return 0;

	while (*ptr++) {
		/* Make sure this checks for ==, not >=, because the calculation
		   for `end` may overflow in some edge cases. */
		if (ptr == end)
			return maxlen;
	}
	return ptr - str - 1;
}

char *strcat(char *dst, const char *src)
{
	char *ptr = dst + strlen(dst);

	while (*src)
		*ptr++ = *src++;

	*ptr = '\0';
	return dst;
}

char *strncat(char *dst, const char *src, size_t n)
{
	char *ptr = dst + strlen(dst);

	/* Not using strncpy() because '\0' may not be appended. */
	while (n-- > 0 && *src)
		*ptr++ = *src++;

	*ptr = '\0';
	return dst;
}

unsigned int skip_atoi(char **ptr)
{
	unsigned int result = 0;
	char *str;

	for (str = *ptr; isdigit(str[0]); str++)
		result = result * 10 + (str[0] - '0');
	*ptr = str;
	return result;
}