1 /*
2 * Copyright 2008-2013 Various Authors
3 * Copyright 2004 Timo Hirvonen
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * 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
19 #include "tabexp.h"
20 #include "xmalloc.h"
21 #include "xstrjoin.h"
22 #include "debug.h"
23
24 #include <stdlib.h>
25
26 struct tabexp tabexp = {
27 .head = NULL,
28 .tails = NULL,
29 .count = 0
30 };
31
tabexp_expand(const char * src,void (* load_matches)(const char * src),int direction)32 char *tabexp_expand(const char *src, void (*load_matches)(const char *src), int direction)
33 {
34 static int idx = -1;
35 char *expanded;
36
37 if (tabexp.tails == NULL) {
38 load_matches(src);
39 if (tabexp.tails == NULL) {
40 BUG_ON(tabexp.head != NULL);
41 return NULL;
42 }
43 BUG_ON(tabexp.head == NULL);
44 idx = -1;
45 }
46 idx += direction;
47
48 if (idx >= tabexp.count)
49 idx = 0;
50 else if (idx < 0)
51 idx = tabexp.count - 1;
52
53 expanded = xstrjoin(tabexp.head, tabexp.tails[idx]);
54 if (tabexp.count == 1)
55 tabexp_reset();
56 return expanded;
57 }
58
tabexp_reset(void)59 void tabexp_reset(void)
60 {
61 int i;
62 for (i = 0; i < tabexp.count; i++)
63 free(tabexp.tails[i]);
64 free(tabexp.tails);
65 free(tabexp.head);
66 tabexp.tails = NULL;
67 tabexp.head = NULL;
68 tabexp.count = 0;
69 }
70