4 Memtable之2
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 wise的comparator是如何实现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