bn_mp_sub_d.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_SUB_D_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* single digit subtraction */
  6. mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c)
  7. {
  8. mp_digit *tmpa, *tmpc;
  9. mp_err err;
  10. int ix, oldused;
  11. /* grow c as required */
  12. if (c->alloc < (a->used + 1)) {
  13. if ((err = mp_grow(c, a->used + 1)) != MP_OKAY) {
  14. return err;
  15. }
  16. }
  17. /* if a is negative just do an unsigned
  18. * addition [with fudged signs]
  19. */
  20. if (a->sign == MP_NEG) {
  21. mp_int a_ = *a;
  22. a_.sign = MP_ZPOS;
  23. err = mp_add_d(&a_, b, c);
  24. c->sign = MP_NEG;
  25. /* clamp */
  26. mp_clamp(c);
  27. return err;
  28. }
  29. /* setup regs */
  30. oldused = c->used;
  31. tmpa = a->dp;
  32. tmpc = c->dp;
  33. /* if a <= b simply fix the single digit */
  34. if (((a->used == 1) && (a->dp[0] <= b)) || (a->used == 0)) {
  35. if (a->used == 1) {
  36. *tmpc++ = b - *tmpa;
  37. } else {
  38. *tmpc++ = b;
  39. }
  40. ix = 1;
  41. /* negative/1digit */
  42. c->sign = MP_NEG;
  43. c->used = 1;
  44. } else {
  45. mp_digit mu = b;
  46. /* positive/size */
  47. c->sign = MP_ZPOS;
  48. c->used = a->used;
  49. /* subtract digits, mu is carry */
  50. for (ix = 0; ix < a->used; ix++) {
  51. *tmpc = *tmpa++ - mu;
  52. mu = *tmpc >> (MP_SIZEOF_BITS(mp_digit) - 1u);
  53. *tmpc++ &= MP_MASK;
  54. }
  55. }
  56. /* zero excess digits */
  57. MP_ZERO_DIGITS(tmpc, oldused - ix);
  58. mp_clamp(c);
  59. return MP_OKAY;
  60. }
  61. #endif