checksum_test.c 1.72 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/*
 *	BIRD Library -- IP One-Complement Checksum Tests
 *
 *	(c) 2015 CZ.NIC z.s.p.o.
 *
 *	Can be freely distributed and used under the terms of the GNU GPL.
 */

#include <stdio.h>

#include "test/birdtest.h"

#include "lib/checksum.h"

#define MAX_NUM 10000

static u16
ipsum_calculate_expected(u32 *a)
{
  int i;
  u32 sum = 0;

  for(i = 0; i < MAX_NUM; i++)
  {
    sum += a[i] & 0xffff;
    bt_debug("low) \t0x%08X \n", sum);

    sum += a[i] >> 16;
    bt_debug("high) \t0x%08X \n", sum);

    u16 carry = sum >> 16;
    sum = (sum & 0xffff) + carry;
    bt_debug("carry) \t0x%08X \n\n", sum);
  }
  bt_debug("sum) \t0x%08X \n", sum);

  sum = sum ^ 0xffff;
  bt_debug("~sum) \t0x%08X \n", sum);

  return sum;
}

static int
t_calculate(void)
{
  u32 a[MAX_NUM];
  int i;

  for (i = 0; i < MAX_NUM; i++)
    a[i] = bt_random();

  u16 sum_calculated   = ipsum_calculate(a, sizeof(a), NULL);
  u16 sum_calculated_2 = ipsum_calculate(&a[0], sizeof(u32)*(MAX_NUM/2), &a[MAX_NUM/2], sizeof(u32)*(MAX_NUM - MAX_NUM/2), NULL);
  bt_assert(sum_calculated == sum_calculated_2);

  u16 sum_expected = ipsum_calculate_expected(a);

  bt_debug("sum_calculated: %08X \n", sum_calculated);
  bt_debug("sum_expected:   %08X \n", sum_expected);

  bt_assert(sum_calculated == sum_expected);

63
  return 1;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
}

static int
t_verify(void)
{
  u32 a[MAX_NUM+1];
  int i;

  for (i = 0; i < MAX_NUM; i++)
    a[i] = bt_random();

  u16 sum = ipsum_calculate_expected(a);

  a[MAX_NUM] = sum;

  bt_assert(ipsum_verify(a, sizeof(a), NULL));

81
  return 1;
82 83 84 85 86 87 88 89 90 91 92 93 94
}


int
main(int argc, char *argv[])
{
  bt_init(argc, argv);

  bt_test_suite(t_calculate, "Checksum of pseudo-random data");
  bt_test_suite(t_verify, "Verification of pseudo-random data.");

  return bt_exit_value();
}