1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
20 #if __cplusplus >= 201703L
21 #include <string_view>
22 #endif // __cplusplus >= 201703L
24 #include "pw_string/util.h"
29 // Key is a simplified string_view used for KVS. This helps KVS work on
30 // platforms without C++17.
34 constexpr Key() : str_{nullptr}, length_{0} {}
35 constexpr Key(const Key&) = default;
36 constexpr Key(const char* str)
38 length_{string::Length(str, std::numeric_limits<size_t>::max())} {}
39 constexpr Key(const char* str, size_t len) : str_{str}, length_{len} {}
40 Key(const std::string& str) : str_{str.data()}, length_{str.length()} {}
42 #if __cplusplus >= 201703L
43 constexpr Key(const std::string_view& str)
44 : str_{str.data()}, length_{str.length()} {}
45 operator std::string_view() { return std::string_view{str_, length_}; }
46 #endif // __cplusplus >= 201703L
49 constexpr size_t size() const { return length_; }
50 constexpr size_t length() const { return length_; }
51 constexpr bool empty() const { return length_ == 0; }
54 constexpr const char& operator[](size_t pos) const { return str_[pos]; }
55 constexpr const char& at(size_t pos) const { return str_[pos]; }
56 constexpr const char& front() const { return str_[0]; }
57 constexpr const char& back() const { return str_[length_ - 1]; }
58 constexpr const char* data() const { return str_; }
61 constexpr const char* begin() const { return str_; }
62 constexpr const char* end() const { return str_ + length_; }
65 constexpr bool operator==(Key other_key) const {
66 return length() == other_key.length() &&
67 std::memcmp(str_, other_key.data(), length()) == 0;
71 constexpr bool operator!=(Key other_key) const {
72 return length() != other_key.length() ||
73 std::memcmp(str_, other_key.data(), length()) != 0;