1/* mpz_setbit -- set a specified bit.
2
3Copyright 1991, 1993-1995, 1997, 1999, 2001, 2002, 2012 Free Software
4Foundation, Inc.
5
6This file is part of the GNU MP Library.
7
8The GNU MP Library is free software; you can redistribute it and/or modify
9it under the terms of either:
10
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.
14
15or
16
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.
20
21or both in parallel, as here.
22
23The GNU MP Library is distributed in the hope that it will be useful, but
24WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
26for more details.
27
28You should have received copies of the GNU General Public License and the
29GNU Lesser General Public License along with the GNU MP Library.  If not,
30see https://www.gnu.org/licenses/.  */
31
32#include "gmp-impl.h"
33
34void
35mpz_setbit (mpz_ptr d, mp_bitcnt_t bit_idx)
36{
37  mp_size_t dsize = SIZ (d);
38  mp_ptr dp = PTR (d);
39  mp_size_t limb_idx;
40  mp_limb_t mask;
41
42  limb_idx = bit_idx / GMP_NUMB_BITS;
43  mask = CNST_LIMB(1) << (bit_idx % GMP_NUMB_BITS);
44  if (dsize >= 0)
45    {
46      if (limb_idx < dsize)
47	{
48	  dp[limb_idx] |= mask;
49	}
50      else
51	{
52	  /* Ugh.  The bit should be set outside of the end of the
53	     number.  We have to increase the size of the number.  */
54	  dp = MPZ_REALLOC (d, limb_idx + 1);
55	  SIZ (d) = limb_idx + 1;
56	  MPN_ZERO (dp + dsize, limb_idx - dsize);
57	  dp[limb_idx] = mask;
58	}
59    }
60  else
61    {
62      /* Simulate two's complement arithmetic, i.e. simulate
63	 1. Set OP = ~(OP - 1) [with infinitely many leading ones].
64	 2. Set the bit.
65	 3. Set OP = ~OP + 1.  */
66
67      dsize = -dsize;
68
69      if (limb_idx < dsize)
70	{
71	  mp_size_t zero_bound;
72	  /* No index upper bound on this loop, we're sure there's a non-zero limb
73	     sooner or later.  */
74	  zero_bound = 0;
75	  while (dp[zero_bound] == 0)
76	    zero_bound++;
77
78	  if (limb_idx > zero_bound)
79	    {
80	      mp_limb_t	 dlimb;
81	      dlimb = dp[limb_idx] & ~mask;
82	      dp[limb_idx] = dlimb;
83
84	      if (UNLIKELY ((dlimb == 0) + limb_idx == dsize)) /* dsize == limb_idx + 1 */
85		{
86		  /* high limb became zero, must normalize */
87		  MPN_NORMALIZE (dp, limb_idx);
88		  SIZ (d) = -limb_idx;
89		}
90	    }
91	  else if (limb_idx == zero_bound)
92	    {
93	      dp[limb_idx] = ((dp[limb_idx] - 1) & ~mask) + 1;
94	      ASSERT (dp[limb_idx] != 0);
95	    }
96	  else
97	    {
98	      MPN_DECR_U (dp + limb_idx, dsize - limb_idx, mask);
99	      dsize -= dp[dsize - 1] == 0;
100	      SIZ (d) = -dsize;
101	    }
102	}
103    }
104}
105