1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2012 Kay Sievers <kay.sievers@vrfy.org>
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 struct strbuf *strbuf_new(void) {
31 str = new0(struct strbuf, 1);
35 str->buf = new0(char, 1);
40 str->root = new0(struct strbuf_node, 1);
52 static void strbuf_node_cleanup(struct strbuf_node *node) {
55 for (i = 0; i < node->children_count; i++)
56 strbuf_node_cleanup(node->children[i].child);
61 void strbuf_complete(struct strbuf *str) {
65 strbuf_node_cleanup(str->root);
69 void strbuf_cleanup(struct strbuf *str) {
73 strbuf_node_cleanup(str->root);
78 static int strbuf_children_cmp(const void *v1, const void *v2) {
79 const struct strbuf_child_entry *n1 = v1;
80 const struct strbuf_child_entry *n2 = v2;
85 ssize_t strbuf_add_string(struct strbuf *str, const char *s, size_t len) {
87 struct strbuf_node *node;
90 struct strbuf_child_entry *child;
91 struct strbuf_node *node_child;
97 /* search string; start from last character to find possibly matching tails */
105 for (depth = 0; depth <= len; depth++) {
106 struct strbuf_child_entry search;
108 /* match against current node */
109 off = node->value_off + node->value_len - len;
110 if (depth == len || (node->value_len >= len && memcmp(str->buf + off, s, len) == 0)) {
111 str->dedup_len += len;
116 /* lookup child node */
117 c = s[len - 1 - depth];
119 child = bsearch(&search, node->children, node->children_count, sizeof(struct strbuf_child_entry),
120 strbuf_children_cmp);
127 buf_new = realloc(str->buf, str->len + len+1);
132 memcpy(str->buf + off, s, len);
134 str->buf[str->len++] = '\0';
137 node_child = new0(struct strbuf_node, 1);
141 node_child->value_off = off;
142 node_child->value_len = len;
144 /* extend array, add new entry, sort for bisection */
145 child = realloc(node->children, (node->children_count + 1) * sizeof(struct strbuf_child_entry));
148 node->children = child;
149 node->children[node->children_count].c = c;
150 node->children[node->children_count].child = node_child;
151 node->children_count++;
152 qsort(node->children, node->children_count, sizeof(struct strbuf_child_entry), strbuf_children_cmp);