Friday 22 August 2008

Padding

A couple of C++ snippets for padding, one simple, one might be easier for a compiler to optimise though you'll have to do your own experiments to see which is faster for you in your program. Both of these are well defined for any value of (in, n) where n > 0 and sensibly defined where n < max_of_size_t + 1 - n. This will not work if either of the two types used are signed or non-integral.
inline size_t roundup_to(size_t n, size_t in)
{
in += n - 1;
in /= n;
in *= n;
return in;
}
inline size_t roundup_to(size_t n, size_t in)
{
in += n - 1;
in -= in % n;
return in;
}