Leveldb源码分析之Slice

本文探讨了Leveldb中Slice数据结构的设计与使用,相较于string,Slice提供更低的开销,不包含实际数据,仅保存指向字节数组的指针。由于leveldb的key和value可能包含'',因此不适合用C风格的null终止字符串。Slice与C++ string之间可以方便地转换。文章还简要分析了Slice的构造函数及常用方法。
摘要由CSDN通过智能技术生成
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_); 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值