[Title] Add packaging/nettle.spec to build nettle on OBS system
[external/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 HAVE_LIBGMP
11 #include "bignum.h"
12
13 static void
14 test_bignum(const char *hex, unsigned length, const uint8_t *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, length, base256);
22
23   if (mpz_cmp(a, b))
24     FAIL();
25
26   buf = xalloc(length + 1);
27   memset(buf, 17, length + 1);
28
29   nettle_mpz_get_str_256(length, buf, a);
30   if (!MEMEQ(length, buf, base256))
31     FAIL();
32
33   if (buf[length] != 17)
34     FAIL();
35
36   mpz_clear(a); mpz_clear(b);
37   free(buf);
38 }
39
40 static void
41 test_size(long x, unsigned size)
42 {
43   mpz_t t;
44
45   mpz_init_set_si(t, x);
46   ASSERT(nettle_mpz_sizeinbase_256_s(t) == size);
47   mpz_clear(t);
48 }
49 #endif /* HAVE_LIBGMP */
50
51
52 int
53 test_main(void)
54 {
55 #if HAVE_LIBGMP
56   test_size(0, 1);
57   test_size(1, 1);
58   test_size(0x7f, 1);
59   test_size(0x80, 2);
60   test_size(0x81, 2);
61   test_size(0xff, 2);
62   test_size(0x100, 2);
63   test_size(0x101, 2);
64   test_size(0x1111, 2);
65   test_size(0x7fff, 2);
66   test_size(0x8000, 3);
67   test_size(0x8001, 3);
68
69   test_size(-      1, 1); /*     ff */
70   test_size(-   0x7f, 1); /*     81 */
71   test_size(-   0x80, 1); /*     80 */
72   test_size(-   0x81, 2); /*   ff7f */
73   test_size(-   0xff, 2); /*   ff01 */
74   test_size(-  0x100, 2); /*   ff00 */
75   test_size(-  0x101, 2); /*   feff */
76   test_size(- 0x1111, 2); /*   eeef */
77   test_size(- 0x7fff, 2); /*   8001 */
78   test_size(- 0x8000, 2); /*   8000 */
79   test_size(- 0x8001, 3); /* ff7fff */
80
81   test_bignum("0", HL("00"));
82   test_bignum("010203040506", HL("010203040506"));
83   test_bignum("80010203040506", HL("0080010203040506"));
84
85   test_bignum(   "-1", HL(    "ff"));
86   test_bignum(  "-7f", HL(    "81"));
87   test_bignum(  "-80", HL(    "80"));
88   test_bignum(  "-81", HL(  "ff7f"));
89   test_bignum("-7fff", HL(  "8001"));
90   test_bignum("-8000", HL(  "8000"));
91   test_bignum("-8001", HL("ff7fff"));
92   
93   SUCCESS();
94 #else /* !HAVE_LIBGMP */
95   SKIP();
96 #endif /* !HAVE_LIBGMP */
97 }