1 /*
2     Copyright (C) 2019 Julian Rüth
3 
4     This file is part of Arb.
5 
6     Arb is free software: you can redistribute it and/or modify it under
7     the terms of the GNU Lesser General Public License (LGPL) as published
8     by the Free Software Foundation; either version 2.1 of the License, or
9     (at your option) any later version.  See <http://www.gnu.org/licenses/>.
10 */
11 
12 #include <string.h>
13 
14 #include "arf.h"
15 
16 static void
arf_set_fmpz_2exp_dump(arf_t x,const fmpz_t m,const fmpz_t e)17 arf_set_fmpz_2exp_dump(arf_t x, const fmpz_t m, const fmpz_t e) {
18     if (fmpz_is_zero(m)) {
19         if (fmpz_get_si(e) == 0) arf_zero(x);
20         else if (fmpz_get_si(e) == -1) arf_pos_inf(x);
21         else if (fmpz_get_si(e) == -2) arf_neg_inf(x);
22         else if (fmpz_get_si(e) == -3) arf_nan(x);
23         else {
24             /* Impossible to happen; all the special values have been treated above. */
25             flint_abort();
26         }
27         return;
28     }
29 
30     arf_set_fmpz_2exp(x, m, e);
31 }
32 
33 int
arf_load_str(arf_t x,const char * data)34 arf_load_str(arf_t x, const char* data)
35 {
36     fmpz_t mantissa, exponent;
37     char * e_str;
38     char * m_str;
39     int err = 0;
40 
41     fmpz_init(mantissa);
42     fmpz_init(exponent);
43 
44     e_str = strchr(data, ' ');
45     if (e_str == NULL) return 1;
46 
47     m_str = (char*)flint_malloc(e_str - data + 1);
48     strncpy(m_str, data, e_str - data);
49     m_str[e_str - data] = '\0';
50     e_str++;
51 
52     err = fmpz_set_str(mantissa, m_str, 16);
53 
54     flint_free(m_str);
55 
56     if (err)
57     {
58         fmpz_clear(exponent);
59         fmpz_clear(mantissa);
60         return err;
61     }
62 
63     err = fmpz_set_str(exponent, e_str, 16);
64 
65     if (err)
66     {
67         fmpz_clear(exponent);
68         fmpz_clear(mantissa);
69         return err;
70     }
71 
72     arf_set_fmpz_2exp_dump(x, mantissa, exponent);
73 
74     fmpz_clear(exponent);
75     fmpz_clear(mantissa);
76 
77     return err;
78 }
79 
arf_load_file(arf_t x,FILE * stream)80 int arf_load_file(arf_t x, FILE* stream)
81 {
82     fmpz_t mantissa, exponent;
83     __mpz_struct *mpz_mantissa, *mpz_exponent;
84     int err;
85 
86     fmpz_init(mantissa);
87     fmpz_init(exponent);
88 
89     mpz_mantissa = _fmpz_promote(mantissa);
90     mpz_exponent = _fmpz_promote(exponent);
91 
92     err = 0;
93 
94     if (mpz_inp_str(mpz_mantissa, stream, 16) == 0)
95         err = 1;
96 
97     if (!err && mpz_inp_str(mpz_exponent, stream, 16) == 0)
98         err = 1;
99 
100     _fmpz_demote_val(mantissa);
101     _fmpz_demote_val(exponent);
102 
103     if (!err)
104         arf_set_fmpz_2exp_dump(x, mantissa, exponent);
105 
106     fmpz_clear(mantissa);
107     fmpz_clear(exponent);
108 
109     return err;
110 }
111 
112