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