1 /*
2 * %CopyrightBegin%
3 *
4 * Copyright Ericsson AB 2002-2016. All Rights Reserved.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * %CopyrightEnd%
19 */
20
21 #include "eidef.h"
22
23 #if defined(HAVE_GMP_H) && defined(HAVE_LIBGMP)
24
25 #include <gmp.h>
26
27 #include "eidef.h"
28 #include "eiext.h"
29 #include "putget.h"
30 #include "ei_x_encode.h"
31
ei_encode_bignum(char * buf,int * index,mpz_t obj)32 int ei_encode_bignum(char *buf, int *index, mpz_t obj)
33 {
34 char *s = buf + *index;
35 char *s0 = s;
36 size_t count;
37 int mpz_sign = mpz_sgn(obj);
38
39 /*
40 * FIXME we could code into ERL_[SMALL_]INTEGER_EXT but to make
41 * this code simple for now we always code into ERL_SMALL_BIG_EXT
42 */
43
44 if (mpz_sign == 0) { /* Special case, bignum is zero */
45 if (!buf) s += 2;
46 else {
47 put8(s,ERL_SMALL_INTEGER_EXT);
48 put8(s,0);
49 }
50 } else {
51
52 if (!buf) {
53 int numb = 8; /* # bits in each external format limb */
54 s += (mpz_sizeinbase(obj, 2) + numb-1) / numb;
55 } else {
56 char *arityp;
57
58 put8(s,ERL_LARGE_BIG_EXT);
59 arityp = s; /* fill in later */
60 s += 4;
61 put8(s, mpz_sign == 1); /* save sign separately */
62 mpz_export(s, &count, -1, 1, 0, 0, obj);
63 s += count;
64 put32le(arityp, count);
65 }
66 }
67
68 *index += s-s0;
69
70 return 0;
71 }
72
ei_x_encode_bignum(ei_x_buff * x,mpz_t n)73 int ei_x_encode_bignum(ei_x_buff* x, mpz_t n)
74 {
75 int i = x->index;
76 ei_encode_bignum(NULL, &i, n);
77 if (!x_fix_buff(x, i))
78 return -1;
79 return ei_encode_bignum(x->buff, &x->index, n);
80 }
81
82 #endif /* HAVE_GMP_H && HAVE_LIBGMP */
83