levelDB数据结构之slice

levelDB数据结构之slice

//两个数据成员
//char *data_ 真正的数据
//size_t size_ char*数据成员的长度
#include <cassert>
#include <cstddef>
#include <cstring>
#include <string>

#include "leveldb/export.h"

namespace leveldb {

class LEVELDB_EXPORT Slice {
 public:
  // 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"
  // std::string.data()的返回值就是数据的char*
  Slice(const std::string& s) : data_(s.data()), size_(s.size()) {}

  // Create a slice that refers to s[0,strlen(s)-1]
  // strlen的返回值是char*数据的长度,其中不包含'\0',例如"abc"的strlen返回值是3
  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()
  // 获取第n个字节的字符,因为这里返回的不是引用,而是char类型的值,所以不能通过[]去修改slice的值
  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.
  // 将slice变成std::string,实质上是用char*来构造string
  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;

  // Return true iff "x" is a prefix of "*this"
  // 判断x是不是*this的前缀
  bool starts_with(const Slice& x) const {
    // memcmp比较的是char*里面的值,而不是char*地址
    return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
  }

 private:
  const char* data_;
  size_t size_;
};
// 运算符重载
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); }

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) {
    // 说明长度短的那个是长度长的那个slice的前缀
    // 那么较长的就更大,较短的更小
    if (size_ < b.size_)
      r = -1;
    else if (size_ > b.size_)
      r = +1;
  }
  return r;
}
上一篇:Go语言快速入门(1)--复合数据类型(1) - 数组、slice


下一篇:JS查询页面是否被百度收录,没有收录则显示搜索链接