Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_kvs / public / pw_kvs / key.h
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
34   constexpr Key() : str_{nullptr}, length_{0} {}
35   constexpr Key(const Key&) = default;
36   constexpr Key(const char* str)
37       : str_{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()} {}
41
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
47
48   // Traits
49   constexpr size_t size() const { return length_; }
50   constexpr size_t length() const { return length_; }
51   constexpr bool empty() const { return length_ == 0; }
52
53   // Access
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_; }
59
60   // Iterator
61   constexpr const char* begin() const { return str_; }
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