kvmap.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #ifndef BRPC_KVMAP_H
  18. #define BRPC_KVMAP_H
  19. #include "butil/containers/flat_map.h"
  20. namespace brpc {
  21. // Remember Key/Values in string
  22. class KVMap {
  23. public:
  24. typedef butil::FlatMap<std::string, std::string> Map;
  25. typedef Map::const_iterator Iterator;
  26. KVMap() {}
  27. // Exchange internal fields with another KVMap.
  28. void Swap(KVMap &rhs) { _entries.swap(rhs._entries); }
  29. // Reset internal fields as if they're just default-constructed.
  30. void Clear() { _entries.clear(); }
  31. // Get value of a key(case-sensitive)
  32. // Return pointer to the value, NULL on not found.
  33. const std::string* Get(const char* key) const { return _entries.seek(key); }
  34. const std::string* Get(const std::string& key) const { return _entries.seek(key); }
  35. // Set value of a key
  36. void Set(const std::string& key, const std::string& value) { GetOrAdd(key) = value; }
  37. void Set(const std::string& key, const char* value) { GetOrAdd(key) = value; }
  38. // Convert other types to string as well
  39. template <typename T>
  40. void Set(const std::string& key, const T& value) { GetOrAdd(key) = std::to_string(value); }
  41. // Remove a key
  42. void Remove(const char* key) { _entries.erase(key); }
  43. void Remove(const std::string& key) { _entries.erase(key); }
  44. // Get iterators to iterate key/value
  45. Iterator Begin() const { return _entries.begin(); }
  46. Iterator End() const { return _entries.end(); }
  47. // number of key/values
  48. size_t Count() const { return _entries.size(); }
  49. private:
  50. std::string& GetOrAdd(const std::string& key) {
  51. if (!_entries.initialized()) {
  52. _entries.init(29);
  53. }
  54. return _entries[key];
  55. }
  56. Map _entries;
  57. };
  58. } // namespace brpc
  59. #endif // BRPC_KVMAP_H