Austin Schuh | bb1338c | 2024-06-15 19:31:16 -0700 | [diff] [blame] | 1 | /* mpz_ui_sub -- Subtract an unsigned one-word integer and an mpz_t. |
| 2 | |
| 3 | Copyright 2002, 2004, 2015 Free Software Foundation, Inc. |
| 4 | |
| 5 | This file is part of the GNU MP Library. |
| 6 | |
| 7 | The GNU MP Library is free software; you can redistribute it and/or modify |
| 8 | it under the terms of either: |
| 9 | |
| 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. |
| 13 | |
| 14 | or |
| 15 | |
| 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. |
| 19 | |
| 20 | or both in parallel, as here. |
| 21 | |
| 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. |
| 26 | |
| 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/. */ |
| 30 | |
| 31 | #include "gmp-impl.h" |
| 32 | |
| 33 | void |
| 34 | mpz_ui_sub (mpz_ptr w, unsigned long int uval, mpz_srcptr v) |
| 35 | { |
| 36 | mp_ptr vp, wp; |
| 37 | mp_size_t vn, wn; |
| 38 | mp_limb_t cy; |
| 39 | |
| 40 | #if BITS_PER_ULONG > GMP_NUMB_BITS /* avoid warnings about shift amount */ |
| 41 | if (uval > GMP_NUMB_MAX) |
| 42 | { |
| 43 | mpz_t u; |
| 44 | mp_limb_t ul[2]; |
| 45 | PTR(u) = ul; |
| 46 | ul[0] = uval & GMP_NUMB_MASK; |
| 47 | ul[1] = uval >> GMP_NUMB_BITS; |
| 48 | SIZ(u) = 2; |
| 49 | mpz_sub (w, u, v); |
| 50 | return; |
| 51 | } |
| 52 | #endif |
| 53 | |
| 54 | vn = SIZ(v); |
| 55 | |
| 56 | if (vn > 1) |
| 57 | { |
| 58 | wp = MPZ_REALLOC (w, vn); |
| 59 | vp = PTR(v); |
| 60 | mpn_sub_1 (wp, vp, vn, (mp_limb_t) uval); |
| 61 | wn = -(vn - (wp[vn - 1] == 0)); |
| 62 | } |
| 63 | else if (vn >= 0) |
| 64 | { |
| 65 | mp_limb_t vp0; |
| 66 | vp0 = PTR (v)[0] & - (mp_limb_t) vn; |
| 67 | wp = MPZ_NEWALLOC (w, 1); |
| 68 | if (uval >= vp0) |
| 69 | { |
| 70 | wp[0] = uval - vp0; |
| 71 | wn = wp[0] != 0; |
| 72 | } |
| 73 | else |
| 74 | { |
| 75 | wp[0] = vp0 - uval; |
| 76 | wn = -1; |
| 77 | } |
| 78 | } |
| 79 | else /* (vn < 0) */ |
| 80 | { |
| 81 | vn = -vn; |
| 82 | wp = MPZ_REALLOC (w, vn + 1); |
| 83 | vp = PTR(v); |
| 84 | cy = mpn_add_1 (wp, vp, vn, (mp_limb_t) uval); |
| 85 | wp[vn] = cy; |
| 86 | wn = vn + (cy != 0); |
| 87 | } |
| 88 | |
| 89 | SIZ(w) = wn; |
| 90 | } |