]> git.notmuchmail.org Git - notmuch/blob - lib/string-list.c
d92a0bab5a77feb4b9cc967a208e5f66c36b886b
[notmuch] / lib / string-list.c
1 /* strings.c - Iterator for a list of strings
2  *
3  * Copyright © 2010 Intel Corporation
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-private.h"
22
23 /* Create a new notmuch_string_list_t object, with 'ctx' as its
24  * talloc owner.
25  *
26  * This function can return NULL in case of out-of-memory.
27  */
28 notmuch_string_list_t *
29 _notmuch_string_list_create (const void *ctx)
30 {
31     notmuch_string_list_t *list;
32
33     list = talloc (ctx, notmuch_string_list_t);
34     if (unlikely (list == NULL))
35         return NULL;
36
37     list->length = 0;
38     list->head = NULL;
39     list->tail = &list->head;
40
41     return list;
42 }
43
44 void
45 _notmuch_string_list_append (notmuch_string_list_t *list,
46                              const char *string)
47 {
48     /* Create and initialize new node. */
49     notmuch_string_node_t *node = talloc (list, notmuch_string_node_t);
50
51     node->string = talloc_strdup (node, string);
52     node->next = NULL;
53
54     /* Append the node to the list. */
55     *(list->tail) = node;
56     list->tail = &node->next;
57     list->length++;
58 }
59
60 static int
61 cmpnode (const void *pa, const void *pb)
62 {
63     notmuch_string_node_t *a = *(notmuch_string_node_t * const *)pa;
64     notmuch_string_node_t *b = *(notmuch_string_node_t * const *)pb;
65
66     return strcmp (a->string, b->string);
67 }
68
69 void
70 _notmuch_string_list_sort (notmuch_string_list_t *list)
71 {
72     notmuch_string_node_t **nodes, *node;
73     int i;
74
75     if (list->length == 0)
76         return;
77
78     nodes = talloc_array (list, notmuch_string_node_t *, list->length);
79     if (unlikely (nodes == NULL))
80         INTERNAL_ERROR ("Could not allocate memory for list sort");
81
82     for (i = 0, node = list->head; node; i++, node = node->next)
83         nodes[i] = node;
84
85     qsort (nodes, list->length, sizeof (*nodes), cmpnode);
86
87     for (i = 0; i < list->length - 1; ++i)
88         nodes[i]->next = nodes[i+1];
89     nodes[i]->next = NULL;
90     list->head = nodes[0];
91     list->tail = &nodes[i]->next;
92
93     talloc_free (nodes);
94 }