GRASS GIS 8 Programmer's Manual  8.2.2dev(2023)-3d2c704037
gis/handler.c
Go to the documentation of this file.
1 /*!
2  \file lib/gis/handler.c
3 
4  \brief GIS Library - Error handlers
5 
6  (C) 2010-2011 by the GRASS Development Team
7 
8  This program is free software under the GNU General Public
9  License (>=v2). Read the file COPYING that comes with GRASS
10  for details.
11 
12  \author Glynn Clements
13 */
14 
15 #include <stddef.h>
16 #include <grass/gis.h>
17 
18 /*!
19  \brief Error handler (see G_add_error_handler() for usage)
20 */
21 struct handler {
22  /*!
23  \brief Pointer to the handler routine
24  */
25  void (*func)(void *);
26  /*!
27  \brief Pointer to closure data
28  */
29  void *closure;
30 };
31 
32 static struct handler *handlers;
33 
34 static int num_handlers;
35 static int max_handlers;
36 
37 static struct handler *alloc_handler(void)
38 {
39  int i;
40 
41  for (i = 0; i < num_handlers; i++) {
42  struct handler *h = &handlers[i];
43  if (!h->func)
44  return h;
45  }
46 
47  if (num_handlers >= max_handlers) {
48  max_handlers += 10;
49  handlers = G_realloc(handlers, max_handlers * sizeof(struct handler));
50  }
51 
52  return &handlers[num_handlers++];
53 }
54 
55 /*!
56  \brief Add new error handler
57 
58  Example
59  \code
60  static void error_handler(void *p) {
61  const char *map = (const char *) p;
62  Vect_delete(map);
63  }
64  G_add_error_handler(error_handler, new->answer);
65  \endcode
66 
67  \param func handler to add
68  \param closure pointer to closure data
69 */
70 void G_add_error_handler(void (*func)(void *), void *closure)
71 {
72  struct handler *h = alloc_handler();
73 
74  h->func = func;
75  h->closure = closure;
76 }
77 
78 /*!
79  \brief Remove existing error handler
80 
81  \param func handler to be remove
82  \param closure pointer to closure data
83 */
84 void G_remove_error_handler(void (*func)(void *), void *closure)
85 {
86  int i;
87 
88  for (i = 0; i < num_handlers; i++) {
89  struct handler *h = &handlers[i];
90 
91  if (h->func == func && h->closure == closure) {
92  h->func = NULL;
93  h->closure = NULL;
94  }
95  }
96 }
97 
98 /*!
99  \brief Call available error handlers (internal use only)
100 */
102 {
103  int i;
104 
105  for (i = 0; i < num_handlers; i++) {
106  struct handler *h = &handlers[i];
107  if (h->func)
108  (*h->func)(h->closure);
109  }
110 }
111 
void G_add_error_handler(void(*func)(void *), void *closure)
Add new error handler.
Definition: gis/handler.c:70
void G_remove_error_handler(void(*func)(void *), void *closure)
Remove existing error handler.
Definition: gis/handler.c:84
#define NULL
Definition: ccmath.h:32
#define G_realloc(p, n)
Definition: defs/gis.h:114
void G__call_error_handlers(void)
Call available error handlers (internal use only)
Definition: gis/handler.c:101