glib库中的哈希函数和比较函数

哈希表是一种提供 key-value 访问的数据结构,通过指定的 key 值可以快速的访问到与它相关联的 value 值。 hash 表的一种典型用法就是字典,通过单词的首字母能够快速的找到单词。关于哈希表的详细介绍请查阅数据结构的相关书籍,我这里只介绍 glib 库中哈希表的哈希函数和比较函数。

主要包括针对int, int64, double, string四种数据类型的处理。详细请看下面的代码。

 

typedef char   gchar;

typedef short  gshort;

typedef long   glong;

typedef int    gint;

typedef gint   gboolean;

 

typedef unsigned char   guchar;

typedef unsigned short  gushort;

typedef unsigned long   gulong;

typedef unsigned int    guint;

 

typedef float   gfloat;

typedef double  gdouble;

/* Define min and max constants for the fixed size numerical types */

#define G_MININT8 ((gint8)  0x80)

#define G_MAXINT8 ((gint8)  0x7f)

#define G_MAXUINT8   ((guint8) 0xff)

 

#define G_MININT16   ((gint16)  0x8000)

#define G_MAXINT16   ((gint16)  0x7fff)

#define G_MAXUINT16  ((guint16) 0xffff)

 

#define G_MININT32   ((gint32)  0x80000000)

#define G_MAXINT32   ((gint32)  0x7fffffff)

#define G_MAXUINT32  ((guint32) 0xffffffff)

 

#define G_MININT64   ((gint64) G_GINT64_CONSTANT(0x8000000000000000))

#define G_MAXINT64   G_GINT64_CONSTANT(0x7fffffffffffffff)

#define G_MAXUINT64  G_GINT64_CONSTANT(0xffffffffffffffffU)

 

typedef void* gpointer;

typedef const void *gconstpointer;

 

gboolean

g_int_equal (gconstpointer v1,

        gconstpointer v2)

{

  return *((const gint*) v1) == *((constgint*) v2);

}

 

guint

g_int_hash (gconstpointer v)

{

  return *(const gint*) v;

}

 

gboolean

g_int64_equal (gconstpointer v1,

               gconstpointer v2)

{

  return *((const gint64*) v1) == *((constgint64*) v2);

}

 

guint

g_int64_hash (gconstpointer v)

{

  return (guint) *(constgint64*) v;

}

 

gboolean

g_double_equal (gconstpointer v1,

                gconstpointer v2)

{

  return *((const gdouble*) v1) == *((constgdouble*) v2);

}

 

guint

g_double_hash (gconstpointer v)

{

  return (guint) *(constgdouble*) v;

}

 

gboolean

g_str_equal (gconstpointer v1,

        gconstpointer v2)

{

  const gchar *string1 = v1;

  const gchar *string2 = v2;

 

  return strcmp (string1, string2) == 0;

}

 

guint

g_str_hash (gconstpointer v)

{

  /* 31 bit hash function */

  const signed char *p = v;

  guint32 h = *p;

 

  if (h)

    for (p += 1; *p != '\0'; p++)

      h = (h << 5) - h + *p;

 

  return h;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值