Add UP_CAST macro, for safer casting from contained data to its container.
[pspp] / src / libpspp / cast.h
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #ifndef LIBPSPP_CAST_H
18 #define LIBPSPP_CAST_H 1
19
20 #include <stddef.h>
21
22 /* Given expressions A and B, both of which have pointer type,
23    expands to a void expression that causes a compiler warning if
24    A and B are not pointers to qualified or unqualified versions
25    of compatible types. */
26 #define CHECK_POINTER_COMPATIBILITY(A, B) ((void) sizeof ((A) == (B)))
27
28 /* Given POINTER, a pointer to the given MEMBER within structure
29    STRUCT, returns the address of the STRUCT. */
30 #define UP_CAST(POINTER, STRUCT, MEMBER)                                \
31         (CHECK_POINTER_COMPATIBILITY (&((STRUCT *) 0)->MEMBER, POINTER), \
32          (STRUCT *) ((char *) (POINTER) - offsetof (STRUCT, MEMBER)))
33
34 #endif /* libpspp/cast.h */