/* Copyright (c) 2009 Ian Piumarta
 * All rights reserved.
 * See the file COPYING for details.
 */

#include "_mpint.h"

/* r = r + ~a + 1 */

mp_digit_t mp_sub_d(mp_t *r, mp_digit_t d)
{
  if (!d) return 0;
  mp_digit_t c= 1;
  mp_size_t w= _mp_max(r->width, 1), i= 0;
  _mp_grow(r, w);
  {
    mp_digit2_t s= (mp_digit2_t)_mp_digitAt(r, i) + (mp_digit2_t)~d + c;
    _mp_digitAtPut(r, i++, s);
    c= (s >> MP_BITS) & 1;
  }
  while (i < w) {
    mp_digit2_t s= (mp_digit2_t)_mp_digitAt(r, i) + ~(mp_digit_t)0 + c;
    _mp_digitAtPut(r, i++, s);
    c= (s >> MP_BITS) & 1;
  }
  mp_normalise(r);
  return c;
}

