]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/LookupTable.h
Source Format Enforcement (#532)
[thirdparty/squid.git] / src / base / LookupTable.h
1 /*
2 * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 #ifndef SQUID_LOOKUPTABLE_H_
10 #define SQUID_LOOKUPTABLE_H_
11
12 #include "sbuf/Algorithms.h"
13 #include "sbuf/SBuf.h"
14
15 #include <unordered_map>
16
17 /**
18 * a record in the initializer list for a LookupTable
19 *
20 * In case it is wished to extend the structure of a LookupTable's initializer
21 * list, it can be done by using a custom struct which must match
22 * LookupTableRecord's signature plus any extra custom fields the user may
23 * wish to add; the extended record type must then be passed as RecordType
24 * template parameter to LookupTable.
25 */
26 template <typename EnumType>
27 struct LookupTableRecord
28 {
29 const char *name;
30 EnumType id;
31 };
32
33 /**
34 * SBuf -> case-insensitive enum lookup table
35 *
36 * How to use:
37 * enum enum_type { ... };
38 * static const LookupTable<enum_type>::Record initializerTable[] = {
39 * {"key1", ENUM_1}, {"key2", ENUM_2}, ... {nullptr, ENUM_INVALID_VALUE}
40 * };
41 * LookupTable<enum_type> lookupTableInstance(ENUM_INVALID_VALUE, initializerTable);
42 *
43 * then in the code:
44 * SBuf s(string_to_lookup);
45 * enum_type item = lookupTableInstance.lookup(s);
46 * if (item != ENUM_INVALID_VALUE) { // do stuff }
47 *
48 */
49
50 template<typename EnumType, typename RecordType = LookupTableRecord<EnumType>, typename Hasher = CaseInsensitiveSBufHash >
51 class LookupTable
52 {
53 public:
54 /// element of the lookup table initialization list
55 typedef RecordType Record;
56
57 LookupTable(const EnumType theInvalid, const Record data[]) :
58 invalidValue(theInvalid)
59 {
60 for (auto i = 0; data[i].name != nullptr; ++i) {
61 lookupTable[SBuf(data[i].name)] = data[i].id;
62 }
63 }
64
65 EnumType lookup(const SBuf &key) const {
66 auto r = lookupTable.find(key);
67 if (r == lookupTable.end())
68 return invalidValue;
69 return r->second;
70 }
71
72 private:
73 typedef std::unordered_map<const SBuf, EnumType, Hasher> lookupTable_t;
74 lookupTable_t lookupTable;
75 EnumType invalidValue;
76 };
77
78 #endif /* SQUID_LOOKUPTABLE_H_ */
79