libsodium 1.0.8
[tomato.git] / release / src / router / gmp / mpz / clrbit.c
blob2475efe1e5b79498c990d485387b44264de34259
1 /* mpz_clrbit -- clear a specified bit.
3 Copyright 1991, 1993-1995, 2001, 2002, 2012 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include "gmp.h"
32 #include "gmp-impl.h"
34 void
35 mpz_clrbit (mpz_ptr d, mp_bitcnt_t bit_idx)
37 mp_size_t dsize = SIZ (d);
38 mp_ptr dp = PTR (d);
39 mp_size_t limb_idx;
40 mp_limb_t mask;
42 limb_idx = bit_idx / GMP_NUMB_BITS;
43 mask = CNST_LIMB(1) << (bit_idx % GMP_NUMB_BITS);
44 if (dsize >= 0)
46 if (limb_idx < dsize)
48 mp_limb_t dlimb;
49 dlimb = dp[limb_idx] & ~mask;
50 dp[limb_idx] = dlimb;
52 if (UNLIKELY ((dlimb == 0) + limb_idx == dsize)) /* dsize == limb_idx + 1 */
54 /* high limb became zero, must normalize */
55 MPN_NORMALIZE (dp, limb_idx);
56 SIZ (d) = limb_idx;
59 else
62 else
64 /* Simulate two's complement arithmetic, i.e. simulate
65 1. Set OP = ~(OP - 1) [with infinitely many leading ones].
66 2. clear the bit.
67 3. Set OP = ~OP + 1. */
69 dsize = -dsize;
71 if (limb_idx < dsize)
73 mp_size_t zero_bound;
75 /* No index upper bound on this loop, we're sure there's a non-zero limb
76 sooner or later. */
77 zero_bound = 0;
78 while (dp[zero_bound] == 0)
79 zero_bound++;
81 if (limb_idx > zero_bound)
83 dp[limb_idx] |= mask;
85 else if (limb_idx == zero_bound)
87 mp_limb_t dlimb;
88 dlimb = (((dp[limb_idx] - 1) | mask) + 1) & GMP_NUMB_MASK;
89 dp[limb_idx] = dlimb;
91 if (dlimb == 0)
93 /* Increment at limb_idx + 1. Extend the number with a zero limb
94 for simplicity. */
95 dp = MPZ_REALLOC (d, dsize + 1);
96 dp[dsize] = 0;
97 MPN_INCR_U (dp + limb_idx + 1, dsize - limb_idx, 1);
98 dsize += dp[dsize];
100 SIZ (d) = -dsize;
103 else
106 else
108 /* Ugh. The bit should be cleared outside of the end of the
109 number. We have to increase the size of the number. */
110 dp = MPZ_REALLOC (d, limb_idx + 1);
111 SIZ (d) = -(limb_idx + 1);
112 MPN_ZERO (dp + dsize, limb_idx - dsize);
113 dp[limb_idx] = mask;