github.com/aergoio/aergo@v1.3.1/libtool/src/gmp-6.1.2/mpq/get_str.c (about)

     1  /* mpq_get_str -- mpq to string conversion.
     2  
     3  Copyright 2001, 2002, 2006, 2011 Free Software Foundation, Inc.
     4  
     5  This file is part of the GNU MP Library.
     6  
     7  The GNU MP Library is free software; you can redistribute it and/or modify
     8  it 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  
    14  or
    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  
    20  or both in parallel, as here.
    21  
    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.
    26  
    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/.  */
    30  
    31  #include <stdio.h>
    32  #include <string.h>
    33  #include "gmp.h"
    34  #include "gmp-impl.h"
    35  #include "longlong.h"
    36  
    37  char *
    38  mpq_get_str (char *str, int base, mpq_srcptr q)
    39  {
    40    size_t  str_alloc, len;
    41  
    42    if (base > 62 || base < -36)
    43      return NULL;
    44  
    45    str_alloc = 0;
    46    if (str == NULL)
    47      {
    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;
    53  
    54        str = (char *) (*__gmp_allocate_func) (str_alloc);
    55      }
    56  
    57    mpz_get_str (str, base, mpq_numref(q));
    58    len = strlen (str);
    59    if (! MPZ_EQUAL_1_P (mpq_denref (q)))
    60      {
    61        str[len++] = '/';
    62        mpz_get_str (str+len, base, mpq_denref(q));
    63        len += strlen (str+len);
    64      }
    65  
    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);
    71  
    72    if (str_alloc != 0)
    73      __GMP_REALLOCATE_FUNC_MAYBE_TYPE (str, str_alloc, len+1, char);
    74  
    75    return str;
    76  }