leveldb源码学习之基本数据结构Slice

slice用于表示字符串,包括length和一个指向外部字节数组的指针。和string一样,允许字符串中包含’\0’。

提供一些基本接口,可以把const char*和string转换为Slice;把Slice转换为string,取得数据指针const char*。

include/leveldb/slice.h

// Slice 是一个简单的结构,包含一个指向外部存储的指针,和一个size
// Slice 在使用中必须保证指向的外部存储没有被释放
// 多线程可以对同一个Slice调用const函数而不借助外部同步机制,若调用非const函数则需要同步机制

#ifndef STORAGE_LEVELDB_INCLUDE_SLICE_H_
#define STORAGE_LEVELDB_INCLUDE_SLICE_H_

#include <assert.h>
#include <stddef.h>
#include <string.h>

#include <string>

#include "leveldb/export.h"

namespace leveldb {

class LEVELDB_EXPORT Slice {
 public:
  // 创建空的 slice.
  Slice() : data_(""), size_(0) {}

  // 创建指向 d[0,n-1] 的slice.
  Slice(const char* d, size_t n) : data_(d), size_(n) {}

  // 创建指向 "s" 内容的slice
  Slice(const std::string& s) : data_(s.data()), size_(s.size()) {}

  // 创建指向 s[0,strlen(s)-1]的 slice
  Slice(const char* s) : data_(s), size_(strlen(s)) {}

  // 可拷贝.
  Slice(const Slice&) = default;
  Slice& operator=(const Slice&) = default;

  // 返回引用的字符串起始地址
  const char* data() const { return data_; }

  // 返回引用的字符串长度(字节数)
  size_t size() const { return size_; }

  // 若引用的字符串长度为0 返回true
  bool empty() const { return size_ == 0; }

  // 返回引用字符串的第i字节.
  // REQUIRES: n < size()
  char operator[](size_t n) const {
    assert(n < size());
    return data_[n];
  }

  // 清空slice
  void clear() {
    data_ = "";
    size_ = 0;
  }

  // 将开头n个字节丢弃.
  void remove_prefix(size_t n) {
    assert(n <= size());
    data_ += n;
    size_ -= n;
  }

  // 返回具有引用字符串的一个副本的string.
  std::string ToString() const { return std::string(data_, size_); }

  // 不同清空的比较返回值:
  //   <  0 iff "*this" <  "b",
  //   == 0 iff "*this" == "b",
  //   >  0 iff "*this" >  "b"
  int compare(const Slice& b) const;

  // 若本字符串以 "x" 开头返回true
  bool starts_with(const Slice& x) const {
    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) {
    if (size_ < b.size_)
      r = -1;
    else if (size_ > b.size_)
      r = +1;
  }
  return r;
}

}  // namespace leveldb

#endif  // STORAGE_LEVELDB_INCLUDE_SLICE_H_

 

Leveldb源码分析

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章