data-structures-c
Loading...
Searching...
No Matches
align.h
Go to the documentation of this file.
1/* align.h
2 *
3 * Copyright (C) 2023 abxh
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 * See the file LICENSE included with this distribution for more
10 * information. */
11
22#pragma once
23
24#include <assert.h>
25#include <stdint.h>
26#include <stdlib.h>
27
28#include "is_pow2.h"
29
43static inline void *align(const size_t alignment, const size_t size, void **ptr_ptr, size_t *space_ptr)
44{
45 assert(ptr_ptr);
46 assert(space_ptr);
47 assert(is_pow2(alignment));
48
49 if (*space_ptr < size) {
50 return NULL;
51 }
52
53 /* explanation:
54 -alignment == ~(alignment - 1U)
55
56 example:
57 for alignment = 8,
58
59 aligned:
60 ((intptr = 0) - 1 + 8) & ~0b111 = 0b00000 = 0
61 ((intptr = 1) - 1 + 8) & ~0b111 = 0b01000 = 8
62 ((intptr = 2) - 1 + 8) & ~0b111 = 0b01000 = 8
63 ...
64 ((intptr = 8) - 1 + 8) & ~0b111 = 0b01000 = 8
65 ((intptr = 9) - 1 + 8) & ~0b111 = 0b10000 = 16
66 ...
67 ((intptr = 17) - 1 + 8) & ~0b111 = 0b11000 = 24
68 */
69
70 const uintptr_t intptr = (uintptr_t)*ptr_ptr;
71 const uintptr_t aligned = (intptr - 1u + alignment) & -alignment;
72 const uintptr_t padding = aligned - intptr;
73
74 if (padding > (*space_ptr - size)) {
75 return NULL;
76 }
77 else {
78 *space_ptr -= padding;
79 return (*ptr_ptr = (void *)aligned);
80 }
81}
82
91static inline uintptr_t calc_alignment_padding(const size_t alignment, const uintptr_t ptr)
92{
93 assert(is_pow2(alignment));
94
95 const uintptr_t aligned = (ptr - 1u + alignment) & -alignment;
96 const uintptr_t padding = aligned - ptr;
97
98 return padding;
99}
100
105#define CALC_ALIGNMENT_PADDING(alignment, ptr) ((((ptr) - 1u + (alignment)) & -(alignment)) - (ptr))
static uintptr_t calc_alignment_padding(const size_t alignment, const uintptr_t ptr)
Calculate the alignment padding required to align a pointer.
Definition align.h:91
static void * align(const size_t alignment, const size_t size, void **ptr_ptr, size_t *space_ptr)
Align pointer to the next alignment boundary.
Definition align.h:43
Check if a number is a power of two.
static size_t is_pow2(const size_t x)
Check if a number is a power of two.
Definition is_pow2.h:34