1 /*
2 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
3 * Use is subject to license terms.
4 */
5
6 #pragma ident "%Z%%M% %I% %E% SMI"
7
8 #include <stdio.h>
9 #include <strings.h>
10 #include "xmalloc.h"
11 #include "xlist.h"
12
13 char **
xsplit(char * list,char sep)14 xsplit(char *list, char sep)
15 {
16 char **a;
17 char *p, *q;
18 uint_t n = 0;
19
20 for (n = 0, p = list; p && *p; ) {
21 while (p && *p && *p == sep)
22 p++;
23 if (!*p)
24 break;
25 n++;
26 p = strchr(p, sep);
27 }
28 a = (char **)xmalloc(sizeof (char *) * (n + 2));
29 for (n = 0, p = list; p && *p; ) {
30 while (*p == sep)
31 p++;
32 if (!*p)
33 break;
34 q = strchr(p, sep);
35 if (!q)
36 q = p + strlen(p);
37 a[n] = (char *)xmalloc((q - p + 2));
38 (void) strncpy(a[n], p, q - p);
39 a[n][q - p] = '\0';
40 n++;
41 if (!*q)
42 break;
43 p = q + 1;
44 }
45 a[n] = NULL;
46 return (a);
47 }
48
49 void
xfree_split_list(char ** list)50 xfree_split_list(char **list)
51 {
52 char **p;
53 for (p = list; p && *p; p++) {
54 xfree(*p);
55 }
56 xfree(list);
57 }
58
59 char *
xjoin(char ** alist,char sep)60 xjoin(char **alist, char sep)
61 {
62 char **p;
63 char *list;
64 char sep_str[2];
65 uint_t n;
66
67 for (n = 1, p = alist; p && *p; p++) {
68 if (!*p || !**p)
69 continue;
70 n += strlen(*p) + 1;
71 }
72 list = (char *)xmalloc(n);
73 *list = '\0';
74
75 sep_str[0] = sep;
76 sep_str[1] = '\0';
77 for (p = alist; p && *p; p++) {
78 if (!*p || !**p)
79 continue;
80 if (*list != '\0')
81 (void) strlcat(list, sep_str, n);
82 (void) strlcat(list, *p, n);
83 }
84 return (list);
85 }
86