Leveldb源码分析之Slice

来源:互联网 发布:锥套皮带轮锥度算法 编辑:程序博客网 时间:2024/05/22 02:16
Leveldb源码分析之Slice

Slice非常简单的数据结构,它包括length和一个指向外部字节数组的指针。
为什么使用Slice,而不直接使用string呢??

  1. 相比返回string,返回Slice的开销会小的多(没有拷贝,Slice中没有实际数据,只有指向数据的指针,开销低)。
  2. leveldb允许key和value包含'\0',不能返回以null结尾的c风格字符串。

C++ string和以null结尾的C风格字符串可以很方便的转换成Slice:

   leveldb::Slice s1 = "hello";    std::string str("world");   leveldb::Slice s2 = str;

Slice也很容易转换成C++风格string:

   std::string str = s1.ToString();   assert(str == std::string("hello"));

使用Slice时需要格外小心,因为Slice引用的外部数组是由Slice的使用者保证在slice的生命周期内外部数组是有效的。比如下面的代码中存在bug:

   leveldb::Slice slice;   if (...) {     std::string str = ...;     slice = str;   }   Use(slice);

当if语句的作用域结束时,str会被析构,slice指向的外部空间就不存在了。

下面进行Slice代码的分析:Slice的代码非常简单:
构造函数:能够用c++ string,c string初始化。

  // Create an empty slice.  Slice() : data_(""), size_(0) { }   // Create a slice that refers to data[0,n-1].  Slice(const char* data, size_t n) : data_(data), 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)) { }

常用方法:

  // 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];  }  // Return a string that contains the copy of the referenced data.  std::string ToString() const { return std::string(data_, size_); 

0 0
原创粉丝点击