【LevelDB】【include】Slice类解析

发布时间 2023-12-16 21:04:32作者: 静塘花开

Slice类

  Slice类是对字符串的封装,设计思想与std::string_view相似。

  源文件位置

    include/leveldb/slice.h

  优点:

    1、拷贝速度快,Slice的拷贝仅需拷贝数据指针和数据长度

    2、多个Slice可指向同个字符串,减少资源开销

    3、支持std::string、char[]、Slice间的快速转换

  注意:

    1、空Slice的data_并非为空指针,而是为空字符串,因此判断Slice是否为空应根据empty()接口判断

    2、使用Slice期间需要保证Slice底层引用的字符串未被销毁

公共接口

  // 返回数据指针
  // 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;

  // 判断Slice是否为空
  // Return true iff the length of the referenced data is zero
  bool empty() const;

  // 清空Slice
  // Change this slice to refer to an empty array
  void clear();

  // 丢弃指定长度的前缀(不对底层字符串做改动,仅修改Slice自身的指针和长度)
  // Drop the first "n" bytes from this slice.
  void remove_prefix(size_t n);

  // 通过Slice构造std::string对象
  // Return a string that contains the copy of the referenced data.
  std::string ToString() const;

  // 比较Slice,内部调用memcmp
  // Three-way comparison.  Returns value:
  //   <  0 iff "*this" <  "b",
  //   == 0 iff "*this" == "b",
  //   >  0 iff "*this" >  "b"
  int compare(const Slice& b) const;

  // 判断此Slice是否以x为前缀
  // Return true iff "x" is a prefix of "*this"
  bool starts_with(const Slice& x);

私有成员变量

  const char* data_; // 数据指针
  size_t size_; // 数据长度

构造函数/运算符重载

  // Create an empty slice.
  Slice() : data_(""), size_(0) {}

  // 用以支持通过底层为char[]的字符串构造Slice
  // Create a slice that refers to d[0,n-1].
  Slice(const char* d, size_t n) : data_(d), size_(n) {}

  // 用以支持通过底层为std::string的字符串构造Slice
  // Create a slice that refers to the contents of "s"
  Slice(const std::string& s);

  // 等同于Slice(const char* d, size_t n),将自动通过strlen获取字符串长度
  // Create a slice that refers to s[0,strlen(s)-1]
  Slice(const char* s);

  // 浅拷贝,仅拷贝指针和长度,引用同个底层char[]/std::string
  // Intentionally copyable.
  Slice(const Slice&) = default;
  Slice& operator=(const Slice&) = default;
 
  // 用以使Slice支持[]索引
  // Return the ith byte in the referenced data.
  // REQUIRES: n < size()
  char operator[](size_t n) const;
 
  // 用以使Slice支持==运算符
  inline bool operator==(const Slice& x, const Slice& y);
 
  // 用以使Slice支持!=运算符
  inline bool operator!=(const Slice& x, const Slice& y);