stream: remove anonymous union
[vlc.git] / compat / posix_memalign.c
blobbdd8f612c58eb809284cd60088c254355910fe93
1 /*****************************************************************************
2 * posix_memalign.c: POSIX posix_memalign() replacement
3 *****************************************************************************
4 * Copyright © 2012, 2019 Rémi Denis-Courmont
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19 *****************************************************************************/
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <limits.h>
29 #ifdef HAVE_MEMALIGN
30 # include <malloc.h>
31 #else
33 static void *memalign(size_t align, size_t size)
35 void *p = malloc(size);
37 if ((uintptr_t)p & (align - 1)) {
38 free(p);
39 p = NULL;
42 return p;
45 #endif
47 static int check_align(size_t align)
49 if (align & (align - 1)) /* must be a power of two */
50 return EINVAL;
51 if (align < sizeof (void *)) /* must be a multiple of sizeof (void *) */
52 return EINVAL;
53 return 0;
56 int posix_memalign(void **ptr, size_t align, size_t size)
58 int val = check_align(align);
59 if (val)
60 return val;
62 /* Unlike posix_memalign(), legacy memalign() requires that size be a
63 * multiple of align.
65 if (size > (SIZE_MAX / 2))
66 return ENOMEM;
68 size += (-size) & (align - 1);
70 int saved_errno = errno;
71 void *p = memalign(align, size);
72 if (p == NULL) {
73 val = errno;
74 errno = saved_errno;
75 return val;
78 *ptr = p;
79 return 0;