1 /* SPDX-License-Identifier: BSD-3-Clause 2 * Copyright(c) 2010-2014 Intel Corporation 3 */ 4 5 #include <ctype.h> 6 #include <errno.h> 7 #include <stdio.h> 8 #include <stdlib.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 70 uint64_t 71 rte_str_to_size(const char *str) 72 { 73 char *endptr; 74 unsigned long long size; 75 76 while (isspace((int)*str)) 77 str++; 78 if (*str == '-') 79 return 0; 80 81 errno = 0; 82 size = strtoull(str, &endptr, 0); 83 if (errno) 84 return 0; 85 86 if (*endptr == ' ') 87 endptr++; /* allow 1 space gap */ 88 89 switch (*endptr) { 90 case 'G': case 'g': 91 size *= 1024; /* fall-through */ 92 case 'M': case 'm': 93 size *= 1024; /* fall-through */ 94 case 'K': case 'k': 95 size *= 1024; /* fall-through */ 96 default: 97 break; 98 } 99 return size; 100 } 101