【LevelDB源码阅读】Slice
是什么
slice是对字符串的封装,包括一个字符指针和一个字符串长度,相当于c++中std::string。
为什么要用
- 开销小,直接操作指针避免不必要的数据拷贝
学到什么
- int memcmp(const void *str1, const void *str2, size_t n):比较str1和str2两个内存块前n个字符
- operator!=通过operator==实现
- 使用=default来显示要求编译器生成合成版本成员函数
- 用const修饰不修改数据成员的函数和不修改的形参变量
- inline机制优化规模小、流程直接、频繁调用的函数,避免函数调用开销
源码分析
- 构造函数
// Create an empty slice.
Slice() : data_(""), size_(0) {}
// Create a slice that refers to d[0,n-1].
Slice(const char *d, size_t n) : data_(d), size_(n) {}
// Create a slice that refers to the contents of "s"
Slice(const std::string &s) : data_(s.data()), size_(s.size()) {}
// Create a slice that refers to s[0,strlen(s)-1]
Slice(const char *s) : data_(s), size_(strlen(s)) {}
- 拷贝构造和拷贝赋值
// Intentionally copyable.
Slice(const Slice &) = default;
Slice& operator=(const Slice &) = default;
- 查询
// Return a pointer to the beginning of the referenced data
const char* data() const { return data_; }
// Return the length (in bytes) of the referenced data
size_t size() const { return size_; }
// Return true iff the length of the referenced data is zero
bool empty() const { return size_ == 0; }
// Return the ith byte in the referenced data.
// REQUIRES: n < size()
char operator[](size_t n) const {
assert(n < size());
return data_[n];
}
- 修改
// Change this slice to refer to an empty array
void clear() {
data_ = "";
size_ = 0;
}
// Drop the first "n" bytes from this slice.
void remove_prefix(size_t n) {
assert(n <= size());
data_ += n;
size_ -= n;
}
- 输出
// Return a string that contains the copy of the referenced data.
std::string ToString() const { return std::string(data_, size_); }
- 比较及其实现
// Three-way comparison. Returns value:
// < 0 iff "*this" < "b",
// == 0 iff "*this" == "b",
// > 0 iff "*this" > "b"
int compare(const Slice &b) const;
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;
}
- 其它有用函数
// Return true iff "x" is a prefix of "*this"
bool starts_with(const Slice &x) const {
return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
}
- 重载操作符
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); }