blob: 696628752632dfe991a22607f1a4742ab1df9f48 [file] [log] [blame]
Manish Pandey65fe3642025-03-21 12:44:42 +00001/*
2 * Copyright The Transfer List Library Contributors
3 *
4 * SPDX-License-Identifier: MIT OR GPL-2.0-or-later
5 */
6
7#ifndef MATH_UTILS_H
8#define MATH_UTILS_H
9
10#include <stdint.h>
11
12/**
13 * @brief Rounds up a given value to the nearest multiple of a boundary.
14 *
15 * @param value The value to round up.
16 * @param boundary The alignment boundary (must be a power of two).
17 * @return The smallest multiple of `boundary` that is greater than or equal to `value`.
18 */
19static inline uintptr_t align_up(uintptr_t value, uintptr_t boundary)
20{
21 return (value + boundary - 1) & ~(boundary - 1);
22}
23
24/**
25 * @brief Checks whether `value` is aligned to the specified `boundary`.
26 *
27 * @param value The value to check.
28 * @param boundary The alignment boundary (should be a power of two for efficiency).
29 * @return `1` if `value` is aligned, `0` otherwise.
30 */
31static inline int is_aligned(uintptr_t value, uintptr_t boundary) {
32 return (value % boundary) == 0;
33}
34
35/**
36 * @brief Safely adds `a` and `b`, detecting overflow.
37 *
38 * @param a First operand.
39 * @param b Second operand.
40 * @param res Pointer to store the result if no overflow occurs.
41 * @return `1` if overflow occurs, `0` otherwise.
42 */
43#define add_overflow(a, b, res) __builtin_add_overflow((a), (b), (res))
44
45/**
46 * @brief Rounds up `v` to the nearest multiple of `size`, detecting overflow.
47 *
48 * @param v The value to round up.
49 * @param size The alignment boundary (must be a power of two).
50 * @param res Pointer to store the rounded-up result.
51 * @return `1` if an overflow occurs, `0` otherwise.
52 */
53#define round_up_overflow(v, size, res) \
54 (__extension__({ \
55 typeof(res) __res = res; \
56 typeof(*(__res)) __roundup_tmp = 0; \
57 typeof(v) __roundup_mask = (typeof(v))(size) - 1; \
58 \
59 add_overflow((v), __roundup_mask, &__roundup_tmp) ? \
60 1 : \
61 (void)(*(__res) = __roundup_tmp & ~__roundup_mask), \
62 0; \
63 }))
64
65/**
66 * @brief Adds `a` and `b`, then rounds up the result to the nearest multiple
67 * of `size`, detecting overflow.
68 *
69 * @param a First operand for addition.
70 * @param b Second operand for addition.
71 * @param size The alignment boundary (must be positive).
72 * @param res Pointer to store the final rounded result.
73 * @return `1` if an overflow occurs during addition or rounding, `0` otherwise.
74 */
75#define add_with_round_up_overflow(a, b, size, res) \
76 (__extension__({ \
77 typeof(a) __a = (a); \
78 typeof(__a) __add_res = 0; \
79 \
80 add_overflow((__a), (b), &__add_res) ? 1 : \
81 round_up_overflow(__add_res, (size), (res)) ? 1 : \
82 0; \
83 }))
84
85#endif /* MATH_UTILS_H */