Search code examples
clinuxhashtableglibc

GHashTable that using uint64_t as key and a struct as value


I am studying the GHashTable. Though there are already some examples in Stackoverflow, they are just some common case. So I am still not sure how to implement my requirements and decide to ask for help.
I want to use a uint64_t as key and a struct as value. I find that there is no such built-in hash function in GLib. There is just a g_int64_hash(). Though the key is uint64_t, it will just be about 52 bits. So I think gint64 is OK. But I see some examples using GINT_TO_POINTER() to convert the value (and sometimes they didn't). So just be confused about this.
Thanks very much!


Solution

  • See in ghash.c how g_int64_hash and g_int64_equal are implemented:

    ...
    gboolean
    g_int64_equal (gconstpointer v1,
                   gconstpointer v2)
    {
      return *((const gint64*) v1) == *((const gint64*) v2);
    }
    ...
    guint
    g_int64_hash (gconstpointer v)
    {
      return (guint) *(const gint64*) v;
    }
    ...
    

    You can write your won uint64_t_hash and uint64_equal similarly:

    gboolean
    uint64_t_equal (gconstpointer v1,
                    gconstpointer v2)
    {
      return *((const uint64_t*) v1) == *((const uint64_t*) v2);
    }
    
    guint
    uint64_t_hash (gconstpointer v)
    {
      return (guint) *(const uint64_t*) v;
    }
    

    See an example:

    #include <glib.h>
    #include <stdio.h>
    #include <inttypes.h>
    
    /* the value structure */
    typedef struct __MyStruct
    {
      int a;
      int b;
    } MyStruct;
    
    /* the hash equality function */
    static gboolean
    uint64_t_equal (gconstpointer v1,
                    gconstpointer v2)
    {
      return *((const uint64_t*) v1) == *((const uint64_t*) v2);
    }
    
    /* the hash function */
    static guint
    uint64_t_hash (gconstpointer v)
    {
      return (guint) *(const uint64_t*) v;
    }
    
    /* the hash function */
    static void
    print_hash(gpointer key,
               gpointer value,
               gpointer user_data)
    {
      printf("%" PRIu64 " = {%d, %d}\n",
        *(uint64_t*) key, ((MyStruct *) value)->a, ((MyStruct *) value)->b);
    }
    
    int
    main(int argc, char **argv)
    {
      GHashTable *hash;
    
      /* key => value */
      uint64_t k1 = 11; MyStruct s1 = {1, 11};
      uint64_t k2 = 22; MyStruct s2 = {2, 22};
      uint64_t k3 = 33; MyStruct s3 = {3, 33};
    
      hash = g_hash_table_new(uint64_t_hash, uint64_t_equal);
    
      /* insert values */
      g_hash_table_insert(hash, &k1, &s1);
      g_hash_table_insert(hash, &k2, &s2);
      g_hash_table_insert(hash, &k3, &s3);
    
      /* iterate over the values in the hash table */
      g_hash_table_foreach(hash, print_hash, NULL);
      g_hash_table_destroy(hash);
      return 0;
    }