summaryrefslogtreecommitdiff
path: root/mpq/get_str.c
diff options
context:
space:
mode:
authorKevin Ryde <user42@zip.com.au>2001-04-02 23:19:57 +0200
committerKevin Ryde <user42@zip.com.au>2001-04-02 23:19:57 +0200
commitf04eabedef769624c373627f2c9688ad7ce23dc4 (patch)
treeb985457cbb9c573877d77a2ce486b0bb6c4cb5b7 /mpq/get_str.c
parentf80a68e1cbb1d05919694303b98882d3a10a27b0 (diff)
downloadgmp-f04eabedef769624c373627f2c9688ad7ce23dc4.tar.gz
* mpq/get_str.c: New file.
Diffstat (limited to 'mpq/get_str.c')
-rw-r--r--mpq/get_str.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/mpq/get_str.c b/mpq/get_str.c
new file mode 100644
index 000000000..e46245026
--- /dev/null
+++ b/mpq/get_str.c
@@ -0,0 +1,67 @@
+/* mpn_get_str -- mpq to string conversion.
+
+Copyright 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 <string.h>
+#include "gmp.h"
+#include "gmp-impl.h"
+
+char *
+mpq_get_str (char *str, int base, mpq_srcptr q)
+{
+ size_t str_alloc, len;
+
+ ASSERT (base >= 2);
+ ASSERT (base <= 36);
+
+ str_alloc = 0;
+ if (str == NULL)
+ {
+ /* This is an overestimate since we don't bother checking how much of
+ the high limbs of num and den are used. +2 for rounding up the
+ chars per bit of num and den. +3 for sign, slash and '\0'. */
+ str_alloc = ((size_t) ((ABS (q->_mp_num._mp_size) + q->_mp_den._mp_size)
+ * BITS_PER_MP_LIMB
+ * __mp_bases[base].chars_per_bit_exactly)) + 5;
+ str = (char *) (*__gmp_allocate_func) (str_alloc);
+ }
+
+ mpz_get_str (str, base, mpq_numref(q));
+ len = strlen (str);
+ if (! MPZ_EQUAL_1_P (mpq_denref (q)))
+ {
+ str[len++] = '/';
+ mpz_get_str (str+len, base, mpq_denref(q));
+ len += strlen (str+len);
+ }
+
+ ASSERT (len == strlen(str));
+ ASSERT (str_alloc == 0 ? 1 : len+1 <= str_alloc);
+ ASSERT (len+1 <= /* size recommended to applications */
+ mpz_sizeinbase (mpq_numref(q), base) +
+ mpz_sizeinbase (mpq_denref(q), base) + 3);
+
+ if (str_alloc != 0 && str_alloc != len+1)
+ str = (char *) (*__gmp_reallocate_func) (str, str_alloc, len+1);
+
+ return str;
+}