ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
mapping.h
Go to the documentation of this file.
1#pragma once
2
4#include "esphome/core/log.h"
5#include <map>
6#include <string>
7
8namespace esphome::mapping {
9
10using alloc_string_t = std::basic_string<char, std::char_traits<char>, RAMAllocator<char>>;
11
21static const char *const TAG = "mapping";
22
23template<typename K, typename V> class Mapping {
24 public:
25 // Constructor
26 Mapping() = default;
27
28 using key_t = const std::conditional_t<std::is_same_v<K, std::string>,
29 alloc_string_t, // if K is std::string, custom string type
30 K>;
31 using value_t = std::conditional_t<std::is_same_v<V, std::string>,
32 alloc_string_t, // if V is std::string, custom string type
33 V>;
34
35 void set(const K &key, const V &value) { this->map_[key_t{key}] = value; }
36
37 V get(const K &key) const {
38 auto it = this->map_.find(key_t{key});
39 if (it != this->map_.end()) {
40 return V{it->second};
41 }
42 if constexpr (std::is_pointer_v<K>) {
43 esph_log_e(TAG, "Key '%p' not found in mapping", key);
44 } else if constexpr (std::is_same_v<K, std::string>) {
45 esph_log_e(TAG, "Key '%s' not found in mapping", key.c_str());
46 } else {
47 esph_log_e(TAG, "Key '%s' not found in mapping", to_string(key).c_str());
48 }
49 return {};
50 }
51
52 // index map overload
53 V operator[](K key) { return this->get(key); }
54
55 // convenience function for strings to get a C-style string
56 template<typename T = V, std::enable_if_t<std::is_same_v<T, std::string>, int> = 0>
57 const char *operator[](K key) const {
58 auto it = this->map_.find(key_t{key});
59 if (it != this->map_.end()) {
60 return it->second.c_str(); // safe since value remains in map
61 }
62 return "";
63 }
64
65 protected:
66 std::map<key_t, value_t, std::less<key_t>, RAMAllocator<std::pair<key_t, value_t>>> map_;
67};
68
69} // namespace esphome::mapping
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:818
const char * operator[](K key) const
Definition mapping.h:57
void set(const K &key, const V &value)
Definition mapping.h:35
std::conditional_t< std::is_same_v< V, std::string >, alloc_string_t, V > value_t
Definition mapping.h:31
const std::conditional_t< std::is_same_v< K, std::string >, alloc_string_t, K > key_t
Definition mapping.h:28
V get(const K &key) const
Definition mapping.h:37
std::map< key_t, value_t, std::less< key_t >, RAMAllocator< std::pair< key_t, value_t > > > map_
Definition mapping.h:66
std::basic_string< char, std::char_traits< char >, RAMAllocator< char > > alloc_string_t
Definition mapping.h:10