1 /* Copyright (C) 2017 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
2
3 This program is free software: you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation, either version 3 of the License, or
6 (at your option) any later version.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <https://www.gnu.org/licenses/>.
15 */
16
17 /*!
18 * \file
19 *
20 * \brief A general purpose lookup table.
21 *
22 * \addtogroup libknot
23 * @{
24 */
25
26 #pragma once
27
28 #include <string.h>
29 #include <strings.h>
30
31 /*!
32 * \brief A general purpose lookup table.
33 */
34 typedef struct knot_lookup {
35 int id;
36 const char *name;
37 } knot_lookup_t;
38
39 /*!
40 * \brief Looks up the given name in the lookup table.
41 *
42 * \param table Lookup table.
43 * \param name Name to look up.
44 *
45 * \return Item in the lookup table with the given name or NULL if no such is
46 * present.
47 */
knot_lookup_by_name(const knot_lookup_t * table,const char * name)48 inline static const knot_lookup_t *knot_lookup_by_name(const knot_lookup_t *table, const char *name)
49 {
50 if (table == NULL || name == NULL) {
51 return NULL;
52 }
53
54 while (table->name != NULL) {
55 if (strcasecmp(name, table->name) == 0) {
56 return table;
57 }
58 table++;
59 }
60
61 return NULL;
62 }
63
64 /*!
65 * \brief Looks up the given id in the lookup table.
66 *
67 * \param table Lookup table.
68 * \param id ID to look up.
69 *
70 * \return Item in the lookup table with the given id or NULL if no such is
71 * present.
72 */
knot_lookup_by_id(const knot_lookup_t * table,int id)73 inline static const knot_lookup_t *knot_lookup_by_id(const knot_lookup_t *table, int id)
74 {
75 if (table == NULL) {
76 return NULL;
77 }
78
79 while (table->name != NULL) {
80 if (table->id == id) {
81 return table;
82 }
83 table++;
84 }
85
86 return NULL;
87 }
88
89 /*! @} */
90