bn_mp_add_d.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "tommath_private.h"
  2. #ifdef BN_MP_ADD_D_C
  3. /* LibTomMath, multiple-precision integer library -- Tom St Denis */
  4. /* SPDX-License-Identifier: Unlicense */
  5. /* single digit addition */
  6. mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c)
  7. {
  8. mp_err err;
  9. int ix, oldused;
  10. mp_digit *tmpa, *tmpc;
  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 and |a| >= b, call c = |a| - b */
  18. if ((a->sign == MP_NEG) && ((a->used > 1) || (a->dp[0] >= b))) {
  19. mp_int a_ = *a;
  20. /* temporarily fix sign of a */
  21. a_.sign = MP_ZPOS;
  22. /* c = |a| - b */
  23. err = mp_sub_d(&a_, b, c);
  24. /* fix sign */
  25. c->sign = MP_NEG;
  26. /* clamp */
  27. mp_clamp(c);
  28. return err;
  29. }
  30. /* old number of used digits in c */
  31. oldused = c->used;
  32. /* source alias */
  33. tmpa = a->dp;
  34. /* destination alias */
  35. tmpc = c->dp;
  36. /* if a is positive */
  37. if (a->sign == MP_ZPOS) {
  38. /* add digits, mu is carry */
  39. mp_digit mu = b;
  40. for (ix = 0; ix < a->used; ix++) {
  41. *tmpc = *tmpa++ + mu;
  42. mu = *tmpc >> MP_DIGIT_BIT;
  43. *tmpc++ &= MP_MASK;
  44. }
  45. /* set final carry */
  46. ix++;
  47. *tmpc++ = mu;
  48. /* setup size */
  49. c->used = a->used + 1;
  50. } else {
  51. /* a was negative and |a| < b */
  52. c->used = 1;
  53. /* the result is a single digit */
  54. if (a->used == 1) {
  55. *tmpc++ = b - a->dp[0];
  56. } else {
  57. *tmpc++ = b;
  58. }
  59. /* setup count so the clearing of oldused
  60. * can fall through correctly
  61. */
  62. ix = 1;
  63. }
  64. /* sign always positive */
  65. c->sign = MP_ZPOS;
  66. /* now zero to oldused */
  67. MP_ZERO_DIGITS(tmpc, oldused - ix);
  68. mp_clamp(c);
  69. return MP_OKAY;
  70. }
  71. #endif