LevelDB 源码分析(四):Slice

栏目: 数据库 · 发布时间: 7年前

内容简介:LevelDB 源码分析(四):Slice

LevelDB 中的字符串并没有使用 std:string ,而是将其封装成了Slice类, Slice 是非常简单的数据结构,它包括 size (字符串的长度)和一个指向外部字节数组的指针。

返回一个 Slice 比返回 std:string 更加方便,因为我们不需要去复制大量原始的key和value的数据。

使用 slice 之前必须要保证 slice 中指针指向的内存没有被收回。

源码: include/leveldb/slice.h

class Slice {
public:
// 创建一个空的slice
Slice() : data_(""), size_(0) { }

// 根据字符数组d[0,n-1]创建一个Slice
Slice(const char* d, size_t n) : data_(d), size_(n) { }

// 根据string类型的"s"创建一个Slice
Slice(const std::string& s) : data_(s.data()), size_(s.size()) { }

// 根据字符数组s[0, strlen(s)-1]创建一个Slice
Slice(const char* s) : data_(s), size_(strlen(s)) { }

// 返回数据的首地址
const char* data() const { return data_; }

// 返回数据的长度(单位为字节)
size_t size() const { return size_; }

// 判断数据是否为空
bool empty() const { return size_ == 0; }

// 返回第n个字节的字符
char operator[](size_t n) const {
assert(n < size());
return data_[n];
}

// 将slice重置成空
void clear() { data_ = ""; size_ = 0; }

// 删除前n个字节
void remove_prefix(size_t n) {
assert(n <= size());
data_ += n;
size_ -= n;
}

// 返回一个string类型的字符串
std::string ToString() const { return std::string(data_, size_); }

// 比较两个slice
// if "*this" < "b", return < 0;
// if "*this" == "b", return == 0;
// if "*this" > "b", return >0 .
int compare(const Slice& b) const;

// 判断当前slice的字符串是否是以x的字符串为首
bool starts_with(const Slice& x) const {
return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
}

private:
const char* data_;
size_t size_;

// Intentionally copyable
};

// slice == 运算符重载
inline bool operator==(const Slice& x, const Slice& y) {
return ((x.size() == y.size()) && (memcmp(x.data(), y.data(), x.size()) == 0));
}

inline bool operator!=(const Slice& x, const Slice& y) {
return !(x == y);
}

// 比较函数
inline int Slice::compare(const Slice& b) const {
const size_t min_len = (size_ < b.size_) ? size_ : b.size_;
int r = memcmp(data_, b.data_, min_len);
if (r == 0) {
if (size_ < b.size_)
r = -1;
else if (size_ > b.size_)
r = +1;
}
return r;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

分享经济的爆发

分享经济的爆发

阿鲁·萨丹拉彻 / 周恂 / 文汇出版社 / 2017-4-1 / 59.00元

◆了解分享经济,读这本就够了!解读了全球几乎所有成功的分享经济案例。 ◆国家多次提出“发展分享经济”“分享经济是经济新常态的国家战略”。 ◆全球分享经济泰斗揭示分享经济将从哪些方面重构我们的生活。 ◆作者是分享经济领域的泰斗,纽约大学斯特恩商学院教授。 ◆全球分享经济理论热门著作! ◆滴滴CEO程维亲自作序力荐! ◆谷歌、《时代周刊》、《 纽约时报》、《华尔街日......一起来看看 《分享经济的爆发》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具