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_