beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpq / get_str.c
blob8fa0de1cd744aac301d71245ffc3ee958e18f73f
1 /* mpq_get_str -- mpq to string conversion.
3 Copyright 2001, 2002, 2006, 2011 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
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.
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.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include <stdio.h>
32 #include <string.h>
33 #include "gmp.h"
34 #include "gmp-impl.h"
35 #include "longlong.h"
37 char *
38 mpq_get_str (char *str, int base, mpq_srcptr q)
40 size_t str_alloc, len;
42 if (base > 62 || base < -36)
43 return NULL;
45 str_alloc = 0;
46 if (str == NULL)
48 /* This is an overestimate since we don't bother checking how much of
49 the high limbs of num and den are used. +2 for rounding up the
50 chars per bit of num and den. +3 for sign, slash and '\0'. */
51 DIGITS_IN_BASE_PER_LIMB (str_alloc, ABSIZ(NUM(q)) + SIZ(DEN(q)), ABS(base));
52 str_alloc += 6;
54 str = (char *) (*__gmp_allocate_func) (str_alloc);
57 mpz_get_str (str, base, mpq_numref(q));
58 len = strlen (str);
59 if (! MPZ_EQUAL_1_P (mpq_denref (q)))
61 str[len++] = '/';
62 mpz_get_str (str+len, base, mpq_denref(q));
63 len += strlen (str+len);
66 ASSERT (len == strlen(str));
67 ASSERT (str_alloc == 0 || len+1 <= str_alloc);
68 ASSERT (len+1 <= /* size recommended to applications */
69 mpz_sizeinbase (mpq_numref(q), ABS(base)) +
70 mpz_sizeinbase (mpq_denref(q), ABS(base)) + 3);
72 if (str_alloc != 0)
73 __GMP_REALLOCATE_FUNC_MAYBE_TYPE (str, str_alloc, len+1, char);
75 return str;