sqlite源码剖析(一)

首先,我看完整个目录结构之后,我打算从sqlite的数据结构开始看起。
hash.h中定义了两个数据结构,Hash类包含以下成员

struct Hash {
  char keyClass;          /* 指示该hash是针对哪种基本类型而设置的,其设定4种 SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
  char copyKey;           /* 判断每个元素是否需要深复制,如pointer类型、binary类型都需要*/
  int count;              /*哈希表中的总元素个数*/
  HashElem *first;        /*哈希目录的首地址*/
  void *(*xMalloc)(int);  /*动态分配的函数指针*/
  void (*xFree)(void *);  /*释放内存的函数指针*/
  int htsize;             /* 桶的个数 */
  struct _ht {            /* 哈希桶*/
    int count;               /* 该桶的元素个数 */
    HashElem *chain;         /* 该桶的首指针 */
  } *ht;
};

其中copyKey判断HashElem类中的键指针是否需要深复制。
HashElem类包含以下成员

struct HashElem {
  HashElem *next, *prev;   /* 桶中指向下一个及前一个的指针 */
  void *data;              /* 存储的内容 */
  void *pKey; int nKey;    /* pKey指键内容,nKey指键长度 */
};

其中data并没有动态分配内存,而单纯是一个指针。
hash.c除了添加、查找、移除函数之外,还添加了几个比较函数,及哈希函数。

static int binHash(const void *pKey, int nKey);
static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2);
static int strHash(const void *pKey, int nKey);
static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2);
static int ptrHash(const void *pKey, int nKey);
static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2);
static int intHash(const void *pKey, int nKey);
static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2);

除了这些函数之外,他还给了两个函数,以保证使用Hash类的用户不用考虑调用哪个函数问题,实现更好的封装性。

static int (*compareFunction(int keyClass))(const void*,int,const void*,int);//通过判断keyClass,返回一个比较函数指针
static int (*hashFunction(int keyClass))(const void*,int);//通过判断keyClass,返回一个hash函数指针

这里的hash结构写的非常简洁易懂,还实现较好的封装性,并同时不用声明不同类型的hash结构,直接使用一个变量keyclass及void *完美解决该问题。
用c++实现应该可以用函数模版来解决该问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值