602554b539416be05128a50ec27224097415fdaa
[platform/upstream/nettle.git] / testsuite / bignum-test.c
1 #include "testutils.h"
2
3 #if HAVE_CONFIG_H
4 #include "config.h"
5 #endif
6
7 #include <stdlib.h>
8 #include <string.h>
9
10 #if WITH_HOGWEED
11 #include "bignum.h"
12
13 static void
14 test_bignum(const char *hex, const struct tstring *base256)
15 {
16   mpz_t a;
17   mpz_t b;
18   uint8_t *buf;
19   
20   mpz_init_set_str(a, hex, 16);
21   nettle_mpz_init_set_str_256_s(b, base256->length, base256->data);
22
23   ASSERT(mpz_cmp(a, b) == 0);
24
25   buf = xalloc(base256->length + 1);
26   memset(buf, 17, base256->length + 1);
27
28   nettle_mpz_get_str_256(base256->length, buf, a);
29   ASSERT(MEMEQ(base256->length, buf, base256->data));
30
31   ASSERT(buf[base256->length] == 17);
32
33   mpz_clear(a); mpz_clear(b);
34   free(buf);
35 }
36
37 static void
38 test_size(long x, unsigned size)
39 {
40   mpz_t t;
41
42   mpz_init_set_si(t, x);
43   ASSERT(nettle_mpz_sizeinbase_256_s(t) == size);
44   mpz_clear(t);
45 }
46 #endif /* WITH_HOGWEED */
47
48
49 void
50 test_main(void)
51 {
52 #if WITH_HOGWEED
53   test_size(0, 1);
54   test_size(1, 1);
55   test_size(0x7f, 1);
56   test_size(0x80, 2);
57   test_size(0x81, 2);
58   test_size(0xff, 2);
59   test_size(0x100, 2);
60   test_size(0x101, 2);
61   test_size(0x1111, 2);
62   test_size(0x7fff, 2);
63   test_size(0x8000, 3);
64   test_size(0x8001, 3);
65
66   test_size(-      1, 1); /*     ff */
67   test_size(-   0x7f, 1); /*     81 */
68   test_size(-   0x80, 1); /*     80 */
69   test_size(-   0x81, 2); /*   ff7f */
70   test_size(-   0xff, 2); /*   ff01 */
71   test_size(-  0x100, 2); /*   ff00 */
72   test_size(-  0x101, 2); /*   feff */
73   test_size(- 0x1111, 2); /*   eeef */
74   test_size(- 0x7fff, 2); /*   8001 */
75   test_size(- 0x8000, 2); /*   8000 */
76   test_size(- 0x8001, 3); /* ff7fff */
77
78   test_bignum("0", SHEX("00"));
79   test_bignum("010203040506", SHEX("010203040506"));
80   test_bignum("80010203040506", SHEX("0080010203040506"));
81
82   test_bignum(   "-1", SHEX(    "ff"));
83   test_bignum(  "-7f", SHEX(    "81"));
84   test_bignum(  "-80", SHEX(    "80"));
85   test_bignum(  "-81", SHEX(  "ff7f"));
86   test_bignum("-7fff", SHEX(  "8001"));
87   test_bignum("-8000", SHEX(  "8000"));
88   test_bignum("-8001", SHEX("ff7fff"));
89   
90 #else /* !WITH_HOGWEED */
91   SKIP();
92 #endif /* !WITH_HOGWEED */
93 }