]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/LookupTable.h
Merged from trunk
[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 * a record in the initializer list for a LookupTable
18 *
19 * In case it is wished to extend the structure of a LookupTable's initializer
20 * list, it can be done by using a custom struct which must match
21 * LookupTableRecord's signature plus any extra custom fields the user may
22 * wish to add; the extended record type must then be passed as RecordType
23 * template parameter to LookupTable.
24 */
25 template <typename EnumType>
26 struct LookupTableRecord
27 {
28 const char *name;
29 EnumType id;
30 };
31
32 /**
33 * SBuf -> case-insensitive enum lookup table
34 *
35 * How to use:
36 * enum enum_type { ... };
37 * static const LookupTable<enum_type>::Record initializerTable[] = {
38 * {"key1", ENUM_1}, {"key2", ENUM_2}, ... {nullptr, ENUM_INVALID_VALUE}
39 * };
40 * LookupTable<enum_type> lookupTableInstance(ENUM_INVALID_VALUE, initializerTable);
41 *
42 * then in the code:
43 * SBuf s(string_to_lookup);
44 * enum_type item = lookupTableInstance.lookup(s);
45 * if (item != ENUM_INVALID_VALUE) { // do stuff }
46 *
47 */
48
49 struct SBufCaseInsensitiveLess : public std::binary_function<SBuf, SBuf, bool> {
50 bool operator() (const SBuf &x, const SBuf &y) const {
51 return x.caseCmp(y) < 0;
52 }
53 };
54 template<typename EnumType, typename RecordType = LookupTableRecord<EnumType> >
55 class LookupTable
56 {
57 public:
58 /// element of the lookup table initialization list
59 typedef RecordType Record;
60
61 LookupTable(const EnumType theInvalid, const Record data[]) :
62 invalidValue(theInvalid)
63 {
64 for (auto i = 0; data[i].name != nullptr; ++i) {
65 lookupTable[SBuf(data[i].name)] = data[i].id;
66 }
67 }
68
69 EnumType lookup(const SBuf &key) const {
70 auto r = lookupTable.find(key);
71 if (r == lookupTable.end())
72 return invalidValue;
73 return r->second;
74 }
75
76 private:
77 typedef std::map<const SBuf, EnumType, SBufCaseInsensitiveLess> lookupTable_t;
78 lookupTable_t lookupTable;
79 EnumType invalidValue;
80 };
81
82 #endif /* SQUID_LOOKUPTABLE_H_ */
83