-
Notifications
You must be signed in to change notification settings - Fork 1
/
slice.h
56 lines (40 loc) · 1.26 KB
/
slice.h
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
#pragma once
#include <cassert>
#include <cstddef>
#include <cstring>
#include <string>
#include <type_traits>
namespace open_hikv {
class Slice {
private:
const char* data_ = "";
size_t size_ = 0;
public:
Slice() = default;
Slice(const char* d, size_t n) : data_(d), size_(n) {}
template <typename T>
Slice(const T* s, size_t n) : Slice(reinterpret_cast<const char*>(s), n) {
static_assert(sizeof(T) == sizeof(char), "");
}
Slice(const std::string& s) : Slice(s.data(), s.size()) {}
template <typename T, typename = std::enable_if_t<
std::is_convertible<T, const char*>::value>>
Slice(T s) : data_(s), size_(strlen(s)) {}
template <size_t L>
Slice(const char (&s)[L]) : data_(s), size_(L - 1) {}
public:
// same as STL
const char* data() const { return data_; }
// same as STL
size_t size() const { return size_; }
const char& operator[](size_t n) const {
assert(n < size_);
return data_[n];
}
bool operator==(const Slice& another) const {
return size_ == another.size_ && memcmp(data_, another.data_, size_) == 0;
}
bool operator!=(const Slice& another) const { return !operator==(another); }
std::string ToString() const { return {data_, size_}; }
};
} // namespace open_hikv