LevelDB slice

2021-04-08  本文已影响0人  wayyyy

LevelDB里面主要用到的字符串类型不是C语言的char [],也不是C++的string对象,而是自己封装的一个简单的数据结构Slice。其类似的设计思想是 c++14 的 string_view

Slice是一个简单的对象,只包含了指向字符串的指针和字符串的长度。为什么使用Slice而不使用char []或者string呢?有以下原因:

无标题.png

使用Slice需要特别小心,使用者需要确保底层引用的字符串没有被销毁。

class 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"
    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)) {}

    // 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()
    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.
    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"
    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;
}
测试

参考资料

  1. https://zhuanlan.zhihu.com/p/219788172
上一篇下一篇

猜你喜欢

热点阅读