1 /* mpi-add.c - MPI functions
2 * Copyright (C) 1994, 1996, 1998, 2001, 2002,
3 * 2003 Free Software Foundation, Inc.
5 * This file is part of Libgcrypt.
7 * Note: This code is heavily based on the GNU MP Library.
8 * Actually it's the same code with only minor changes in the
9 * way the data is stored; this is to support the abstraction
10 * of an optional secure memory allocation which may be used
11 * to avoid revealing of sensitive data due to paging etc.
14 #include "mpi-internal.h"
17 * Add the unsigned integer V to the mpi-integer U and store the
18 * result in W. U and V may be the same.
20 void mpi_add_ui(MPI w, MPI u, unsigned long v)
23 mpi_size_t usize, wsize;
30 /* If not space for W (and possible carry), increase space. */
32 if (w->alloced < wsize)
35 /* These must be after realloc (U may be the same as W). */
39 if (!usize) { /* simple */
42 } else if (!usign) { /* mpi is not negative */
44 cy = mpihelp_add_1(wp, up, usize, v);
48 /* The signs are different. Need exact comparison to determine
49 * which operand to subtract from which.
51 if (usize == 1 && up[0] < v) {
55 mpihelp_sub_1(wp, up, usize, v);
56 /* Size can decrease with at most one limb. */
57 wsize = usize - (wp[usize-1] == 0);
67 void mpi_add(MPI w, MPI u, MPI v)
70 mpi_size_t usize, vsize, wsize;
71 int usign, vsign, wsign;
73 if (u->nlimbs < v->nlimbs) { /* Swap U and V. */
79 RESIZE_IF_NEEDED(w, wsize);
80 /* These must be after realloc (u or v may be the same as w). */
89 RESIZE_IF_NEEDED(w, wsize);
90 /* These must be after realloc (u or v may be the same as w). */
97 if (!vsize) { /* simple */
98 MPN_COPY(wp, up, usize);
101 } else if (usign != vsign) { /* different sign */
102 /* This test is right since USIZE >= VSIZE */
103 if (usize != vsize) {
104 mpihelp_sub(wp, up, usize, vp, vsize);
106 MPN_NORMALIZE(wp, wsize);
108 } else if (mpihelp_cmp(up, vp, usize) < 0) {
109 mpihelp_sub_n(wp, vp, up, usize);
111 MPN_NORMALIZE(wp, wsize);
115 mpihelp_sub_n(wp, up, vp, usize);
117 MPN_NORMALIZE(wp, wsize);
121 } else { /* U and V have same sign. Add them. */
122 mpi_limb_t cy = mpihelp_add(wp, up, usize, vp, vsize);
132 EXPORT_SYMBOL_GPL(mpi_add);
134 void mpi_sub(MPI w, MPI u, MPI v)
136 MPI vv = mpi_copy(v);
137 vv->sign = !vv->sign;
141 EXPORT_SYMBOL_GPL(mpi_sub);
143 void mpi_addm(MPI w, MPI u, MPI v, MPI m)
148 EXPORT_SYMBOL_GPL(mpi_addm);
150 void mpi_subm(MPI w, MPI u, MPI v, MPI m)
155 EXPORT_SYMBOL_GPL(mpi_subm);