beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / setbit.c
blob3c2c139f987a24e3f8ae9f7f45ff11e728483e08
1 /* mpz_setbit -- set a specified bit.
3 Copyright 1991, 1993-1995, 1997, 1999, 2001, 2002, 2012 Free Software
4 Foundation, Inc.
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of either:
11 * the GNU Lesser General Public License as published by the Free
12 Software Foundation; either version 3 of the License, or (at your
13 option) any later version.
17 * the GNU General Public License as published by the Free Software
18 Foundation; either version 2 of the License, or (at your option) any
19 later version.
21 or both in parallel, as here.
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26 for more details.
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library. If not,
30 see https://www.gnu.org/licenses/. */
32 #include "gmp.h"
33 #include "gmp-impl.h"
35 void
36 mpz_setbit (mpz_ptr d, mp_bitcnt_t bit_idx)
38 mp_size_t dsize = SIZ (d);
39 mp_ptr dp = PTR (d);
40 mp_size_t limb_idx;
41 mp_limb_t mask;
43 limb_idx = bit_idx / GMP_NUMB_BITS;
44 mask = CNST_LIMB(1) << (bit_idx % GMP_NUMB_BITS);
45 if (dsize >= 0)
47 if (limb_idx < dsize)
49 dp[limb_idx] |= mask;
51 else
53 /* Ugh. The bit should be set outside of the end of the
54 number. We have to increase the size of the number. */
55 dp = MPZ_REALLOC (d, limb_idx + 1);
56 SIZ (d) = limb_idx + 1;
57 MPN_ZERO (dp + dsize, limb_idx - dsize);
58 dp[limb_idx] = mask;
61 else
63 /* Simulate two's complement arithmetic, i.e. simulate
64 1. Set OP = ~(OP - 1) [with infinitely many leading ones].
65 2. Set the bit.
66 3. Set OP = ~OP + 1. */
68 dsize = -dsize;
70 if (limb_idx < dsize)
72 mp_size_t zero_bound;
73 /* No index upper bound on this loop, we're sure there's a non-zero limb
74 sooner or later. */
75 zero_bound = 0;
76 while (dp[zero_bound] == 0)
77 zero_bound++;
79 if (limb_idx > zero_bound)
81 mp_limb_t dlimb;
82 dlimb = dp[limb_idx] & ~mask;
83 dp[limb_idx] = dlimb;
85 if (UNLIKELY ((dlimb == 0) + limb_idx == dsize)) /* dsize == limb_idx + 1 */
87 /* high limb became zero, must normalize */
88 MPN_NORMALIZE (dp, limb_idx);
89 SIZ (d) = -limb_idx;
92 else if (limb_idx == zero_bound)
94 dp[limb_idx] = ((dp[limb_idx] - 1) & ~mask) + 1;
95 ASSERT (dp[limb_idx] != 0);
97 else
99 MPN_DECR_U (dp + limb_idx, dsize - limb_idx, mask);
100 dsize -= dp[dsize - 1] == 0;
101 SIZ (d) = -dsize;