xref: /netbsd-src/external/lgpl3/gmp/dist/mpz/com.c (revision 6d322f2f4598f0d8a138f10ea648ec4fabe41f8b)
1 /* mpz_com(mpz_ptr dst, mpz_ptr src) -- Assign the bit-complemented value of
2    SRC to DST.
3 
4 Copyright 1991, 1993, 1994, 1996, 2001, 2003, 2012 Free Software Foundation,
5 Inc.
6 
7 This file is part of the GNU MP Library.
8 
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
13 
14 The GNU MP Library is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17 License for more details.
18 
19 You should have received a copy of the GNU Lesser General Public License
20 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
21 
22 #include "gmp.h"
23 #include "gmp-impl.h"
24 
25 void
26 mpz_com (mpz_ptr dst, mpz_srcptr src)
27 {
28   mp_size_t size = SIZ (src);
29   mp_srcptr src_ptr;
30   mp_ptr dst_ptr;
31 
32   if (size >= 0)
33     {
34       /* As with infinite precision: one's complement, two's complement.
35 	 But this can be simplified using the identity -x = ~x + 1.
36 	 So we're going to compute (~~x) + 1 = x + 1!  */
37 
38       if (UNLIKELY (size == 0))
39 	{
40 	  /* special case, as mpn_add_1 wants size!=0 */
41 	  PTR (dst)[0] = 1;
42 	  SIZ (dst) = -1;
43 	}
44       else
45 	{
46 	  mp_limb_t cy;
47 
48 	  dst_ptr = MPZ_REALLOC (dst, size + 1);
49 
50 	  src_ptr = PTR (src);
51 
52 	  cy = mpn_add_1 (dst_ptr, src_ptr, size, (mp_limb_t) 1);
53 	  dst_ptr[size] = cy;
54 	  size += (cy != 0);
55 
56 	  /* Store a negative size, to indicate ones-extension.  */
57 	  SIZ (dst) = -size;
58       }
59     }
60   else
61     {
62       /* As with infinite precision: two's complement, then one's complement.
63 	 But that can be simplified using the identity -x = ~(x - 1).
64 	 So we're going to compute ~~(x - 1) = x - 1!  */
65       size = -size;
66 
67       dst_ptr = MPZ_REALLOC (dst, size);
68 
69       src_ptr = PTR (src);
70 
71       mpn_sub_1 (dst_ptr, src_ptr, size, (mp_limb_t) 1);
72       size -= dst_ptr[size - 1] == 0;
73 
74       /* Store a positive size, to indicate zero-extension.  */
75       SIZ (dst) = size;
76     }
77 }
78