内容简介: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;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Domain-Driven Design
Eric Evans / Addison-Wesley Professional / 2003-8-30 / USD 74.99
"Eric Evans has written a fantastic book on how you can make the design of your software match your mental model of the problem domain you are addressing. "His book is very compatible with XP. It is n......一起来看看 《Domain-Driven Design》 这本书的介绍吧!