[project @ 1996-01-08 20:28:12 by partain]
[ghc.git] / ghc / runtime / gmp / mpz_com.c
1 /* mpz_com(MP_INT *dst, MP_INT *src) -- Assign the bit-complemented value of
2 SRC to DST.
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 mpz_com (MP_INT *dst, const MP_INT *src)
28 #else
29 mpz_com (dst, src)
30 MP_INT *dst;
31 const MP_INT *src;
32 #endif
33 {
34 mp_size size = src->size;
35 mp_srcptr src_ptr;
36 mp_ptr dst_ptr;
37
38 if (size >= 0)
39 {
40 /* As with infinite precision: one's complement, two's complement.
41 But this can be simplified using the identity -x = ~x + 1.
42 So we're going to compute (~~x) + 1 = x + 1! */
43
44 if (dst->alloc < size + 1)
45 _mpz_realloc (dst, size + 1);
46
47 src_ptr = src->d;
48 dst_ptr = dst->d;
49
50 if (size == 0)
51 {
52 /* Special case, as mpn_add wants the first arg's size >= the
53 second arg's size. */
54 dst_ptr[0] = 1;
55 dst->size = -1;
56 return;
57 }
58
59 {
60 mp_limb one = 1;
61 int cy;
62
63 cy = mpn_add (dst_ptr, src_ptr, size, &one, 1);
64 if (cy)
65 {
66 dst_ptr[size] = cy;
67 size++;
68 }
69 }
70
71 /* Store a negative size, to indicate ones-extension. */
72 dst->size = -size;
73 }
74 else
75 {
76 /* As with infinite precision: two's complement, then one's complement.
77 But that can be simplified using the identity -x = ~(x - 1).
78 So we're going to compute ~~(x - 1) = x - 1! */
79 size = -size;
80
81 if (dst->alloc < size)
82 _mpz_realloc (dst, size);
83
84 src_ptr = src->d;
85 dst_ptr = dst->d;
86
87 {
88 mp_limb one = 1;
89
90 size += mpn_sub (dst_ptr, src_ptr, size, &one, 1);
91 }
92
93 /* Store a positive size, to indicate zero-extension. */
94 dst->size = size;
95 }
96 }