New upstream version 18.11-rc1
[deb_dpdk.git] / lib / librte_eal / common / eal_common_string_fns.c
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
12 /* split string into tokens */
13 int
14 rte_strsplit(char *string, int stringlen,
15              char **tokens, int maxtokens, char delim)
16 {
17         int i, tok = 0;
18         int tokstart = 1; /* first token is right at start of string */
19
20         if (string == NULL || tokens == NULL)
21                 goto einval_error;
22
23         for (i = 0; i < stringlen; i++) {
24                 if (string[i] == '\0' || tok >= maxtokens)
25                         break;
26                 if (tokstart) {
27                         tokstart = 0;
28                         tokens[tok++] = &string[i];
29                 }
30                 if (string[i] == delim) {
31                         string[i] = '\0';
32                         tokstart = 1;
33                 }
34         }
35         return tok;
36
37 einval_error:
38         errno = EINVAL;
39         return -1;
40 }
41
42 /* Copy src string into dst.
43  *
44  * Return negative value and NUL-terminate if dst is too short,
45  * Otherwise return number of bytes copied.
46  */
47 ssize_t
48 rte_strscpy(char *dst, const char *src, size_t dsize)
49 {
50         size_t nleft = dsize;
51         size_t res = 0;
52
53         /* Copy as many bytes as will fit. */
54         while (nleft != 0) {
55                 dst[res] = src[res];
56                 if (src[res] == '\0')
57                         return res;
58                 res++;
59                 nleft--;
60         }
61
62         /* Not enough room in dst, set NUL and return error. */
63         if (res != 0)
64                 dst[res - 1] = '\0';
65         return -E2BIG;
66 }