leveldb源码学习 1 - Slice

作为levedb中的一个基本数据结构,Slice类是对字符数组指针和字符串长度的一个封装类。


1. 成员变量

Slice中有两个私有成员变量:

private:
  const char* data_;//指向一个外部字符数组指针
  size_t size_;//字符串长度

那为什么要定义Slice类,而不是直接用std::string呢?这里主要还是为了将提高存储效率,减少字符拷贝开销。


2 . 构造函数

Slice 定义了四个不同参数的构造函数:

Slice() : data_(""), size_(0) { }//创建空对象
Slice(const char* d, size_t n) : data_(d), size_(n) { }//参数为字符数组指针和长度
Slice(const std::string& s) : data_(s.data()), size_(s.size()) { }//参数为string字符串及长度
Slice(const char* s) : data_(s), size_(strlen(s)) { }//参数为字符数组指针


3. 成员函数

const char* data() const { return data_; }//返回字符数组指针
size_t size() const { return size_; }//返回字符串的大小
bool empty() const { return size_ == 0; }//返回空字符串
void clear() { data_ = ""; size_ = 0; }//清空字符串

std::string ToString() const { return std::string(data_, size_); }//转换成字符串string类型。std::string类的构造函数string( const char *str, size_type length );

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

bool starts_with(const Slice& x) const {//判断Slice对象x,是否与当前对象的字符前x.size()个相同,x.size()<=this.size()
    return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
}

inline int Slice::compare(const Slice& b) const {//Slice的内联函数,比较两个Slice对象。
  const int min_len = (size_ < b.size_) ? size_ : b.size_;
  int r = memcmp(data_, b.data_, min_len);//r>0,则this>b;r<0,则this<b
  if (r == 0) {
    if (size_ < b.size_) r = -1;
    else if (size_ > b.size_) r = +1;//this对象的字符数组包含b,返回+1;
  }
  return r;
}
4. 不属于Slice类,但是在Slice.h中定义的leveldb命名空间的其他内联函数
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);
}



参考资料:

http://blog.csdn.net/sparkliang/article/details/8567602

http://blog.csdn.net/tankles/article/details/7663311

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值