]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/LookupTable.h
Docs: Copyright updates for 2018 (#114)
[thirdparty/squid.git] / src / base / LookupTable.h
1 /*
2 * Copyright (C) 1996-2018 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 class SBufCaseInsensitiveLess : public std::binary_function<SBuf, SBuf, bool> {
51 public:
52 bool operator() (const SBuf &x, const SBuf &y) const {
53 return x.caseCmp(y) < 0;
54 }
55 };
56
57 template<typename EnumType, typename RecordType = LookupTableRecord<EnumType>, typename Hasher = CaseInsensitiveSBufHash >
58 class LookupTable
59 {
60 public:
61 /// element of the lookup table initialization list
62 typedef RecordType Record;
63
64 LookupTable(const EnumType theInvalid, const Record data[]) :
65 invalidValue(theInvalid)
66 {
67 for (auto i = 0; data[i].name != nullptr; ++i) {
68 lookupTable[SBuf(data[i].name)] = data[i].id;
69 }
70 }
71
72 EnumType lookup(const SBuf &key) const {
73 auto r = lookupTable.find(key);
74 if (r == lookupTable.end())
75 return invalidValue;
76 return r->second;
77 }
78
79 private:
80 typedef std::unordered_map<const SBuf, EnumType, Hasher> lookupTable_t;
81 lookupTable_t lookupTable;
82 EnumType invalidValue;
83 };
84
85 #endif /* SQUID_LOOKUPTABLE_H_ */
86