Statistics
| Branch: | Revision:

iof-bird / bird-2.0.1 / lib / checksum_test.c @ 6b3f1a54

History | View | Annotate | Download (1.72 KB)

1
/*
2
 *        BIRD Library -- IP One-Complement Checksum Tests
3
 *
4
 *        (c) 2015 CZ.NIC z.s.p.o.
5
 *
6
 *        Can be freely distributed and used under the terms of the GNU GPL.
7
 */
8

    
9
#include <stdio.h>
10

    
11
#include "test/birdtest.h"
12

    
13
#include "lib/checksum.h"
14

    
15
#define MAX_NUM 10000
16

    
17
static u16
18
ipsum_calculate_expected(u32 *a)
19
{
20
  int i;
21
  u32 sum = 0;
22

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

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

    
31
    u16 carry = sum >> 16;
32
    sum = (sum & 0xffff) + carry;
33
    bt_debug("carry) \t0x%08X \n\n", sum);
34
  }
35
  bt_debug("sum) \t0x%08X \n", sum);
36

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

    
40
  return sum;
41
}
42

    
43
static int
44
t_calculate(void)
45
{
46
  u32 a[MAX_NUM];
47
  int i;
48

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

    
52
  u16 sum_calculated   = ipsum_calculate(a, sizeof(a), NULL);
53
  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);
54
  bt_assert(sum_calculated == sum_calculated_2);
55

    
56
  u16 sum_expected = ipsum_calculate_expected(a);
57

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

    
61
  bt_assert(sum_calculated == sum_expected);
62

    
63
  return 1;
64
}
65

    
66
static int
67
t_verify(void)
68
{
69
  u32 a[MAX_NUM+1];
70
  int i;
71

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

    
75
  u16 sum = ipsum_calculate_expected(a);
76

    
77
  a[MAX_NUM] = sum;
78

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

    
81
  return 1;
82
}
83

    
84

    
85
int
86
main(int argc, char *argv[])
87
{
88
  bt_init(argc, argv);
89

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

    
93
  return bt_exit_value();
94
}