My Kernel v0.1.0
math.h
Go to the documentation of this file.
1
13#ifndef UTILS_MATH_H
14#define UTILS_MATH_H
15
16#include <kernel/types.h>
17
19#define MAX(_x, _y) \
20 ({ \
21 __typeof__(_x) _max1 = (_x); \
22 __typeof__(_y) _max2 = (_y); \
23 _max1 > _max2 ? _max1 : _max2; \
24 })
25
27#define MIN(_x, _y) \
28 ({ \
29 __typeof__(_x) _max1 = (_x); \
30 __typeof__(_y) _max2 = (_y); \
31 _max1 < _max2 ? _max1 : _max2; \
32 })
33
35#define ABS(_x) \
36 ({ \
37 __typeof__(_x) _tmp = (_x); \
38 _tmp < 0 ? -_tmp : _tmp; \
39 })
40
42#define is_power_of_2(_x) (_x != 0 && ((_x & (_x - 1)) == 0))
43
44#define __align_mask(_value, _power) ((__typeof__(_value))((_power)-1))
45
50#define align_up(_value, _power) \
51 ((((_value)-1) | __align_mask(_value, _power)) + 1)
52
57#define align_down(_value, _power) ((_value) & ~__align_mask(_value, _power))
58
60#define is_aligned(_value, _alignment) (!((_value) % (_alignment)))
61
62#define align_down_ptr(_ptr, _power) ((void *)align_down((vaddr_t)_ptr, _power))
63#define align_up_ptr(_ptr, _power) ((void *)align_up((vaddr_t)_ptr, _power))
64#define is_aligned_ptr(_ptr, _alignment) is_aligned((vaddr_t)_ptr, _alignment)
65
72static inline u32 round_up(u32 value, u32 alignment)
73{
74 if (alignment == 0)
75 return value;
76
77 u32 offset = value % alignment;
78 if (offset)
79 value += alignment - offset; // WARNING: Offset can occur here!
80
81 return value;
82}
83
88static inline u32 round_down(u32 value, u32 alignment)
89{
90 if (alignment == 0)
91 return value;
92
93 return value - (value % alignment);
94}
95
96#endif /* UTILS_MATH_H */
static u32 round_down(u32 value, u32 alignment)
Round value to the previous multiple of alignment.
Definition: math.h:88
static u32 round_up(u32 value, u32 alignment)
Round value to the next multiple of alignment.
Definition: math.h:72