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 https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
19 * Austin Clements <aclements@csail.mit.edu>
22 #include "notmuch-private.h"
24 /* Create a new notmuch_string_list_t object, with 'ctx' as its
27 * This function can return NULL in case of out-of-memory.
29 notmuch_string_list_t *
30 _notmuch_string_list_create (const void *ctx)
32 notmuch_string_list_t *list;
34 list = talloc (ctx, notmuch_string_list_t);
35 if (unlikely (list == NULL))
40 list->tail = &list->head;
46 _notmuch_string_list_append (notmuch_string_list_t *list,
49 /* Create and initialize new node. */
50 notmuch_string_node_t *node = talloc (list, notmuch_string_node_t);
52 node->string = talloc_strdup (node, string);
55 /* Append the node to the list. */
57 list->tail = &node->next;
62 cmpnode (const void *pa, const void *pb)
64 notmuch_string_node_t *a = *(notmuch_string_node_t * const *)pa;
65 notmuch_string_node_t *b = *(notmuch_string_node_t * const *)pb;
67 return strcmp (a->string, b->string);
71 _notmuch_string_list_sort (notmuch_string_list_t *list)
73 notmuch_string_node_t **nodes, *node;
76 if (list->length == 0)
79 nodes = talloc_array (list, notmuch_string_node_t *, list->length);
80 if (unlikely (nodes == NULL))
81 INTERNAL_ERROR ("Could not allocate memory for list sort");
83 for (i = 0, node = list->head; node; i++, node = node->next)
86 qsort (nodes, list->length, sizeof (*nodes), cmpnode);
88 for (i = 0; i < list->length - 1; ++i)
89 nodes[i]->next = nodes[i+1];
90 nodes[i]->next = NULL;
91 list->head = nodes[0];
92 list->tail = &nodes[i]->next;