int aws_mp_div_d()

in AWSCognitoIdentityProvider/Internal/JKBigInteger/LibTomMath/tommath.c [1205:1277]


int aws_mp_div_d(aws_mp_int *a, aws_mp_digit b, aws_mp_int *c, aws_mp_digit *d)
{
  aws_mp_int q;
  aws_mp_word w;
  aws_mp_digit t;
  int     res, ix;

  /* cannot divide by zero */
  if (b == 0) {
     return AWS_MP_VAL;
  }

  /* quick outs */
  if (b == 1 || aws_mp_iszero(a) == 1) {
     if (d != NULL) {
        *d = 0;
     }
     if (c != NULL) {
        return aws_mp_copy(a, c);
     }
     return AWS_MP_OKAY;
  }

  /* power of two ? */
  if (s_is_power_of_two(b, &ix) == 1) {
     if (d != NULL) {
        *d = a->dp[0] & ((((aws_mp_digit)1)<<ix) - 1);
     }
     if (c != NULL) {
        return aws_mp_div_2d(a, ix, c, NULL);
     }
     return AWS_MP_OKAY;
  }

#ifdef AWS_BN_MP_DIV_3_C
  /* three? */
  if (b == 3) {
     return aws_mp_div_3(a, c, d);
  }
#endif

  /* no easy answer [c'est la vie].  Just division */
  if ((res = aws_mp_init_size(&q, a->used)) != AWS_MP_OKAY) {
     return res;
  }
  
  q.used = a->used;
  q.sign = a->sign;
  w = 0;
  for (ix = a->used - 1; ix >= 0; ix--) {
     w = (w << ((aws_mp_word)AWS_DIGIT_BIT)) | ((aws_mp_word)a->dp[ix]);
     
     if (w >= b) {
        t = (aws_mp_digit)(w / b);
        w -= ((aws_mp_word)t) * ((aws_mp_word)b);
      } else {
        t = 0;
      }
      q.dp[ix] = (aws_mp_digit)t;
  }
  
  if (d != NULL) {
     *d = (aws_mp_digit)w;
  }
  
  if (c != NULL) {
      aws_mp_clamp(&q);
      aws_mp_exch(&q, c);
  }
    aws_mp_clear(&q);
  
  return res;
}