(root)/
gmp-6.3.0/
mpq/
set_str.c
       1  /* mpq_set_str -- string to mpq conversion.
       2  
       3  Copyright 2001, 2002, 2015, 2018 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-impl.h"
      34  
      35  
      36  /* FIXME: Would like an mpz_set_mem (or similar) accepting a pointer and
      37     length so we wouldn't have to copy the numerator just to null-terminate
      38     it.  */
      39  
      40  int
      41  mpq_set_str (mpq_ptr q, const char *str, int base)
      42  {
      43    const char  *slash;
      44    char        *num;
      45    size_t      numlen;
      46    int         ret;
      47  
      48    slash = strchr (str, '/');
      49    if (slash == NULL)
      50      {
      51        SIZ(DEN(q)) = 1;
      52        MPZ_NEWALLOC (DEN(q), 1)[0] = 1;
      53  
      54        return mpz_set_str (mpq_numref(q), str, base);
      55      }
      56  
      57    numlen = slash - str;
      58    num = __GMP_ALLOCATE_FUNC_TYPE (numlen+1, char);
      59    memcpy (num, str, numlen);
      60    num[numlen] = '\0';
      61    ret = mpz_set_str (mpq_numref(q), num, base);
      62    __GMP_FREE_FUNC_TYPE (num, numlen+1, char);
      63  
      64    if (ret != 0)
      65      return ret;
      66  
      67    return mpz_set_str (mpq_denref(q), slash+1, base);
      68  }