]>
Commit | Line | Data |
---|---|---|
04f12ecd MW |
1 | /* |
2 | * Copyright (C) 2008-2014 Tobias Brunner | |
3 | * Copyright (C) 2008 Martin Willi | |
19ef2aec TB |
4 | * |
5 | * Copyright (C) secunet Security Networks AG | |
04f12ecd MW |
6 | * |
7 | * This program is free software; you can redistribute it and/or modify it | |
8 | * under the terms of the GNU General Public License as published by the | |
9 | * Free Software Foundation; either version 2 of the License, or (at your | |
10 | * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. | |
11 | * | |
12 | * This program is distributed in the hope that it will be useful, but | |
13 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY | |
14 | * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License | |
15 | * for more details. | |
16 | */ | |
17 | ||
18 | /** | |
19 | * @defgroup align_i align | |
20 | * @{ @ingroup utils_i | |
21 | */ | |
22 | ||
23 | #ifndef ALIGN_H_ | |
24 | #define ALIGN_H_ | |
25 | ||
26 | /** | |
27 | * Macro gives back larger of two values. | |
28 | */ | |
29 | #define max(x,y) ({ \ | |
30 | typeof(x) _x = (x); \ | |
31 | typeof(y) _y = (y); \ | |
32 | _x > _y ? _x : _y; }) | |
33 | ||
34 | /** | |
35 | * Macro gives back smaller of two values. | |
36 | */ | |
37 | #define min(x,y) ({ \ | |
38 | typeof(x) _x = (x); \ | |
39 | typeof(y) _y = (y); \ | |
40 | _x < _y ? _x : _y; }) | |
41 | ||
42 | /** | |
43 | * Get the padding required to make size a multiple of alignment | |
44 | */ | |
45 | static inline size_t pad_len(size_t size, size_t alignment) | |
46 | { | |
47 | size_t remainder; | |
48 | ||
49 | remainder = size % alignment; | |
50 | return remainder ? alignment - remainder : 0; | |
51 | } | |
52 | ||
53 | /** | |
54 | * Round up size to be multiple of alignment | |
55 | */ | |
56 | static inline size_t round_up(size_t size, size_t alignment) | |
57 | { | |
58 | return size + pad_len(size, alignment); | |
59 | } | |
60 | ||
61 | /** | |
62 | * Round down size to be a multiple of alignment | |
63 | */ | |
64 | static inline size_t round_down(size_t size, size_t alignment) | |
65 | { | |
66 | return size - (size % alignment); | |
67 | } | |
68 | ||
69 | /** | |
70 | * malloc(), but returns aligned memory. | |
71 | * | |
72 | * The returned pointer must be freed using free_align(), not free(). | |
73 | * | |
74 | * @param size size of allocated data | |
75 | * @param align alignment, up to 255 bytes, usually a power of 2 | |
76 | * @return allocated hunk, aligned to align bytes | |
77 | */ | |
b12c53ce | 78 | void* malloc_align(size_t size, uint8_t align); |
04f12ecd MW |
79 | |
80 | /** | |
81 | * Free a hunk allocated by malloc_align(). | |
82 | * | |
83 | * @param ptr hunk to free | |
84 | */ | |
85 | void free_align(void *ptr); | |
86 | ||
87 | #endif /** ALIGN_H_ @} */ |