utils: add round_up/down() helper functions
authorMartin Willi <martin@revosec.ch>
Mon, 22 Jul 2013 12:16:38 +0000 (14:16 +0200)
committerMartin Willi <martin@revosec.ch>
Mon, 29 Jul 2013 07:00:48 +0000 (09:00 +0200)
src/libstrongswan/tests/test_utils.c
src/libstrongswan/utils/utils.h

index 811882e..d9f1726 100644 (file)
@@ -166,6 +166,28 @@ START_TEST(test_untoh)
 END_TEST
 
 /*******************************************************************************
+ * round_up/down
+ */
+
+START_TEST(test_round)
+{
+       ck_assert_int_eq(round_up(0, 4), 0);
+       ck_assert_int_eq(round_up(1, 4), 4);
+       ck_assert_int_eq(round_up(2, 4), 4);
+       ck_assert_int_eq(round_up(3, 4), 4);
+       ck_assert_int_eq(round_up(4, 4), 4);
+       ck_assert_int_eq(round_up(5, 4), 8);
+
+       ck_assert_int_eq(round_down(0, 4), 0);
+       ck_assert_int_eq(round_down(1, 4), 0);
+       ck_assert_int_eq(round_down(2, 4), 0);
+       ck_assert_int_eq(round_down(3, 4), 0);
+       ck_assert_int_eq(round_down(4, 4), 4);
+       ck_assert_int_eq(round_down(5, 4), 4);
+}
+END_TEST
+
+/*******************************************************************************
  * memxor
  */
 
@@ -416,6 +438,10 @@ Suite *utils_suite_create()
        tcase_add_test(tc, test_untoh);
        suite_add_tcase(s, tc);
 
+       tc = tcase_create("round");
+       tcase_add_test(tc, test_round);
+       suite_add_tcase(s, tc);
+
        tc = tcase_create("memxor");
        tcase_add_test(tc, test_memxor);
        tcase_add_test(tc, test_memxor_aligned);
index 0e103de..d055f71 100644 (file)
@@ -671,6 +671,29 @@ static inline u_int64_t untoh64(void *network)
 }
 
 /**
+ * Round up size to be multiple of alignement
+ */
+static inline size_t round_up(size_t size, int alignement)
+{
+       int remainder;
+
+       remainder = size % alignement;
+       if (remainder)
+       {
+               size += alignement - remainder;
+       }
+       return size;
+}
+
+/**
+ * Round down size to be a multiple of alignement
+ */
+static inline size_t round_down(size_t size, int alignement)
+{
+       return size - (size % alignement);
+}
+
+/**
  * Special type to count references
  */
 typedef u_int refcount_t;