2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
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.
9 #ifndef SQUID_LOOKUPTABLE_H_
10 #define SQUID_LOOKUPTABLE_H_
12 #include "sbuf/Algorithms.h"
13 #include "sbuf/SBuf.h"
15 #include <unordered_map>
18 * a record in the initializer list for a LookupTable
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.
26 template <typename EnumType
>
27 struct LookupTableRecord
34 * SBuf -> case-insensitive enum lookup table
37 * enum enum_type { ... };
38 * static const LookupTable<enum_type>::Record initializerTable[] = {
39 * {"key1", ENUM_1}, {"key2", ENUM_2}, ... {nullptr, ENUM_INVALID_VALUE}
41 * LookupTable<enum_type> lookupTableInstance(ENUM_INVALID_VALUE, initializerTable);
44 * SBuf s(string_to_lookup);
45 * enum_type item = lookupTableInstance.lookup(s);
46 * if (item != ENUM_INVALID_VALUE) { // do stuff }
50 class SBufCaseInsensitiveLess
: public std::binary_function
<SBuf
, SBuf
, bool> {
52 bool operator() (const SBuf
&x
, const SBuf
&y
) const {
53 return x
.caseCmp(y
) < 0;
57 template<typename EnumType
, typename RecordType
= LookupTableRecord
<EnumType
>, typename Hasher
= CaseInsensitiveSBufHash
>
61 /// element of the lookup table initialization list
62 typedef RecordType Record
;
64 LookupTable(const EnumType theInvalid
, const Record data
[]) :
65 invalidValue(theInvalid
)
67 for (auto i
= 0; data
[i
].name
!= nullptr; ++i
) {
68 lookupTable
[SBuf(data
[i
].name
)] = data
[i
].id
;
72 EnumType
lookup(const SBuf
&key
) const {
73 auto r
= lookupTable
.find(key
);
74 if (r
== lookupTable
.end())
80 typedef std::unordered_map
<const SBuf
, EnumType
, Hasher
> lookupTable_t
;
81 lookupTable_t lookupTable
;
82 EnumType invalidValue
;
85 #endif /* SQUID_LOOKUPTABLE_H_ */