Leveldb源码分析--4

4 Memtable之2

4.6 Comparator

弄清楚了key,接下来就要看看key的使用了,先从Comparator开始分析。首先Comparator是一个抽象类,导出了几个接口。

其中Name()Compare()接口都很明了,另外的两个Find xxx接口都有什么功能呢,直接看程序注释:

  // Advanced functions: these are used to reduce the space requirements
  // for internal data structures like index blocks.
  // 这两个函数:用于减少像index blocks这样的内部数据结构占用的空间
  // 其中的*start和*key参数都是IN OUT的。

  // If *start < limit, changes *start to a short string in [start,limit).
  // Simple comparator implementations may return with *start unchanged,
  // i.e., an implementation of this method that does nothing is correct.
  // 这个函数的作用就是:如果*start < limit,就在[start,limit)中找到一个
  // 短字符串,并赋给*start返回
  // 简单的comparator实现可能不改变*start,这也是正确的
  virtual void FindShortestSeparator(std::string* start, const Slice& limit) const = 0;

  // Changes *key to a short string >= *key.
  // Simple comparator implementations may return with *key unchanged,
  // i.e., an implementation of this method that does nothing is correct.
  //这个函数的作用就是:找一个>= *key的短字符串
  //简单的comparator实现可能不改变*key,这也是正确的
  virtual void FindShortSuccessor(std::string* key) const = 0;

其中的实现类有两个,一个是内置的BytewiseComparatorImpl,另一个是InternalKeyComparator。下面分别来分析。

4.6.1 BytewiseComparatorImpl

首先是重载的Name和比较函数,比较函数如其名,就是字符串比较,如下:

virtual const char* Name() const {return"leveldb.BytewiseComparator";}

virtual int Compare(const Slice& a, const Slice& b) const {return a.compare(b);}

再来看看Byte wisecomparator是如何实现FindShortestSeparator()的,没什么特别的,代码+注释如下:

virtual void FindShortestSeparator(std::string* start, const Slice& limit) const 
{
    // 首先计算共同前缀字符串的长度
     size_t min_length = std::min(start->size(), limit.size());
    size_t diff_index = 0;
    while ((diff_index < min_length) && ((*start)[diff_index] == limit[diff_index])) {
      diff_index++;
    }
    if (diff_index >= min_length) {
      // 说明*sta
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值