leveldb_slice

Slice切片。切片是一种简单的数据结构,包含指向数据的指针和数据的大小。

多个线程可以在没有外部同步的情况下在Slice上调用const方法,但是如果任何线程可以调用非const方法,则访问同一Slice的所有线程都必须使用外部同步。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
//
// Created by Dell on 2023/3/10.
//

#ifndef LEVELDB_SLICE_H
#define LEVELDB_SLICE_H

#include <cassert>
#include <cstddef>
#include <cstring>
#include <string>

namespace leveldb {

class Slice {

public:
// TODO
// 无参构造函数
Slice() : data_(""), size_(0) {}
// 有参构造函数
Slice(const char* d, size_t n) : data_(d), size_(n) {}
// 通过string构造
Slice(const std::string& s) : data_(s.data()), size_(s.size()) {}
// 通过char* 构造
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_; }
// 判断slice是否为空
bool empty() { return size_ == 0; }
// 清空slice
void clear() {
data_ = "";
size_ = 0;
}
// 将slice转化为string
std::string ToString() const { return std::string(data_, size_); }
// 比较slice的前缀是否为x
bool starts_with(const Slice& x) const {
return ((size_ > x.size_) && (memcmp(data_, x.data_, x.size_) == 0));
}
// 移除长度为n的前缀
void remove_prefix(size_t n) {
assert(n <= size_);
data_ += n;
size_ -= n;
}
// 比较两个slice
int compare(const Slice& b) const;
// 重载取值运算符
char operator[](size_t n) const {
assert(n <= size_);
return data_[n];
}


private:
// 数据
const char* data_;
// 大小
size_t size_;
};

// 重载==运算符
inline bool operator==(const Slice& x, const Slice& y) {
// 两个slice相等:大小相等且数据相等
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); // 比较前min_len个数据大小
if (r == 0) {
// 如果前min_len个数据相等,长度大的大
if (size_ < b.size_)
r = -1;
else if (size_ > b.size_)
r = +1;
}

return r;
}

};

#endif //LEVELDB_SLICE_H

/**

#define PTR char*

int memcmp(const PTR str1, const PTR str2, size_t count) {
// register 放到寄存器
register const unsigned char *s1 = (const unsigned char*)str1;
register const unsigned char *s2 = (const unsigned char*)str2;

while (count -- > 0) {
if (*s1 ++ == *s2 ++)
return s1[-1] < s2[-1] ? -1 : 1;
}

return 0;
}

**/

0%