Merge branch 'en/dir-traversal'
[git] / t / helper / test-mergesort.c
1 #include "test-tool.h"
2 #include "cache.h"
3 #include "mergesort.h"
4
5 struct line {
6         char *text;
7         struct line *next;
8 };
9
10 static void *get_next(const void *a)
11 {
12         return ((const struct line *)a)->next;
13 }
14
15 static void set_next(void *a, void *b)
16 {
17         ((struct line *)a)->next = b;
18 }
19
20 static int compare_strings(const void *a, const void *b)
21 {
22         const struct line *x = a, *y = b;
23         return strcmp(x->text, y->text);
24 }
25
26 int cmd__mergesort(int argc, const char **argv)
27 {
28         struct line *line, *p = NULL, *lines = NULL;
29         struct strbuf sb = STRBUF_INIT;
30
31         for (;;) {
32                 if (strbuf_getwholeline(&sb, stdin, '\n'))
33                         break;
34                 line = xmalloc(sizeof(struct line));
35                 line->text = strbuf_detach(&sb, NULL);
36                 if (p) {
37                         line->next = p->next;
38                         p->next = line;
39                 } else {
40                         line->next = NULL;
41                         lines = line;
42                 }
43                 p = line;
44         }
45
46         lines = llist_mergesort(lines, get_next, set_next, compare_strings);
47
48         while (lines) {
49                 printf("%s", lines->text);
50                 lines = lines->next;
51         }
52         return 0;
53 }