1 /**
2 * Integer Rounding Functions
3 * 
4 * Copyright:
5 * (C) 1999-2007 Jack Lloyd
6 * (C) 2014-2015 Etienne Cimon
7 *
8 * License:
9 * Botan is released under the Simplified BSD License (see LICENSE.md)
10 */
11 module botan.utils.rounding;
12 
13 import botan.utils.types;
14 
15 /**
16 * Round up
17 * Params:
18 *  n = an integer
19 *  align_to = the alignment boundary
20 * Returns: n rounded up to a multiple of align_to
21 */
22 T roundUp(T)(T n, T align_to)
23 {
24     if (align_to == 0)
25         return n;
26 
27     if (n % align_to || n == 0)
28         n += align_to - (n % align_to);
29     return n;
30 }
31 
32 /**
33 * Round down
34 * Params:
35 *  n = an integer
36 *  align_to = the alignment boundary
37 * Returns: n rounded down to a multiple of align_to
38 */
39 T roundDown(T)(T n, T align_to)
40 {
41     if (align_to == 0)
42         return n;
43 
44     return (n - (n % align_to));
45 }
46 
47 /**
48 * Clamp
49 */
50 size_t clamp(size_t n, size_t lower_bound, size_t upper_bound)
51 {
52     if (n < lower_bound)
53         return lower_bound;
54     if (n > upper_bound)
55         return upper_bound;
56     return n;
57 }