Code

c07cfa1c2de1e0153f661c2a1553753d451788bb
[sysdb.git] / src / utils / strings.c
1 /*
2  * SysDB - src/utils/strings.c
3  * Copyright (C) 2016 Sebastian 'tokkee' Harl <sh@tokkee.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
28 #if HAVE_CONFIG_H
29 #       include "config.h"
30 #endif
32 #include "utils/strings.h"
34 #include <stdlib.h>
35 #include <string.h>
37 /*
38  * public API
39  */
41 int
42 stringv_copy(char ***dst, size_t *dst_len,
43                 const char * const *src, size_t src_len)
44 {
45         char **tmp;
46         size_t i;
48         if (*dst) {
49                 tmp = realloc(*dst, src_len * sizeof(*tmp));
50                 if (tmp)
51                         memset(tmp, 0, src_len * sizeof(*tmp));
52         }
53         else
54                 tmp = calloc(src_len, sizeof(*tmp));
56         if (! tmp)
57                 return -1;
59         *dst = tmp;
60         *dst_len = src_len;
61         for (i = 0; i < src_len; ++i) {
62                 (*dst)[i] = strdup(src[i]);
63                 if (! (*dst)[i])
64                         return -1;
65         }
66         return 0;
67 } /* stringv_copy */
69 void
70 stringv_free(char ***s, size_t *s_len)
71 {
72         size_t i;
74         if (*s) {
75                 for (i = 0; i < *s_len; ++i) {
76                         if ((*s)[i])
77                                 free((*s)[i]);
78                         (*s)[i] = NULL;
79                 }
80                 free(*s);
81         }
83         *s = NULL;
84         *s_len = 0;
85 } /* stringv_free */
87 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */