[project @ 1998-11-26 09:17:22 by sof]
[ghc-hetmet.git] / ghc / runtime / gmp / mpq_inv.c
1 /* mpq_inv(dest,src) -- invert a rational number, i.e. set DEST to SRC
2    with the numerator and denominator swapped.
3
4 Copyright (C) 1991 Free Software Foundation, Inc.
5
6 This file is part of the GNU MP Library.
7
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 The GNU MP Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with the GNU MP Library; see the file COPYING.  If not, write to
20 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
21
22 #include "gmp.h"
23 #include "gmp-impl.h"
24
25 void
26 #ifdef __STDC__
27 mpq_inv (MP_RAT *dest, const MP_RAT *src)
28 #else
29 mpq_inv (dest, src)
30      MP_RAT *dest;
31      const MP_RAT *src;
32 #endif
33 {
34   mp_size num_size = src->num.size;
35   mp_size den_size = src->den.size;
36
37   if (num_size == 0)
38     num_size = 1 / num_size;    /* Divide by zero!  */
39
40   if (num_size < 0)
41     {
42       num_size = -num_size;
43       den_size = -den_size;
44     }
45   dest->den.size = num_size;
46   dest->num.size = den_size;
47
48   /* If dest == src we may just swap the numerator and denominator, but
49      we have to ensure the new denominator is positive.  */
50
51   if (dest == src)
52     {
53       mp_size alloc = dest->num.alloc;
54       mp_ptr limb_ptr = dest->num.d;
55
56       dest->num.alloc = dest->den.alloc;
57       dest->num.d = dest->den.d;
58
59       dest->den.alloc = alloc;
60       dest->den.d = limb_ptr;
61     }
62   else
63     {
64       den_size = ABS (den_size);
65       if (dest->num.alloc < den_size)
66         _mpz_realloc (&(dest->num), den_size);
67
68       if (dest->den.alloc < num_size)
69         _mpz_realloc (&(dest->den), num_size);
70
71       MPN_COPY (dest->num.d, src->den.d, den_size);
72       MPN_COPY (dest->den.d, src->num.d, num_size);
73     }
74 }