1 // Copyright 2020 The Pigweed Authors 2 // 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 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 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 13 // the License. 14 #pragma once 15 16 #include <cstring> 17 #include <limits> 18 #include <string> 19 20 #if __cplusplus >= 201703L 21 #include <string_view> 22 #endif // __cplusplus >= 201703L 23 24 #include "pw_string/util.h" 25 26 namespace pw { 27 namespace kvs { 28 29 // Key is a simplified string_view used for KVS. This helps KVS work on 30 // platforms without C++17. 31 class Key { 32 public: 33 // Constructors Key()34 constexpr Key() : str_{nullptr}, length_{0} {} 35 constexpr Key(const Key&) = default; Key(const char * str)36 constexpr Key(const char* str) 37 : str_{str}, 38 length_{string::Length(str, std::numeric_limits<size_t>::max())} {} Key(const char * str,size_t len)39 constexpr Key(const char* str, size_t len) : str_{str}, length_{len} {} Key(const std::string & str)40 Key(const std::string& str) : str_{str.data()}, length_{str.length()} {} 41 42 #if __cplusplus >= 201703L Key(const std::string_view & str)43 constexpr Key(const std::string_view& str) 44 : str_{str.data()}, length_{str.length()} {} string_view()45 operator std::string_view() { return std::string_view{str_, length_}; } 46 #endif // __cplusplus >= 201703L 47 48 // Traits size()49 constexpr size_t size() const { return length_; } length()50 constexpr size_t length() const { return length_; } empty()51 constexpr bool empty() const { return length_ == 0; } 52 53 // Access 54 constexpr const char& operator[](size_t pos) const { return str_[pos]; } at(size_t pos)55 constexpr const char& at(size_t pos) const { return str_[pos]; } front()56 constexpr const char& front() const { return str_[0]; } back()57 constexpr const char& back() const { return str_[length_ - 1]; } data()58 constexpr const char* data() const { return str_; } 59 60 // Iterator begin()61 constexpr const char* begin() const { return str_; } end()62 constexpr const char* end() const { return str_ + length_; } 63 64 // Equal 65 constexpr bool operator==(Key other_key) const { 66 return length() == other_key.length() && 67 std::memcmp(str_, other_key.data(), length()) == 0; 68 } 69 70 // Not Equal 71 constexpr bool operator!=(Key other_key) const { 72 return length() != other_key.length() || 73 std::memcmp(str_, other_key.data(), length()) != 0; 74 } 75 76 private: 77 const char* str_; 78 size_t length_; 79 }; 80 81 } // namespace kvs 82 } // namespace pw 83