better split up of library files "types.h" & "definitions.h"
[strongswan.git] / src / libstrongswan / enum.c
1 /**
2 * @file library.c
3 *
4 * @brief enum value to string conversion functions.
5 *
6 */
7
8 /*
9 * Copyright (C) 2006 Martin Willi
10 * Hochschule fuer Technik Rapperswil
11 *
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU General Public License as published by the
14 * Free Software Foundation; either version 2 of the License, or (at your
15 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
19 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * for more details.
21 */
22
23 #include <stddef.h>
24 #include <stdio.h>
25
26 #include "enum.h"
27
28 #include <printf_hook.h>
29
30 /**
31 * get the name of an enum value in a enum_name_t list
32 */
33 static char *enum_name(enum_name_t *e, long val)
34 {
35 do
36 {
37 if (val >= e->first && val <= e->last)
38 {
39 return e->names[val - e->first];
40 }
41 }
42 while ((e = e->next));
43 return NULL;
44 }
45
46 /**
47 * output handler in printf() for enum names
48 */
49 static int print_enum(FILE *stream, const struct printf_info *info,
50 const void *const *args)
51 {
52 enum_name_t *ed = *((void**)(args[0]));
53 long val = *((long*)(args[1]));
54 char *name;
55
56 name = enum_name(ed, val);
57 if (name == NULL)
58 {
59 return fprintf(stream, "(unknown enum value: %ld)", val);
60 }
61 return fprintf(stream, "%s", name);
62 }
63
64 /**
65 * register printf() handlers
66 */
67 static void __attribute__ ((constructor))print_register()
68 {
69 register_printf_function(PRINTF_ENUM, print_enum, arginfo_ptr_int);
70 }