blob: d0cfb58dd1fd3ed3f194d1ecfb17abac90efc7b8 [file] [log] [blame]
Austin Schuhdace2a62020-08-18 10:56:48 -07001/* mpq_get_str -- mpq to string conversion.
2
3Copyright 2001, 2002, 2006, 2011, 2018 Free Software Foundation, Inc.
4
5This file is part of the GNU MP Library.
6
7The GNU MP Library is free software; you can redistribute it and/or modify
8it under the terms of either:
9
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
13
14or
15
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
19
20or both in parallel, as here.
21
22The GNU MP Library is distributed in the hope that it will be useful, but
23WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25for more details.
26
27You should have received copies of the GNU General Public License and the
28GNU Lesser General Public License along with the GNU MP Library. If not,
29see https://www.gnu.org/licenses/. */
30
31#include <stdio.h>
32#include <string.h>
33#include "gmp-impl.h"
34#include "longlong.h"
35
36char *
37mpq_get_str (char *str, int base, mpq_srcptr q)
38{
39 size_t str_alloc, len;
40
41 if (base > 62 || base < -36)
42 return NULL;
43
44 str_alloc = 0;
45 if (str == NULL)
46 {
47 /* This is an overestimate since we don't bother checking how much of
48 the high limbs of num and den are used. +2 for rounding up the
49 chars per bit of num and den. +3 for sign, slash and '\0'. */
50 if (ABS(base) < 2)
51 base = 10;
52 DIGITS_IN_BASE_PER_LIMB (str_alloc, ABSIZ(NUM(q)) + SIZ(DEN(q)), ABS(base));
53 str_alloc += 6;
54
55 str = __GMP_ALLOCATE_FUNC_TYPE (str_alloc, char);
56 }
57
58 mpz_get_str (str, base, mpq_numref(q));
59 len = strlen (str);
60 if (! MPZ_EQUAL_1_P (mpq_denref (q)))
61 {
62 str[len++] = '/';
63 mpz_get_str (str+len, base, mpq_denref(q));
64 len += strlen (str+len);
65 }
66
67 ASSERT (len == strlen(str));
68 ASSERT (str_alloc == 0 || len+1 <= str_alloc);
69 ASSERT (len+1 <= 3 + /* size recommended to applications */
70 (ABS(base) < 2 ?
71 mpz_sizeinbase (mpq_numref(q), 10) +
72 mpz_sizeinbase (mpq_denref(q), 10)
73 : mpz_sizeinbase (mpq_numref(q), ABS(base)) +
74 mpz_sizeinbase (mpq_denref(q), ABS(base))));
75
76 if (str_alloc != 0)
77 __GMP_REALLOCATE_FUNC_MAYBE_TYPE (str, str_alloc, len+1, char);
78
79 return str;
80}