NingSun | 0c89b3c | 2018-02-08 08:34:03 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Integer Rounding Functions |
| 3 | * (C) 1999-2007 Jack Lloyd |
| 4 | * |
| 5 | * Botan is released under the Simplified BSD License (see license.txt) |
| 6 | */ |
| 7 | |
| 8 | #ifndef BOTAN_ROUNDING_H__ |
| 9 | #define BOTAN_ROUNDING_H__ |
| 10 | |
| 11 | #include <botan/version.h> |
| 12 | #if BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(2,0,0) |
| 13 | // ECB cipher mode was dropped in Botan 2.0.0 |
| 14 | // so including this code in SoftHSM for continued support |
| 15 | // for e.g. CKA_VALUE_CHECK |
| 16 | |
| 17 | #include <botan/types.h> |
| 18 | #include <botan/assert.h> |
| 19 | |
| 20 | namespace Botan { |
| 21 | |
| 22 | /** |
| 23 | * Round up |
| 24 | * @param n a non-negative integer |
| 25 | * @param align_to the alignment boundary |
| 26 | * @return n rounded up to a multiple of align_to |
| 27 | */ |
| 28 | inline size_t round_up(size_t n, size_t align_to) |
| 29 | { |
| 30 | BOTAN_ASSERT(align_to != 0, "align_to must not be 0"); |
| 31 | |
| 32 | if(n % align_to) |
| 33 | n += align_to - (n % align_to); |
| 34 | return n; |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Round down |
| 39 | * @param n an integer |
| 40 | * @param align_to the alignment boundary |
| 41 | * @return n rounded down to a multiple of align_to |
| 42 | */ |
| 43 | template<typename T> |
| 44 | inline T round_down(T n, T align_to) |
| 45 | { |
| 46 | if(align_to == 0) |
| 47 | return n; |
| 48 | |
| 49 | return (n - (n % align_to)); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Clamp |
| 54 | */ |
| 55 | inline size_t clamp(size_t n, size_t lower_bound, size_t upper_bound) |
| 56 | { |
| 57 | if(n < lower_bound) |
| 58 | return lower_bound; |
| 59 | if(n > upper_bound) |
| 60 | return upper_bound; |
| 61 | return n; |
| 62 | } |
| 63 | |
| 64 | } |
| 65 | |
| 66 | #endif |
| 67 | |
| 68 | #endif |