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