utils: Add utility function to calculate padding length

This commit is contained in:
Tobias Brunner
2013-10-17 10:25:34 +02:00
parent 32fef0c6e9
commit 812ae898bf
2 changed files with 24 additions and 13 deletions
+8 -1
View File
@@ -167,11 +167,18 @@ START_TEST(test_untoh)
END_TEST END_TEST
/******************************************************************************* /*******************************************************************************
* round_up/down * pad_len/round_up/down
*/ */
START_TEST(test_round) START_TEST(test_round)
{ {
ck_assert_int_eq(pad_len(0, 4), 0);
ck_assert_int_eq(pad_len(1, 4), 3);
ck_assert_int_eq(pad_len(2, 4), 2);
ck_assert_int_eq(pad_len(3, 4), 1);
ck_assert_int_eq(pad_len(4, 4), 0);
ck_assert_int_eq(pad_len(5, 4), 3);
ck_assert_int_eq(round_up(0, 4), 0); ck_assert_int_eq(round_up(0, 4), 0);
ck_assert_int_eq(round_up(1, 4), 4); ck_assert_int_eq(round_up(1, 4), 4);
ck_assert_int_eq(round_up(2, 4), 4); ck_assert_int_eq(round_up(2, 4), 4);
+16 -12
View File
@@ -679,26 +679,30 @@ static inline u_int64_t untoh64(void *network)
} }
/** /**
* Round up size to be multiple of alignement * Get the padding required to make size a multiple of alignment
*/ */
static inline size_t round_up(size_t size, int alignement) static inline size_t pad_len(size_t size, size_t alignment)
{ {
int remainder; size_t remainder;
remainder = size % alignement; remainder = size % alignment;
if (remainder) return remainder ? alignment - remainder : 0;
{
size += alignement - remainder;
}
return size;
} }
/** /**
* Round down size to be a multiple of alignement * Round up size to be multiple of alignment
*/ */
static inline size_t round_down(size_t size, int alignement) static inline size_t round_up(size_t size, size_t alignment)
{ {
return size - (size % alignement); return size + pad_len(size, alignment);
}
/**
* Round down size to be a multiple of alignment
*/
static inline size_t round_down(size_t size, size_t alignment)
{
return size - (size % alignment);
} }
/** /**