Don't write out zero-byte sections in builder
[platform/upstream/glib.git] / gio / gvdb / gvdb-builder.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "gvdb-builder.h"
23 #include "gvdb-format.h"
24
25 #include <glib.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <string.h>
29
30
31 struct _GvdbItem
32 {
33   gchar *key;
34   guint32 hash_value;
35   guint32_le assigned_index;
36   GvdbItem *parent;
37   GvdbItem *sibling;
38   GvdbItem *next;
39   GVariant *options;
40
41   /* one of:
42    * this:
43    */
44   GVariant *value;
45
46   /* this: */
47   GHashTable *table;
48
49   /* or this: */
50   GvdbItem *child;
51 };
52
53 static void
54 gvdb_item_free (gpointer data)
55 {
56   GvdbItem *item = data;
57
58   g_free (item->key);
59
60   if (item->value)
61     g_variant_unref (item->value);
62
63   if (item->options)
64     g_variant_unref (item->options);
65
66   if (item->table)
67     g_hash_table_unref (item->table);
68
69   g_slice_free (GvdbItem, item);
70 }
71
72 GHashTable *
73 gvdb_hash_table_new (GHashTable  *parent,
74                      const gchar *name_in_parent)
75 {
76   GHashTable *table;
77
78   table = g_hash_table_new_full (g_str_hash, g_str_equal,
79                                  g_free, gvdb_item_free);
80
81   if (parent)
82     {
83       GvdbItem *item;
84
85       item = gvdb_hash_table_insert (parent, name_in_parent);
86       gvdb_item_set_hash_table (item, table);
87     }
88
89   return table;
90 }
91
92 static guint32
93 djb_hash (const gchar *key)
94 {
95   guint32 hash_value = 5381;
96
97   while (*key)
98     hash_value = hash_value * 33 + *key++;
99
100   return hash_value;
101 }
102
103 GvdbItem *
104 gvdb_hash_table_insert (GHashTable  *table,
105                         const gchar *key)
106 {
107   GvdbItem *item;
108
109   item = g_slice_new0 (GvdbItem);
110   item->key = g_strdup (key);
111   item->hash_value = djb_hash (key);
112
113   g_hash_table_insert (table, g_strdup (key), item);
114
115   return item;
116 }
117
118 void
119 gvdb_hash_table_insert_string (GHashTable  *table,
120                                const gchar *key,
121                                const gchar *value)
122 {
123   GvdbItem *item;
124
125   item = gvdb_hash_table_insert (table, key);
126   gvdb_item_set_value (item, g_variant_new_string (value));
127 }
128
129 void
130 gvdb_item_set_value (GvdbItem *item,
131                      GVariant *value)
132 {
133   g_return_if_fail (!item->value && !item->table && !item->child);
134
135   item->value = g_variant_ref_sink (value);
136 }
137
138 void
139 gvdb_item_set_options (GvdbItem *item,
140                        GVariant *options)
141 {
142   g_return_if_fail (!item->options);
143
144   item->options = g_variant_ref_sink (options);
145 }
146
147 void
148 gvdb_item_set_hash_table (GvdbItem   *item,
149                           GHashTable *table)
150 {
151   g_return_if_fail (!item->value && !item->table && !item->child);
152
153   item->table = g_hash_table_ref (table);
154 }
155
156 void
157 gvdb_item_set_parent (GvdbItem *item,
158                       GvdbItem *parent)
159 {
160   GvdbItem **node;
161
162   g_return_if_fail (g_str_has_prefix (item->key, parent->key));
163   g_return_if_fail (!parent->value && !parent->table);
164   g_return_if_fail (!item->parent && !item->sibling);
165
166   for (node = &parent->child; *node; node = &(*node)->sibling)
167     if (strcmp ((*node)->key, item->key) > 0)
168       break;
169
170   item->parent = parent;
171   item->sibling = *node;
172   *node = item;
173 }
174
175 typedef struct
176 {
177   GvdbItem **buckets;
178   gint n_buckets;
179 } HashTable;
180
181 HashTable *
182 hash_table_new (gint n_buckets)
183 {
184   HashTable *table;
185
186   table = g_slice_new (HashTable);
187   table->buckets = g_new0 (GvdbItem *, n_buckets);
188   table->n_buckets = n_buckets;
189
190   return table;
191 }
192
193 static void
194 hash_table_insert (gpointer key,
195                    gpointer value,
196                    gpointer data)
197 {
198   guint32 hash_value, bucket;
199   HashTable *table = data;
200   GvdbItem *item = value;
201
202   hash_value = djb_hash (key);
203   bucket = hash_value % table->n_buckets;
204   item->next = table->buckets[bucket];
205   table->buckets[bucket] = item;
206 }
207
208 static guint32_le
209 item_to_index (GvdbItem *item)
210 {
211   if (item != NULL)
212     return item->assigned_index;
213
214   return guint32_to_le (-1u);
215 }
216
217 typedef struct
218 {
219   GQueue *chunks;
220   guint64 offset;
221   gboolean byteswap;
222 } FileBuilder;
223
224 typedef struct
225 {
226   gsize offset;
227   gsize size;
228   gpointer data;
229 } FileChunk;
230
231 static gpointer
232 file_builder_allocate (FileBuilder         *fb,
233                        guint                alignment,
234                        gsize                size,
235                        struct gvdb_pointer *pointer)
236 {
237   FileChunk *chunk;
238
239   if (size == 0)
240     return NULL;
241
242   fb->offset += (-fb->offset) & (alignment - 1);
243   chunk = g_slice_new (FileChunk);
244   chunk->offset = fb->offset;
245   chunk->size = size;
246   chunk->data = g_malloc (size);
247
248   pointer->start = guint32_to_le (fb->offset);
249   fb->offset += size;
250   pointer->end = guint32_to_le (fb->offset);
251
252   g_queue_push_tail (fb->chunks, chunk);
253
254   return chunk->data;
255 }
256
257 static void
258 file_builder_add_value (FileBuilder         *fb,
259                         GVariant            *value,
260                         struct gvdb_pointer *pointer)
261 {
262   GVariant *variant, *normal;
263   gpointer data;
264   gsize size;
265
266   if (fb->byteswap)
267     {
268       value = g_variant_byteswap (value);
269       variant = g_variant_new_variant (value);
270       g_variant_unref (value);
271     }
272   else
273     variant = g_variant_new_variant (value);
274
275   normal = g_variant_get_normal_form (variant);
276   g_variant_unref (variant);
277
278   size = g_variant_get_size (normal);
279   data = file_builder_allocate (fb, 8, size, pointer);
280   g_variant_store (normal, data);
281   g_variant_unref (normal);
282 }
283
284 static void
285 file_builder_add_options (FileBuilder         *fb,
286                           GVariant            *options,
287                           struct gvdb_pointer *pointer)
288 {
289   GVariant *normal;
290   gpointer data;
291   gsize size;
292
293   if (options)
294     {
295       if (fb->byteswap)
296         {
297           options = g_variant_byteswap (options);
298           normal = g_variant_get_normal_form (options);
299           g_variant_unref (options);
300         }
301       else
302         normal = g_variant_get_normal_form (options);
303
304       size = g_variant_get_size (normal);
305       data = file_builder_allocate (fb, 8, size, pointer);
306       g_variant_store (normal, data);
307       g_variant_unref (normal);
308     }
309 }
310
311 static void
312 file_builder_add_string (FileBuilder *fb,
313                          const gchar *string,
314                          guint32_le  *start,
315                          guint16_le  *size)
316 {
317   FileChunk *chunk;
318   gsize length;
319
320   length = strlen (string);
321
322   chunk = g_slice_new (FileChunk);
323   chunk->offset = fb->offset;
324   chunk->size = length;
325   chunk->data = g_malloc (length);
326   memcpy (chunk->data, string, length);
327
328   *start = guint32_to_le (fb->offset);
329   *size = guint16_to_le (length);
330   fb->offset += length;
331
332   g_queue_push_tail (fb->chunks, chunk);
333 }
334
335 static void
336 file_builder_allocate_for_hash (FileBuilder            *fb,
337                                 gsize                   n_buckets,
338                                 gsize                   n_items,
339                                 guint                   bloom_shift,
340                                 gsize                   n_bloom_words,
341                                 guint32_le            **bloom_filter,
342                                 guint32_le            **hash_buckets,
343                                 struct gvdb_hash_item **hash_items,
344                                 struct gvdb_pointer    *pointer)
345 {
346   guint32_le bloom_hdr, table_hdr;
347   guchar *data;
348   gsize size;
349
350   g_assert (n_bloom_words < (1u << 27));
351
352   bloom_hdr = guint32_to_le (bloom_shift << 27 | n_bloom_words);
353   table_hdr = guint32_to_le (n_buckets);
354
355   size = sizeof bloom_hdr + sizeof table_hdr +
356          n_bloom_words * sizeof (guint32_le) +
357          n_buckets     * sizeof (guint32_le) +
358          n_items       * sizeof (struct gvdb_hash_item);
359
360   data = file_builder_allocate (fb, 4, size, pointer);
361
362 #define chunk(s) (size -= (s), data += (s), data - (s))
363   memcpy (chunk (sizeof bloom_hdr), &bloom_hdr, sizeof bloom_hdr);
364   memcpy (chunk (sizeof table_hdr), &table_hdr, sizeof table_hdr);
365   *bloom_filter = (guint32_le *) chunk (n_bloom_words * sizeof (guint32_le));
366   *hash_buckets = (guint32_le *) chunk (n_buckets * sizeof (guint32_le));
367   *hash_items = (struct gvdb_hash_item *) chunk (n_items *
368                   sizeof (struct gvdb_hash_item));
369   g_assert (size == 0);
370 #undef chunk
371
372   memset (*bloom_filter, 0, n_bloom_words * sizeof (guint32_le));
373 }
374
375 static void
376 file_builder_add_hash (FileBuilder         *fb,
377                        GHashTable          *table,
378                        struct gvdb_pointer *pointer)
379 {
380   guint32_le *buckets, *bloom_filter;
381   struct gvdb_hash_item *items;
382   HashTable *mytable;
383   GvdbItem *item;
384   guint32 index;
385   gint bucket;
386
387   mytable = hash_table_new (g_hash_table_size (table));
388   g_hash_table_foreach (table, hash_table_insert, mytable);
389   index = 0;
390
391   for (bucket = 0; bucket < mytable->n_buckets; bucket++)
392     for (item = mytable->buckets[bucket]; item; item = item->next)
393       item->assigned_index = guint32_to_le (index++);
394
395   file_builder_allocate_for_hash (fb, mytable->n_buckets, index, 5, 0,
396                                   &bloom_filter, &buckets, &items, pointer);
397
398   index = 0;
399   for (bucket = 0; bucket < mytable->n_buckets; bucket++)
400     {
401       buckets[bucket] = guint32_to_le (index);
402
403       for (item = mytable->buckets[bucket]; item; item = item->next)
404         {
405           struct gvdb_hash_item *entry = items++;
406           const gchar *basename;
407
408           g_assert (index == guint32_from_le (item->assigned_index));
409           entry->hash_value = guint32_to_le (item->hash_value);
410           entry->parent = item_to_index (item->parent);
411           entry->unused = 0;
412
413           if (item->parent != NULL)
414             basename = item->key + strlen (item->parent->key);
415           else
416             basename = item->key;
417
418           file_builder_add_string (fb, basename,
419                                    &entry->key_start,
420                                    &entry->key_size);
421
422           if (item->value != NULL)
423             {
424               g_assert (item->child == NULL && item->table == NULL);
425
426               file_builder_add_value (fb, item->value, &entry->value.pointer);
427               file_builder_add_options (fb, item->options, &entry->options);
428               entry->type = 'v';
429             }
430
431           if (item->child != NULL)
432             {
433               guint32 children = 0;
434               guint32_le *offsets;
435               GvdbItem *child;
436
437               g_assert (item->table == NULL);
438
439               for (child = item->child; child; child = child->sibling)
440                 children++;
441
442               offsets = file_builder_allocate (fb, 4, 4 * children,
443                                                &entry->value.pointer);
444               entry->type = 'L';
445
446               for (child = item->child; child; child = child->sibling)
447                 offsets[--children] = child->assigned_index;
448
449               g_assert (children == 0);
450             }
451
452           if (item->table != NULL)
453             {
454               entry->type = 'H';
455               file_builder_add_hash (fb, item->table, &entry->value.pointer);
456             }
457
458           index++;
459         }
460     }
461 }
462
463 static FileBuilder *
464 file_builder_new (gboolean byteswap)
465 {
466   FileBuilder *builder;
467
468   builder = g_slice_new (FileBuilder);
469   builder->chunks = g_queue_new ();
470   builder->offset = sizeof (struct gvdb_header);
471   builder->byteswap = byteswap;
472
473   return builder;
474 }
475
476 static GString *
477 file_builder_serialise (FileBuilder          *fb,
478                         struct gvdb_pointer   root)
479 {
480   struct gvdb_header header = { { 0, }, };
481   GString *result;
482
483   if (fb->byteswap)
484     {
485       header.signature[0] = GVDB_SWAPPED_SIGNATURE0;
486       header.signature[1] = GVDB_SWAPPED_SIGNATURE1;
487     }
488   else
489     {
490       header.signature[0] = GVDB_SIGNATURE0;
491       header.signature[1] = GVDB_SIGNATURE1;
492     }
493
494   result = g_string_new (NULL);
495
496   header.root = root;
497   g_string_append_len (result, (gpointer) &header, sizeof header);
498
499   while (!g_queue_is_empty (fb->chunks))
500     {
501       FileChunk *chunk = g_queue_pop_head (fb->chunks);
502
503       if (result->len != chunk->offset)
504         {
505           gchar zero[8] = { 0, };
506
507           g_assert (chunk->offset > result->len);
508           g_assert (chunk->offset - result->len < 8);
509
510           g_string_append_len (result, zero, chunk->offset - result->len);
511           g_assert (result->len == chunk->offset);
512         }
513
514       g_string_append_len (result, chunk->data, chunk->size);
515       g_free (chunk->data);
516     }
517
518   g_queue_free (fb->chunks);
519   g_slice_free (FileBuilder, fb);
520
521   return result;
522 }
523
524 gboolean
525 gvdb_table_write_contents (GHashTable   *table,
526                            const gchar  *filename,
527                            gboolean      byteswap,
528                            GError      **error)
529 {
530   struct gvdb_pointer root;
531   gboolean status;
532   FileBuilder *fb;
533   GString *str;
534
535   fb = file_builder_new (byteswap);
536   file_builder_add_hash (fb, table, &root);
537   str = file_builder_serialise (fb, root);
538
539   status = g_file_set_contents (filename, str->str, str->len, error);
540   g_string_free (str, TRUE);
541
542   return status;
543 }