xref: /dpdk/lib/eal/common/eal_common_string_fns.c (revision daa02b5cddbb8e11b31d41e2bf7bb1ae64dcae2f)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4 
5 #include <string.h>
6 #include <stdio.h>
7 #include <stdarg.h>
8 #include <errno.h>
9 
10 #include <rte_string_fns.h>
11 #include <rte_errno.h>
12 
13 /* split string into tokens */
14 int
15 rte_strsplit(char *string, int stringlen,
16 	     char **tokens, int maxtokens, char delim)
17 {
18 	int i, tok = 0;
19 	int tokstart = 1; /* first token is right at start of string */
20 
21 	if (string == NULL || tokens == NULL)
22 		goto einval_error;
23 
24 	for (i = 0; i < stringlen; i++) {
25 		if (string[i] == '\0' || tok >= maxtokens)
26 			break;
27 		if (tokstart) {
28 			tokstart = 0;
29 			tokens[tok++] = &string[i];
30 		}
31 		if (string[i] == delim) {
32 			string[i] = '\0';
33 			tokstart = 1;
34 		}
35 	}
36 	return tok;
37 
38 einval_error:
39 	errno = EINVAL;
40 	return -1;
41 }
42 
43 /* Copy src string into dst.
44  *
45  * Return negative value and NUL-terminate if dst is too short,
46  * Otherwise return number of bytes copied.
47  */
48 ssize_t
49 rte_strscpy(char *dst, const char *src, size_t dsize)
50 {
51 	size_t nleft = dsize;
52 	size_t res = 0;
53 
54 	/* Copy as many bytes as will fit. */
55 	while (nleft != 0) {
56 		dst[res] = src[res];
57 		if (src[res] == '\0')
58 			return res;
59 		res++;
60 		nleft--;
61 	}
62 
63 	/* Not enough room in dst, set NUL and return error. */
64 	if (res != 0)
65 		dst[res - 1] = '\0';
66 	rte_errno = E2BIG;
67 	return -rte_errno;
68 }
69