]> git.ipfire.org Git - thirdparty/squid.git/blame - src/base/LookupTable.h
SourceFormat Enforcement
[thirdparty/squid.git] / src / base / LookupTable.h
CommitLineData
24aa4519 1/*
ef57eb7b 2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
24aa4519
FC
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
a0655385
FC
9#ifndef SQUID_LOOKUPTABLE_H_
10#define SQUID_LOOKUPTABLE_H_
11
12#include "SBuf.h"
81ab22b6 13#include "SBufAlgos.h"
a0655385 14
81ab22b6 15#include <unordered_map>
a0655385 16
d8e2dffe 17/**
46f990e0 18 * a record in the initializer list for a LookupTable
d8e2dffe
FC
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 */
26template <typename EnumType>
27struct LookupTableRecord
28{
29 const char *name;
30 EnumType id;
31};
32
a0655385 33/**
46f990e0 34 * SBuf -> case-insensitive enum lookup table
ae22f65a
FC
35 *
36 * How to use:
37 * enum enum_type { ... };
b88a45ed 38 * static const LookupTable<enum_type>::Record initializerTable[] = {
ae22f65a
FC
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 *
a0655385 48 */
46f990e0 49
d1ea2a11
FC
50class SBufCaseInsensitiveLess : public std::binary_function<SBuf, SBuf, bool> {
51public:
46f990e0
FC
52 bool operator() (const SBuf &x, const SBuf &y) const {
53 return x.caseCmp(y) < 0;
54 }
55};
d1ea2a11 56
81ab22b6 57template<typename EnumType, typename RecordType = LookupTableRecord<EnumType>, typename Hasher = CaseInsensitiveSBufHash >
a0655385
FC
58class LookupTable
59{
60public:
ae22f65a 61 /// element of the lookup table initialization list
d8e2dffe 62 typedef RecordType Record;
a0655385
FC
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 }
d8e2dffe 71
a0655385
FC
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
79private:
81ab22b6 80 typedef std::unordered_map<const SBuf, EnumType, Hasher> lookupTable_t;
a0655385
FC
81 lookupTable_t lookupTable;
82 EnumType invalidValue;
83};
84
85#endif /* SQUID_LOOKUPTABLE_H_ */
4be4fedc 86