Implement a rangeset data type and use it to track items in log segments.
[bluesky.git] / bluesky / util.c
index c4bac19..be378ef 100644 (file)
@@ -53,17 +53,6 @@ gboolean bluesky_inode_is_ready(BlueSkyInode *inode)
 
 /**** Reference-counted strings. ****/
 
-void bluesky_mmap_unref(BlueSkyMmap *mmap)
-{
-    if (mmap == NULL)
-        return;
-
-    if (g_atomic_int_dec_and_test(&mmap->refcount)) {
-        munmap((void *)mmap->addr, mmap->len);
-        g_free(mmap);
-    }
-}
-
 /* Create and return a new reference-counted string.  The reference count is
  * initially one.  The newly-returned string takes ownership of the memory
  * pointed at by data, and will call g_free on it when the reference count
@@ -86,12 +75,14 @@ BlueSkyRCStr *bluesky_string_new_from_gstring(GString *s)
 }
 
 /* Create a new BlueSkyRCStr from a memory-mapped buffer. */
-BlueSkyRCStr *bluesky_string_new_from_mmap(BlueSkyMmap *mmap,
+BlueSkyRCStr *bluesky_string_new_from_mmap(BlueSkyCacheFile *mmap,
                                            int offset, gsize len)
 {
+    g_assert(offset + len <= mmap->len);
+
     BlueSkyRCStr *string = g_new(BlueSkyRCStr, 1);
     string->mmap = mmap;
-    g_atomic_int_inc(&mmap->refcount);
+    g_atomic_int_inc(&mmap->mapcount);
     string->data = (char *)mmap->addr + offset;
     string->len = len;
     g_atomic_int_set(&string->refcount, 1);
@@ -228,3 +219,40 @@ BlueSkyInode *bluesky_list_tail(GList *head)
     else
         return (BlueSkyInode *)head->prev->data;
 }
+
+/**** Range sets. ****/
+
+/* These are a data structure which can track a set of discontiguous integer
+ * ranges--such as the partitioning of the inode number space or the bytes in a
+ * log file into objects.  This current prototype implementation just tracks
+ * the starting offset with a hash table and doesn't track the length, but
+ * should be extended later to track properly. */
+
+struct BlueSkyRangeset {
+    GHashTable *hashtable;
+};
+
+BlueSkyRangeset *bluesky_rangeset_new()
+{
+    BlueSkyRangeset *rangeset = g_new(BlueSkyRangeset, 1);
+    rangeset->hashtable = g_hash_table_new(g_direct_hash, g_direct_equal);
+    return rangeset;
+}
+
+void bluesky_rangeset_free(BlueSkyRangeset *rangeset)
+{
+    g_hash_table_unref(rangeset->hashtable);
+    g_free(rangeset);
+}
+
+gboolean bluesky_rangeset_insert(BlueSkyRangeset *rangeset,
+                                 int start, int length, gpointer data)
+{
+    g_hash_table_insert(rangeset->hashtable, GINT_TO_POINTER(start), data);
+    return TRUE;
+}
+
+gpointer bluesky_rangeset_lookup(BlueSkyRangeset *rangeset, int start)
+{
+    return g_hash_table_lookup(rangeset->hashtable, GINT_TO_POINTER(start));
+}