1 /* gmp-glue.c
2 
3    Copyright (C) 2013 Niels Möller
4    Copyright (C) 2013 Red Hat
5 
6    This file is part of GNU Nettle.
7 
8    GNU Nettle is free software: you can redistribute it and/or
9    modify it under the terms of either:
10 
11      * the GNU Lesser General Public License as published by the Free
12        Software Foundation; either version 3 of the License, or (at your
13        option) any later version.
14 
15    or
16 
17      * the GNU General Public License as published by the Free
18        Software Foundation; either version 2 of the License, or (at your
19        option) any later version.
20 
21    or both in parallel, as here.
22 
23    GNU Nettle is distributed in the hope that it will be useful,
24    but WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
26    General Public License for more details.
27 
28    You should have received copies of the GNU General Public License and
29    the GNU Lesser General Public License along with this program.  If
30    not, see http://www.gnu.org/licenses/.
31 */
32 
33 #if HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36 
37 #include "mpn-base256.h"
38 
39 void
mpn_set_base256(mp_limb_t * rp,mp_size_t rn,const uint8_t * xp,size_t xn)40 mpn_set_base256 (mp_limb_t *rp, mp_size_t rn,
41 		 const uint8_t *xp, size_t xn)
42 {
43   size_t xi;
44   mp_limb_t out;
45   unsigned bits;
46   for (xi = xn, out = bits = 0; xi > 0 && rn > 0; )
47     {
48       mp_limb_t in = xp[--xi];
49       out |= (in << bits) & GMP_NUMB_MASK;
50       bits += 8;
51       if (bits >= GMP_NUMB_BITS)
52 	{
53 	  *rp++ = out;
54 	  rn--;
55 
56 	  bits -= GMP_NUMB_BITS;
57 	  out = in >> (8 - bits);
58 	}
59     }
60   if (rn > 0)
61     {
62       *rp++ = out;
63       if (--rn > 0)
64 	mpn_zero (rp, rn);
65     }
66 }
67 
68 void
mpn_get_base256(uint8_t * rp,size_t rn,const mp_limb_t * xp,mp_size_t xn)69 mpn_get_base256 (uint8_t *rp, size_t rn,
70 		 const mp_limb_t *xp, mp_size_t xn)
71 {
72   unsigned bits;
73   mp_limb_t in;
74   for (bits = in = 0; xn > 0 && rn > 0; )
75     {
76       if (bits >= 8)
77 	{
78 	  rp[--rn] = in;
79 	  in >>= 8;
80 	  bits -= 8;
81 	}
82       else
83 	{
84 	  uint8_t old = in;
85 	  in = *xp++;
86 	  xn--;
87 	  rp[--rn] = old | (in << bits);
88 	  in >>= (8 - bits);
89 	  bits += GMP_NUMB_BITS - 8;
90 	}
91     }
92   while (rn > 0)
93     {
94       rp[--rn] = in;
95       in >>= 8;
96     }
97 }
98