Reorganisation of the source tree
[ghc-hetmet.git] / rts / gmp / mpz / inp_raw.c
1 /* mpz_inp_raw -- Input a mpz_t in raw, but endianess, and wordsize
2    independent format (as output by mpz_out_raw).
3
4 Copyright (C) 1991, 1993, 1994, 1995 Free Software Foundation, Inc.
5
6 This file is part of the GNU MP Library.
7
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or (at your
11 option) any later version.
12
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16 License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library; see the file COPYING.LIB.  If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21 MA 02111-1307, USA. */
22
23 #include <stdio.h>
24
25 #include "gmp.h"
26 #include "gmp-impl.h"
27
28 size_t
29 #if __STDC__
30 mpz_inp_raw (mpz_ptr x, FILE *stream)
31 #else
32 mpz_inp_raw (x, stream)
33      mpz_ptr x;
34      FILE *stream;
35 #endif
36 {
37   int i;
38   mp_size_t s;
39   mp_size_t xsize;
40   mp_ptr xp;
41   unsigned int c;
42   mp_limb_t x_limb;
43   mp_size_t in_bytesize;
44   int neg_flag;
45
46   if (stream == 0)
47     stream = stdin;
48
49   /* Read 4-byte size */
50   in_bytesize = 0;
51   for (i = 4 - 1; i >= 0; i--)
52     {
53       c = fgetc (stream);
54       in_bytesize = (in_bytesize << BITS_PER_CHAR) | c;
55     }
56
57   /* Size is stored as a 32 bit word; sign extend in_bytesize for non-32 bit
58      machines.  */
59   if (sizeof (mp_size_t) > 4)
60     in_bytesize |= (-(in_bytesize < 0)) << 31;
61
62   neg_flag = in_bytesize < 0;
63   in_bytesize = ABS (in_bytesize);
64   xsize = (in_bytesize + BYTES_PER_MP_LIMB - 1) / BYTES_PER_MP_LIMB;
65
66   if (xsize == 0)
67     {
68       x->_mp_size = 0;
69       return 4;                 /* we've read 4 bytes */
70     }
71
72   if (x->_mp_alloc < xsize)
73     _mpz_realloc (x, xsize);
74   xp = x->_mp_d;
75
76   x_limb = 0;
77   for (i = (in_bytesize - 1) % BYTES_PER_MP_LIMB; i >= 0; i--)
78     {
79       c = fgetc (stream);
80       x_limb = (x_limb << BITS_PER_CHAR) | c;
81     }
82   xp[xsize - 1] = x_limb;
83
84   for (s = xsize - 2; s >= 0; s--)
85     {
86       x_limb = 0;
87       for (i = BYTES_PER_MP_LIMB - 1; i >= 0; i--)
88         {
89           c = fgetc (stream);
90           x_limb = (x_limb << BITS_PER_CHAR) | c;
91         }
92       xp[s] = x_limb;
93     }
94
95   if (c == EOF)
96     return 0;                   /* error */
97
98   MPN_NORMALIZE (xp, xsize);
99   x->_mp_size = neg_flag ? -xsize : xsize;
100   return in_bytesize + 4;
101 }