1 /* MIT License
2 *
3 * Copyright (c) 2018 John Schember
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 *
24 * SPDX-License-Identifier: MIT
25 */
26 #include "ares_private.h"
27
ares_strsplit_free(char ** elms,size_t num_elm)28 void ares_strsplit_free(char **elms, size_t num_elm)
29 {
30 ares_free_array(elms, num_elm, ares_free);
31 }
32
ares_strsplit_duplicate(char ** elms,size_t num_elm)33 char **ares_strsplit_duplicate(char **elms, size_t num_elm)
34 {
35 size_t i;
36 char **out;
37
38 if (elms == NULL || num_elm == 0) {
39 return NULL; /* LCOV_EXCL_LINE: DefensiveCoding */
40 }
41
42 out = ares_malloc_zero(sizeof(*elms) * num_elm);
43 if (out == NULL) {
44 return NULL; /* LCOV_EXCL_LINE: OutOfMemory */
45 }
46
47 for (i = 0; i < num_elm; i++) {
48 out[i] = ares_strdup(elms[i]);
49 if (out[i] == NULL) {
50 ares_strsplit_free(out, num_elm); /* LCOV_EXCL_LINE: OutOfMemory */
51 return NULL; /* LCOV_EXCL_LINE: OutOfMemory */
52 }
53 }
54
55 return out;
56 }
57
ares_strsplit(const char * in,const char * delms,size_t * num_elm)58 char **ares_strsplit(const char *in, const char *delms, size_t *num_elm)
59 {
60 ares_status_t status;
61 ares_buf_t *buf = NULL;
62 char **out = NULL;
63
64 if (in == NULL || delms == NULL || num_elm == NULL) {
65 return NULL; /* LCOV_EXCL_LINE: DefensiveCoding */
66 }
67
68 *num_elm = 0;
69
70 buf = ares_buf_create_const((const unsigned char *)in, ares_strlen(in));
71 if (buf == NULL) {
72 return NULL;
73 }
74
75 status = ares_buf_split_str(
76 buf, (const unsigned char *)delms, ares_strlen(delms),
77 ARES_BUF_SPLIT_NO_DUPLICATES | ARES_BUF_SPLIT_CASE_INSENSITIVE, 0, &out,
78 num_elm);
79 if (status != ARES_SUCCESS) {
80 goto done;
81 }
82
83 done:
84 ares_buf_destroy(buf);
85 if (status != ARES_SUCCESS) {
86 out = NULL;
87 }
88
89 return out;
90 }
91