1
/*
2
* \brief Commonly used math functions
3
* \author Norman Feske
4
* \date 2006-04-12
5
*/
6
7
/*
8
* Copyright (C) 2006-2013 Genode Labs GmbH
9
*
10
* This file is part of the Genode OS framework, which is distributed
11
* under the terms of the GNU General Public License version 2.
12
*/
13
14
#
ifndef _INCLUDE__UTIL__MISC_MATH_H_
15
#
define _INCLUDE__UTIL__MISC_MATH_H_
16
17
namespace
Genode {
18
19
template
<
typename
T1
,
typename
T2
>
20
T1
max(
T1
v1
,
T2
v2
)
{
return
v1 >
v2 ?
v1 : v2
;
}
21
22
template
<
typename
T1
,
typename
T2
>
23
T1
min(
T1
v1
,
T2
v2
)
{
return
v1 <
v2 ?
v1 : v2
;
}
24
25
template
<
typename
T
>
26
T
abs(
T
value
)
{
return
value >=
0 ?
value : -
value
;
}
27
28
29
/**
30
* Alignment to the power of two
31
*/
32
template
<
typename
T
>
33
static
constexpr
T
_align_mask(
T
align
)
{
34
return
~
(
(
(
T)
1 <<
align)
-
(
T)
1)
;
}
35
36
template
<
typename
T
>
37
static
constexpr
T
_align_offset(
T
align
)
{
38
return
(
(
T)
1 <<
align)
-
(
T)
1
;
}
39
40
template
<
typename
T
>
41
static
constexpr
T
align_addr(
T
addr
,
int
align
)
{
42
return
(
addr +
_align_offset(
(
T)
align)
)
&
_align_mask(
(
T)
align)
;
}
43
44
45
/**
46
* LOG2
47
*
48
* Scan for most-significant set bit.
49
*/
50
template
<
typename
T
>
51
static
inline
T
log2(
T
value
)
52
{
53
if
(
!
value)
return
-
1
;
54
for
(
int i =
8 *
sizeof
(
value)
-
1; i >=
0; --
i)
55
if
(
(
(
T)
1 <<
i)
&
value)
return
i
;
56
57
return
-
1
;
58
}
59
60
61
/**
62
* Align value to next machine-word boundary
63
*/
64
template
<
typename
T
>
65
inline
T
align_natural(
T
value
)
66
{
67
T mask =
sizeof
(
long)
-
1;
68
return
(
value +
mask)
&
~
mask
;
69
}
70
}
71
72
#
endif /* _INCLUDE__UTIL__MISC_MATH_H_ */