]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/LookupTable.h
merge coverity-fixes: implement LookupTable
[thirdparty/squid.git] / src / base / LookupTable.h
1 /*
2 * Copyright (C) 1996-2015 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.h"
13
14 #include <map>
15
16 /**
17 * SBuf -> enum lookup table
18 *
19 * How to use:
20 * enum enum_type { ... };
21 * static const LookupTable<enum_type>::Record initializerTable[] {
22 * {"key1", ENUM_1}, {"key2", ENUM_2}, ... {nullptr, ENUM_INVALID_VALUE}
23 * };
24 * LookupTable<enum_type> lookupTableInstance(ENUM_INVALID_VALUE, initializerTable);
25 *
26 * then in the code:
27 * SBuf s(string_to_lookup);
28 * enum_type item = lookupTableInstance.lookup(s);
29 * if (item != ENUM_INVALID_VALUE) { // do stuff }
30 *
31 */
32 template<typename EnumType>
33 class LookupTable
34 {
35 public:
36 /// element of the lookup table initialization list
37 typedef struct {
38 const char *name;
39 EnumType id;
40 } Record;
41
42 LookupTable(const EnumType theInvalid, const Record data[]) :
43 invalidValue(theInvalid)
44 {
45 for (auto i = 0; data[i].name != nullptr; ++i) {
46 lookupTable[SBuf(data[i].name)] = data[i].id;
47 }
48 }
49 EnumType lookup(const SBuf &key) const {
50 auto r = lookupTable.find(key);
51 if (r == lookupTable.end())
52 return invalidValue;
53 return r->second;
54 }
55
56 private:
57 typedef std::map<const SBuf, EnumType> lookupTable_t;
58 lookupTable_t lookupTable;
59 EnumType invalidValue;
60 };
61
62 #endif /* SQUID_LOOKUPTABLE_H_ */