009b00fa0ee0ab07b6a623ff44ea23e728c69a3f
[platform/upstream/glib.git] / tests / unicode-collate.c
1 #undef G_DISABLE_ASSERT
2 #undef G_LOG_DOMAIN
3
4 #include <glib.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 typedef struct {
10   const char *key;
11   const char *str;
12 } Line;
13   
14
15 int 
16 compare_collate (const void *a, const void *b)
17 {
18   const Line *line_a = a;
19   const Line *line_b = b;
20
21   return g_utf8_collate (line_a->str, line_b->str);
22 }
23
24 int 
25 compare_key (const void *a, const void *b)
26 {
27   const Line *line_a = a;
28   const Line *line_b = b;
29
30   return strcmp (line_a->key, line_b->key);
31 }
32
33 int main (int argc, char **argv)
34 {
35   GIOChannel *in;
36   GError *error = NULL;
37   GArray *line_array = g_array_new (FALSE, FALSE, sizeof(Line));
38   guint i;
39   gboolean do_key = FALSE;
40   gboolean do_file = FALSE;
41
42   if (argc != 1 && argc != 2 && argc != 3)
43     {
44       fprintf (stderr, "Usage: unicode-collate [--key|--file] [FILE]\n");
45       return 1;
46     }
47
48   i = 1;
49   if (argc > 1)
50     {
51       if (strcmp (argv[1], "--key") == 0)
52         {
53           do_key = TRUE;
54           i = 2;
55         }
56       else if (strcmp (argv[1], "--file") == 0)
57         {
58           do_key = TRUE;
59           do_file = TRUE;
60           i = 2;
61         }
62     }
63
64  if (argc > i)
65     {
66       in = g_io_channel_new_file (argv[i], "r", &error);
67       if (!in)
68         {
69           fprintf (stderr, "Cannot open %s: %s\n", argv[i], error->message);
70           return 1;
71         }
72     }
73   else
74     {
75       in = g_io_channel_unix_new (fileno (stdin));
76     }
77
78   while (TRUE)
79     {
80       gsize term_pos;
81       gchar *str;
82       Line line;
83
84       if (g_io_channel_read_line (in, &str, NULL, &term_pos, &error) != G_IO_STATUS_NORMAL)
85         break;
86
87       str[term_pos] = '\0';
88
89       if (do_file)
90         line.key = g_utf8_collate_key_for_filename (str, -1);
91       else
92         line.key = g_utf8_collate_key (str, -1);
93       line.str = str;
94
95       g_array_append_val (line_array, line);
96     }
97
98   if (error)
99     {
100       fprintf (stderr, "Error reading test file, %s\n", error->message);
101       return 1;
102     }
103
104   qsort (line_array->data, line_array->len, sizeof (Line), do_key ? compare_key : compare_collate);
105   for (i = 0; i < line_array->len; i++)
106     printf ("%s\n", g_array_index (line_array, Line, i).str);
107
108   g_io_channel_unref (in);
109
110   return 0;
111 }