1 // Copyright 2014 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Original code by Matt McCutchen, see the LICENSE file.
6
7 #include "BigInteger.hh"
8
operator =(const BigInteger & x)9 BigInteger& BigInteger::operator =(const BigInteger &x) {
10 // Calls like a = a have no effect
11 if (this == &x)
12 return *this;
13 // Copy sign
14 sign = x.sign;
15 // Copy the rest
16 mag = x.mag;
17 return *this;
18 }
19
BigInteger(const Blk * b,Index blen,Sign s)20 BigInteger::BigInteger(const Blk *b, Index blen, Sign s) : mag(b, blen) {
21 switch (s) {
22 case zero:
23 if (!mag.isZero())
24 abort();
25 sign = zero;
26 break;
27 case positive:
28 case negative:
29 // If the magnitude is zero, force the sign to zero.
30 sign = mag.isZero() ? zero : s;
31 break;
32 default:
33 /* g++ seems to be optimizing out this case on the assumption
34 * that the sign is a valid member of the enumeration. Oh well. */
35 abort();
36 }
37 }
38
BigInteger(const BigUnsigned & x,Sign s)39 BigInteger::BigInteger(const BigUnsigned &x, Sign s) : mag(x) {
40 switch (s) {
41 case zero:
42 if (!mag.isZero())
43 abort();
44 sign = zero;
45 break;
46 case positive:
47 case negative:
48 // If the magnitude is zero, force the sign to zero.
49 sign = mag.isZero() ? zero : s;
50 break;
51 default:
52 /* g++ seems to be optimizing out this case on the assumption
53 * that the sign is a valid member of the enumeration. Oh well. */
54 abort();
55 }
56 }
57
58 /* CONSTRUCTION FROM PRIMITIVE INTEGERS
59 * Same idea as in BigUnsigned.cc, except that negative input results in a
60 * negative BigInteger instead of an exception. */
61
62 // Done longhand to let us use initialization.
BigInteger(unsigned long x)63 BigInteger::BigInteger(unsigned long x) : mag(x) { sign = mag.isZero() ? zero : positive; }
BigInteger(unsigned int x)64 BigInteger::BigInteger(unsigned int x) : mag(x) { sign = mag.isZero() ? zero : positive; }
BigInteger(unsigned short x)65 BigInteger::BigInteger(unsigned short x) : mag(x) { sign = mag.isZero() ? zero : positive; }
66
67 // For signed input, determine the desired magnitude and sign separately.
68
69 namespace {
70 template <class X, class UX>
magOf(X x)71 BigInteger::Blk magOf(X x) {
72 /* UX(...) cast needed to stop short(-2^15), which negates to
73 * itself, from sign-extending in the conversion to Blk. */
74 return BigInteger::Blk(x < 0 ? UX(-x) : x);
75 }
76 template <class X>
signOf(X x)77 BigInteger::Sign signOf(X x) {
78 return (x == 0) ? BigInteger::zero
79 : (x > 0) ? BigInteger::positive
80 : BigInteger::negative;
81 }
82 }
83
BigInteger(long x)84 BigInteger::BigInteger(long x) : sign(signOf(x)), mag(magOf<long , unsigned long >(x)) {}
BigInteger(int x)85 BigInteger::BigInteger(int x) : sign(signOf(x)), mag(magOf<int , unsigned int >(x)) {}
BigInteger(short x)86 BigInteger::BigInteger(short x) : sign(signOf(x)), mag(magOf<short, unsigned short>(x)) {}
87
88 // CONVERSION TO PRIMITIVE INTEGERS
89
90 /* Reuse BigUnsigned's conversion to an unsigned primitive integer.
91 * The friend is a separate function rather than
92 * BigInteger::convertToUnsignedPrimitive to avoid requiring BigUnsigned to
93 * declare BigInteger. */
94 template <class X>
convertBigUnsignedToPrimitiveAccess(const BigUnsigned & a)95 inline X convertBigUnsignedToPrimitiveAccess(const BigUnsigned &a) {
96 return a.convertToPrimitive<X>();
97 }
98
99 template <class X>
convertToUnsignedPrimitive() const100 X BigInteger::convertToUnsignedPrimitive() const {
101 if (sign == negative)
102 abort();
103 else
104 return convertBigUnsignedToPrimitiveAccess<X>(mag);
105 }
106
107 /* Similar to BigUnsigned::convertToPrimitive, but split into two cases for
108 * nonnegative and negative numbers. */
109 template <class X, class UX>
convertToSignedPrimitive() const110 X BigInteger::convertToSignedPrimitive() const {
111 if (sign == zero)
112 return 0;
113 else if (mag.getLength() == 1) {
114 // The single block might fit in an X. Try the conversion.
115 Blk b = mag.getBlock(0);
116 if (sign == positive) {
117 X x = X(b);
118 if (x >= 0 && Blk(x) == b)
119 return x;
120 } else {
121 X x = -X(b);
122 /* UX(...) needed to avoid rejecting conversion of
123 * -2^15 to a short. */
124 if (x < 0 && Blk(UX(-x)) == b)
125 return x;
126 }
127 // Otherwise fall through.
128 }
129 abort();
130 }
131
toUnsignedLong() const132 unsigned long BigInteger::toUnsignedLong () const { return convertToUnsignedPrimitive<unsigned long > (); }
toUnsignedInt() const133 unsigned int BigInteger::toUnsignedInt () const { return convertToUnsignedPrimitive<unsigned int > (); }
toUnsignedShort() const134 unsigned short BigInteger::toUnsignedShort() const { return convertToUnsignedPrimitive<unsigned short> (); }
toLong() const135 long BigInteger::toLong () const { return convertToSignedPrimitive <long , unsigned long> (); }
toInt() const136 int BigInteger::toInt () const { return convertToSignedPrimitive <int , unsigned int> (); }
toShort() const137 short BigInteger::toShort () const { return convertToSignedPrimitive <short, unsigned short>(); }
138
139 // COMPARISON
compareTo(const BigInteger & x) const140 BigInteger::CmpRes BigInteger::compareTo(const BigInteger &x) const {
141 // A greater sign implies a greater number
142 if (sign < x.sign)
143 return less;
144 else if (sign > x.sign)
145 return greater;
146 else switch (sign) {
147 // If the signs are the same...
148 case zero:
149 return equal; // Two zeros are equal
150 case positive:
151 // Compare the magnitudes
152 return mag.compareTo(x.mag);
153 case negative:
154 // Compare the magnitudes, but return the opposite result
155 return CmpRes(-mag.compareTo(x.mag));
156 default:
157 abort();
158 }
159 }
160
161 /* COPY-LESS OPERATIONS
162 * These do some messing around to determine the sign of the result,
163 * then call one of BigUnsigned's copy-less operations. */
164
165 // See remarks about aliased calls in BigUnsigned.cc .
166 #define DTRT_ALIASED(cond, op) \
167 if (cond) { \
168 BigInteger tmpThis; \
169 tmpThis.op; \
170 *this = tmpThis; \
171 return; \
172 }
173
add(const BigInteger & a,const BigInteger & b)174 void BigInteger::add(const BigInteger &a, const BigInteger &b) {
175 DTRT_ALIASED(this == &a || this == &b, add(a, b));
176 // If one argument is zero, copy the other.
177 if (a.sign == zero)
178 operator =(b);
179 else if (b.sign == zero)
180 operator =(a);
181 // If the arguments have the same sign, take the
182 // common sign and add their magnitudes.
183 else if (a.sign == b.sign) {
184 sign = a.sign;
185 mag.add(a.mag, b.mag);
186 } else {
187 // Otherwise, their magnitudes must be compared.
188 switch (a.mag.compareTo(b.mag)) {
189 case equal:
190 // If their magnitudes are the same, copy zero.
191 mag = 0;
192 sign = zero;
193 break;
194 // Otherwise, take the sign of the greater, and subtract
195 // the lesser magnitude from the greater magnitude.
196 case greater:
197 sign = a.sign;
198 mag.subtract(a.mag, b.mag);
199 break;
200 case less:
201 sign = b.sign;
202 mag.subtract(b.mag, a.mag);
203 break;
204 }
205 }
206 }
207
subtract(const BigInteger & a,const BigInteger & b)208 void BigInteger::subtract(const BigInteger &a, const BigInteger &b) {
209 // Notice that this routine is identical to BigInteger::add,
210 // if one replaces b.sign by its opposite.
211 DTRT_ALIASED(this == &a || this == &b, subtract(a, b));
212 // If a is zero, copy b and flip its sign. If b is zero, copy a.
213 if (a.sign == zero) {
214 mag = b.mag;
215 // Take the negative of _b_'s, sign, not ours.
216 // Bug pointed out by Sam Larkin on 2005.03.30.
217 sign = Sign(-b.sign);
218 } else if (b.sign == zero)
219 operator =(a);
220 // If their signs differ, take a.sign and add the magnitudes.
221 else if (a.sign != b.sign) {
222 sign = a.sign;
223 mag.add(a.mag, b.mag);
224 } else {
225 // Otherwise, their magnitudes must be compared.
226 switch (a.mag.compareTo(b.mag)) {
227 // If their magnitudes are the same, copy zero.
228 case equal:
229 mag = 0;
230 sign = zero;
231 break;
232 // If a's magnitude is greater, take a.sign and
233 // subtract a from b.
234 case greater:
235 sign = a.sign;
236 mag.subtract(a.mag, b.mag);
237 break;
238 // If b's magnitude is greater, take the opposite
239 // of b.sign and subtract b from a.
240 case less:
241 sign = Sign(-b.sign);
242 mag.subtract(b.mag, a.mag);
243 break;
244 }
245 }
246 }
247
multiply(const BigInteger & a,const BigInteger & b)248 void BigInteger::multiply(const BigInteger &a, const BigInteger &b) {
249 DTRT_ALIASED(this == &a || this == &b, multiply(a, b));
250 // If one object is zero, copy zero and return.
251 if (a.sign == zero || b.sign == zero) {
252 sign = zero;
253 mag = 0;
254 return;
255 }
256 // If the signs of the arguments are the same, the result
257 // is positive, otherwise it is negative.
258 sign = (a.sign == b.sign) ? positive : negative;
259 // Multiply the magnitudes.
260 mag.multiply(a.mag, b.mag);
261 }
262
263 /*
264 * DIVISION WITH REMAINDER
265 * Please read the comments before the definition of
266 * `BigUnsigned::divideWithRemainder' in `BigUnsigned.cc' for lots of
267 * information you should know before reading this function.
268 *
269 * Following Knuth, I decree that x / y is to be
270 * 0 if y==0 and floor(real-number x / y) if y!=0.
271 * Then x % y shall be x - y*(integer x / y).
272 *
273 * Note that x = y * (x / y) + (x % y) always holds.
274 * In addition, (x % y) is from 0 to y - 1 if y > 0,
275 * and from -(|y| - 1) to 0 if y < 0. (x % y) = x if y = 0.
276 *
277 * Examples: (q = a / b, r = a % b)
278 * a b q r
279 * === === === ===
280 * 4 3 1 1
281 * -4 3 -2 2
282 * 4 -3 -2 -2
283 * -4 -3 1 -1
284 */
divideWithRemainder(const BigInteger & b,BigInteger & q)285 void BigInteger::divideWithRemainder(const BigInteger &b, BigInteger &q) {
286 // Defend against aliased calls;
287 // same idea as in BigUnsigned::divideWithRemainder .
288 if (this == &q)
289 abort();
290 if (this == &b || &q == &b) {
291 BigInteger tmpB(b);
292 divideWithRemainder(tmpB, q);
293 return;
294 }
295
296 // Division by zero gives quotient 0 and remainder *this
297 if (b.sign == zero) {
298 q.mag = 0;
299 q.sign = zero;
300 return;
301 }
302 // 0 / b gives quotient 0 and remainder 0
303 if (sign == zero) {
304 q.mag = 0;
305 q.sign = zero;
306 return;
307 }
308
309 // Here *this != 0, b != 0.
310
311 // Do the operands have the same sign?
312 if (sign == b.sign) {
313 // Yes: easy case. Quotient is zero or positive.
314 q.sign = positive;
315 } else {
316 // No: harder case. Quotient is negative.
317 q.sign = negative;
318 // Decrease the magnitude of the dividend by one.
319 mag--;
320 /*
321 * We tinker with the dividend before and with the
322 * quotient and remainder after so that the result
323 * comes out right. To see why it works, consider the following
324 * list of examples, where A is the magnitude-decreased
325 * a, Q and R are the results of BigUnsigned division
326 * with remainder on A and |b|, and q and r are the
327 * final results we want:
328 *
329 * a A b Q R q r
330 * -3 -2 3 0 2 -1 0
331 * -4 -3 3 1 0 -2 2
332 * -5 -4 3 1 1 -2 1
333 * -6 -5 3 1 2 -2 0
334 *
335 * It appears that we need a total of 3 corrections:
336 * Decrease the magnitude of a to get A. Increase the
337 * magnitude of Q to get q (and make it negative).
338 * Find r = (b - 1) - R and give it the desired sign.
339 */
340 }
341
342 // Divide the magnitudes.
343 mag.divideWithRemainder(b.mag, q.mag);
344
345 if (sign != b.sign) {
346 // More for the harder case (as described):
347 // Increase the magnitude of the quotient by one.
348 q.mag++;
349 // Modify the remainder.
350 mag.subtract(b.mag, mag);
351 mag--;
352 }
353
354 // Sign of the remainder is always the sign of the divisor b.
355 sign = b.sign;
356
357 // Set signs to zero as necessary. (Thanks David Allen!)
358 if (mag.isZero())
359 sign = zero;
360 if (q.mag.isZero())
361 q.sign = zero;
362
363 // WHEW!!!
364 }
365
366 // Negation
negate(const BigInteger & a)367 void BigInteger::negate(const BigInteger &a) {
368 DTRT_ALIASED(this == &a, negate(a));
369 // Copy a's magnitude
370 mag = a.mag;
371 // Copy the opposite of a.sign
372 sign = Sign(-a.sign);
373 }
374
375 // INCREMENT/DECREMENT OPERATORS
376
377 // Prefix increment
operator ++()378 BigInteger& BigInteger::operator ++() {
379 if (sign == negative) {
380 mag--;
381 if (mag == 0)
382 sign = zero;
383 } else {
384 mag++;
385 sign = positive; // if not already
386 }
387 return *this;
388 }
389
390 // Postfix increment
operator ++(int)391 BigInteger BigInteger::operator ++(int) {
392 BigInteger temp(*this);
393 operator ++();
394 return temp;
395 }
396
397 // Prefix decrement
operator --()398 BigInteger& BigInteger::operator --() {
399 if (sign == positive) {
400 mag--;
401 if (mag == 0)
402 sign = zero;
403 } else {
404 mag++;
405 sign = negative;
406 }
407 return *this;
408 }
409
410 // Postfix decrement
operator --(int)411 BigInteger BigInteger::operator --(int) {
412 BigInteger temp(*this);
413 operator --();
414 return temp;
415 }
416
417