summaryrefslogtreecommitdiff
path: root/mpz/inp_raw.c
blob: 0d3bbdfd594a607fc93159273247f90988235f17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* mpz_inp_raw -- Input a mpz_t in raw, but endianess, and wordsize
   independent format (as output by mpz_out_raw).

Copyright 1991, 1993, 1994, 1995, 2001 Free Software Foundation, Inc.

This file is part of the GNU MP Library.

The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version.

The GNU MP Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
License for more details.

You should have received a copy of the GNU Lesser General Public License
along with the GNU MP Library; see the file COPYING.LIB.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA. */

#include <stdio.h>

#include "gmp.h"
#include "gmp-impl.h"


#define BITS_PER_CHAR  8

size_t
mpz_inp_raw (mpz_ptr x, FILE *stream)
{
  int i;
  mp_size_t s;
  mp_size_t xsize;
  mp_ptr xp;
  unsigned int c;
  mp_limb_t x_limb;
  mp_size_t in_bytesize;
  int neg_flag;

  if (stream == 0)
    stream = stdin;

  /* Read 4-byte size */
  in_bytesize = 0;
  for (i = 4 - 1; i >= 0; i--)
    {
      c = fgetc (stream);
      in_bytesize = (in_bytesize << BITS_PER_CHAR) | c;
    }

  /* Size is stored as a 32 bit word; sign extend in_bytesize for non-32 bit
     machines.  */
  if (sizeof (mp_size_t) > 4)
    in_bytesize |= (-(in_bytesize < 0)) << 31;

  neg_flag = in_bytesize < 0;
  in_bytesize = ABS (in_bytesize);
  xsize = (in_bytesize + BYTES_PER_MP_LIMB - 1) / BYTES_PER_MP_LIMB;

  if (xsize == 0)
    {
      x->_mp_size = 0;
      return 4;			/* we've read 4 bytes */
    }

  if (x->_mp_alloc < xsize)
    _mpz_realloc (x, xsize);
  xp = x->_mp_d;

  x_limb = 0;
  for (i = (in_bytesize - 1) % BYTES_PER_MP_LIMB; i >= 0; i--)
    {
      c = fgetc (stream);
      x_limb = (x_limb << BITS_PER_CHAR) | c;
    }
  xp[xsize - 1] = x_limb;

  for (s = xsize - 2; s >= 0; s--)
    {
      x_limb = 0;
      for (i = BYTES_PER_MP_LIMB - 1; i >= 0; i--)
	{
	  c = fgetc (stream);
	  x_limb = (x_limb << BITS_PER_CHAR) | c;
	}
      xp[s] = x_limb;
    }

  if (c == EOF)
    return 0;			/* error */

  MPN_NORMALIZE (xp, xsize);
  x->_mp_size = neg_flag ? -xsize : xsize;
  return in_bytesize + 4;
}