Botan  1.11.15
src/lib/utils/rounding.h
Go to the documentation of this file.
00001 /*
00002 * Integer Rounding Functions
00003 * (C) 1999-2007 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #ifndef BOTAN_ROUNDING_H__
00009 #define BOTAN_ROUNDING_H__
00010 
00011 #include <botan/types.h>
00012 
00013 namespace Botan {
00014 
00015 /**
00016 * Round up
00017 * @param n an integer
00018 * @param align_to the alignment boundary
00019 * @return n rounded up to a multiple of align_to
00020 */
00021 template<typename T>
00022 inline T round_up(T n, T align_to)
00023    {
00024    if(align_to == 0)
00025       return n;
00026 
00027    if(n % align_to || n == 0)
00028       n += align_to - (n % align_to);
00029    return n;
00030    }
00031 
00032 /**
00033 * Round down
00034 * @param n an integer
00035 * @param align_to the alignment boundary
00036 * @return n rounded down to a multiple of align_to
00037 */
00038 template<typename T>
00039 inline T round_down(T n, T align_to)
00040    {
00041    if(align_to == 0)
00042       return n;
00043 
00044    return (n - (n % align_to));
00045    }
00046 
00047 /**
00048 * Clamp
00049 */
00050 inline size_t clamp(size_t n, size_t lower_bound, size_t upper_bound)
00051    {
00052    if(n < lower_bound)
00053       return lower_bound;
00054    if(n > upper_bound)
00055       return upper_bound;
00056    return n;
00057    }
00058 
00059 }
00060 
00061 #endif