1 /* strings.c - Iterator for a list of strings
3 * Copyright © 2010 Intel Corporation
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.
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.
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/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "notmuch-private.h"
23 /* Create a new notmuch_string_list_t object, with 'ctx' as its
26 * This function can return NULL in case of out-of-memory.
28 notmuch_string_list_t *
29 _notmuch_string_list_create (const void *ctx)
31 notmuch_string_list_t *list;
33 list = talloc (ctx, notmuch_string_list_t);
34 if (unlikely (list == NULL))
39 list->tail = &list->head;
45 _notmuch_string_list_append (notmuch_string_list_t *list,
48 /* Create and initialize new node. */
49 notmuch_string_node_t *node = talloc (list, notmuch_string_node_t);
51 node->string = talloc_strdup (node, string);
54 /* Append the node to the list. */
56 list->tail = &node->next;
61 cmpnode (const void *pa, const void *pb)
63 notmuch_string_node_t *a = *(notmuch_string_node_t * const *)pa;
64 notmuch_string_node_t *b = *(notmuch_string_node_t * const *)pb;
66 return strcmp (a->string, b->string);
70 _notmuch_string_list_sort (notmuch_string_list_t *list)
72 notmuch_string_node_t **nodes, *node;
75 if (list->length == 0)
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");
82 for (i = 0, node = list->head; node; i++, node = node->next)
85 qsort (nodes, list->length, sizeof (*nodes), cmpnode);
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;