blob: 863fadcb39846804c688e5688e25fc74dd6ebf25 [file] [log] [blame]
Bo Xu8ad00402014-12-02 13:06:22 -08001// 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 "BigUnsigned.hh"
8
9// Memory management definitions have moved to the bottom of NumberlikeArray.hh.
10
11// The templates used by these constructors and converters are at the bottom of
12// BigUnsigned.hh.
13
14BigUnsigned::BigUnsigned(unsigned long x) { initFromPrimitive (x); }
15BigUnsigned::BigUnsigned(unsigned int x) { initFromPrimitive (x); }
16BigUnsigned::BigUnsigned(unsigned short x) { initFromPrimitive (x); }
17BigUnsigned::BigUnsigned( long x) { initFromSignedPrimitive(x); }
18BigUnsigned::BigUnsigned( int x) { initFromSignedPrimitive(x); }
19BigUnsigned::BigUnsigned( short x) { initFromSignedPrimitive(x); }
20
21unsigned long BigUnsigned::toUnsignedLong () const { return convertToPrimitive <unsigned long >(); }
22unsigned int BigUnsigned::toUnsignedInt () const { return convertToPrimitive <unsigned int >(); }
23unsigned short BigUnsigned::toUnsignedShort() const { return convertToPrimitive <unsigned short>(); }
24long BigUnsigned::toLong () const { return convertToSignedPrimitive< long >(); }
25int BigUnsigned::toInt () const { return convertToSignedPrimitive< int >(); }
26short BigUnsigned::toShort () const { return convertToSignedPrimitive< short>(); }
27
28// BIT/BLOCK ACCESSORS
29
30void BigUnsigned::setBlock(Index i, Blk newBlock) {
31 if (newBlock == 0) {
32 if (i < len) {
33 blk[i] = 0;
34 zapLeadingZeros();
35 }
36 // If i >= len, no effect.
37 } else {
38 if (i >= len) {
39 // The nonzero block extends the number.
40 allocateAndCopy(i+1);
41 // Zero any added blocks that we aren't setting.
42 for (Index j = len; j < i; j++)
43 blk[j] = 0;
44 len = i+1;
45 }
46 blk[i] = newBlock;
47 }
48}
49
50/* Evidently the compiler wants BigUnsigned:: on the return type because, at
51 * that point, it hasn't yet parsed the BigUnsigned:: on the name to get the
52 * proper scope. */
53BigUnsigned::Index BigUnsigned::bitLength() const {
54 if (isZero())
55 return 0;
56 else {
57 Blk leftmostBlock = getBlock(len - 1);
58 Index leftmostBlockLen = 0;
59 while (leftmostBlock != 0) {
60 leftmostBlock >>= 1;
61 leftmostBlockLen++;
62 }
63 return leftmostBlockLen + (len - 1) * N;
64 }
65}
66
67void BigUnsigned::setBit(Index bi, bool newBit) {
68 Index blockI = bi / N;
69 Blk block = getBlock(blockI), mask = Blk(1) << (bi % N);
70 block = newBit ? (block | mask) : (block & ~mask);
71 setBlock(blockI, block);
72}
73
74// COMPARISON
75BigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {
76 // A bigger length implies a bigger number.
77 if (len < x.len)
78 return less;
79 else if (len > x.len)
80 return greater;
81 else {
82 // Compare blocks one by one from left to right.
83 Index i = len;
84 while (i > 0) {
85 i--;
86 if (blk[i] == x.blk[i])
87 continue;
88 else if (blk[i] > x.blk[i])
89 return greater;
90 else
91 return less;
92 }
93 // If no blocks differed, the numbers are equal.
94 return equal;
95 }
96}
97
98// COPY-LESS OPERATIONS
99
100/*
101 * On most calls to copy-less operations, it's safe to read the inputs little by
102 * little and write the outputs little by little. However, if one of the
103 * inputs is coming from the same variable into which the output is to be
104 * stored (an "aliased" call), we risk overwriting the input before we read it.
105 * In this case, we first compute the result into a temporary BigUnsigned
106 * variable and then copy it into the requested output variable *this.
107 * Each put-here operation uses the DTRT_ALIASED macro (Do The Right Thing on
108 * aliased calls) to generate code for this check.
109 *
110 * I adopted this approach on 2007.02.13 (see Assignment Operators in
111 * BigUnsigned.hh). Before then, put-here operations rejected aliased calls
112 * with an exception. I think doing the right thing is better.
113 *
114 * Some of the put-here operations can probably handle aliased calls safely
115 * without the extra copy because (for example) they process blocks strictly
116 * right-to-left. At some point I might determine which ones don't need the
117 * copy, but my reasoning would need to be verified very carefully. For now
118 * I'll leave in the copy.
119 */
120#define DTRT_ALIASED(cond, op) \
121 if (cond) { \
122 BigUnsigned tmpThis; \
123 tmpThis.op; \
124 *this = tmpThis; \
125 return; \
126 }
127
128
129
130void BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {
131 DTRT_ALIASED(this == &a || this == &b, add(a, b));
132 // If one argument is zero, copy the other.
133 if (a.len == 0) {
134 operator =(b);
135 return;
136 } else if (b.len == 0) {
137 operator =(a);
138 return;
139 }
140 // Some variables...
141 // Carries in and out of an addition stage
142 bool carryIn, carryOut;
143 Blk temp;
144 Index i;
145 // a2 points to the longer input, b2 points to the shorter
146 const BigUnsigned *a2, *b2;
147 if (a.len >= b.len) {
148 a2 = &a;
149 b2 = &b;
150 } else {
151 a2 = &b;
152 b2 = &a;
153 }
154 // Set prelimiary length and make room in this BigUnsigned
155 len = a2->len + 1;
156 allocate(len);
157 // For each block index that is present in both inputs...
158 for (i = 0, carryIn = false; i < b2->len; i++) {
159 // Add input blocks
160 temp = a2->blk[i] + b2->blk[i];
161 // If a rollover occurred, the result is less than either input.
162 // This test is used many times in the BigUnsigned code.
163 carryOut = (temp < a2->blk[i]);
164 // If a carry was input, handle it
165 if (carryIn) {
166 temp++;
167 carryOut |= (temp == 0);
168 }
169 blk[i] = temp; // Save the addition result
170 carryIn = carryOut; // Pass the carry along
171 }
172 // If there is a carry left over, increase blocks until
173 // one does not roll over.
174 for (; i < a2->len && carryIn; i++) {
175 temp = a2->blk[i] + 1;
176 carryIn = (temp == 0);
177 blk[i] = temp;
178 }
179 // If the carry was resolved but the larger number
180 // still has blocks, copy them over.
181 for (; i < a2->len; i++)
182 blk[i] = a2->blk[i];
183 // Set the extra block if there's still a carry, decrease length otherwise
184 if (carryIn)
185 blk[i] = 1;
186 else
187 len--;
188}
189
190void BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {
191 DTRT_ALIASED(this == &a || this == &b, subtract(a, b));
192 if (b.len == 0) {
193 // If b is zero, copy a.
194 operator =(a);
195 return;
196 } else if (a.len < b.len)
197 // If a is shorter than b, the result is negative.
198#ifdef FOXIT_CHROME_BUILD
199 abort();
200#else
201 throw "BigUnsigned::subtract: "
202 "Negative result in unsigned calculation";
203#endif
204 // Some variables...
205 bool borrowIn, borrowOut;
206 Blk temp;
207 Index i;
208 // Set preliminary length and make room
209 len = a.len;
210 allocate(len);
211 // For each block index that is present in both inputs...
212 for (i = 0, borrowIn = false; i < b.len; i++) {
213 temp = a.blk[i] - b.blk[i];
214 // If a reverse rollover occurred,
215 // the result is greater than the block from a.
216 borrowOut = (temp > a.blk[i]);
217 // Handle an incoming borrow
218 if (borrowIn) {
219 borrowOut |= (temp == 0);
220 temp--;
221 }
222 blk[i] = temp; // Save the subtraction result
223 borrowIn = borrowOut; // Pass the borrow along
224 }
225 // If there is a borrow left over, decrease blocks until
226 // one does not reverse rollover.
227 for (; i < a.len && borrowIn; i++) {
228 borrowIn = (a.blk[i] == 0);
229 blk[i] = a.blk[i] - 1;
230 }
231 /* If there's still a borrow, the result is negative.
232 * Throw an exception, but zero out this object so as to leave it in a
233 * predictable state. */
234 if (borrowIn) {
235 len = 0;
236#ifdef FOXIT_CHROME_BUILD
237 abort();
238#else
239 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
240#endif
241 } else
242 // Copy over the rest of the blocks
243 for (; i < a.len; i++)
244 blk[i] = a.blk[i];
245 // Zap leading zeros
246 zapLeadingZeros();
247}
248
249/*
250 * About the multiplication and division algorithms:
251 *
252 * I searched unsucessfully for fast C++ built-in operations like the `b_0'
253 * and `c_0' Knuth describes in Section 4.3.1 of ``The Art of Computer
254 * Programming'' (replace `place' by `Blk'):
255 *
256 * ``b_0[:] multiplication of a one-place integer by another one-place
257 * integer, giving a two-place answer;
258 *
259 * ``c_0[:] division of a two-place integer by a one-place integer,
260 * provided that the quotient is a one-place integer, and yielding
261 * also a one-place remainder.''
262 *
263 * I also missed his note that ``[b]y adjusting the word size, if
264 * necessary, nearly all computers will have these three operations
265 * available'', so I gave up on trying to use algorithms similar to his.
266 * A future version of the library might include such algorithms; I
267 * would welcome contributions from others for this.
268 *
269 * I eventually decided to use bit-shifting algorithms. To multiply `a'
270 * and `b', we zero out the result. Then, for each `1' bit in `a', we
271 * shift `b' left the appropriate amount and add it to the result.
272 * Similarly, to divide `a' by `b', we shift `b' left varying amounts,
273 * repeatedly trying to subtract it from `a'. When we succeed, we note
274 * the fact by setting a bit in the quotient. While these algorithms
275 * have the same O(n^2) time complexity as Knuth's, the ``constant factor''
276 * is likely to be larger.
277 *
278 * Because I used these algorithms, which require single-block addition
279 * and subtraction rather than single-block multiplication and division,
280 * the innermost loops of all four routines are very similar. Study one
281 * of them and all will become clear.
282 */
283
284/*
285 * This is a little inline function used by both the multiplication
286 * routine and the division routine.
287 *
288 * `getShiftedBlock' returns the `x'th block of `num << y'.
289 * `y' may be anything from 0 to N - 1, and `x' may be anything from
290 * 0 to `num.len'.
291 *
292 * Two things contribute to this block:
293 *
294 * (1) The `N - y' low bits of `num.blk[x]', shifted `y' bits left.
295 *
296 * (2) The `y' high bits of `num.blk[x-1]', shifted `N - y' bits right.
297 *
298 * But we must be careful if `x == 0' or `x == num.len', in
299 * which case we should use 0 instead of (2) or (1), respectively.
300 *
301 * If `y == 0', then (2) contributes 0, as it should. However,
302 * in some computer environments, for a reason I cannot understand,
303 * `a >> b' means `a >> (b % N)'. This means `num.blk[x-1] >> (N - y)'
304 * will return `num.blk[x-1]' instead of the desired 0 when `y == 0';
305 * the test `y == 0' handles this case specially.
306 */
307inline BigUnsigned::Blk getShiftedBlock(const BigUnsigned &num,
308 BigUnsigned::Index x, unsigned int y) {
309 BigUnsigned::Blk part1 = (x == 0 || y == 0) ? 0 : (num.blk[x - 1] >> (BigUnsigned::N - y));
310 BigUnsigned::Blk part2 = (x == num.len) ? 0 : (num.blk[x] << y);
311 return part1 | part2;
312}
313
314void BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {
315 DTRT_ALIASED(this == &a || this == &b, multiply(a, b));
316 // If either a or b is zero, set to zero.
317 if (a.len == 0 || b.len == 0) {
318 len = 0;
319 return;
320 }
321 /*
322 * Overall method:
323 *
324 * Set this = 0.
325 * For each 1-bit of `a' (say the `i2'th bit of block `i'):
326 * Add `b << (i blocks and i2 bits)' to *this.
327 */
328 // Variables for the calculation
329 Index i, j, k;
330 unsigned int i2;
331 Blk temp;
332 bool carryIn, carryOut;
333 // Set preliminary length and make room
334 len = a.len + b.len;
335 allocate(len);
336 // Zero out this object
337 for (i = 0; i < len; i++)
338 blk[i] = 0;
339 // For each block of the first number...
340 for (i = 0; i < a.len; i++) {
341 // For each 1-bit of that block...
342 for (i2 = 0; i2 < N; i2++) {
343 if ((a.blk[i] & (Blk(1) << i2)) == 0)
344 continue;
345 /*
346 * Add b to this, shifted left i blocks and i2 bits.
347 * j is the index in b, and k = i + j is the index in this.
348 *
349 * `getShiftedBlock', a short inline function defined above,
350 * is now used for the bit handling. It replaces the more
351 * complex `bHigh' code, in which each run of the loop dealt
352 * immediately with the low bits and saved the high bits to
353 * be picked up next time. The last run of the loop used to
354 * leave leftover high bits, which were handled separately.
355 * Instead, this loop runs an additional time with j == b.len.
356 * These changes were made on 2005.01.11.
357 */
358 for (j = 0, k = i, carryIn = false; j <= b.len; j++, k++) {
359 /*
360 * The body of this loop is very similar to the body of the first loop
361 * in `add', except that this loop does a `+=' instead of a `+'.
362 */
363 temp = blk[k] + getShiftedBlock(b, j, i2);
364 carryOut = (temp < blk[k]);
365 if (carryIn) {
366 temp++;
367 carryOut |= (temp == 0);
368 }
369 blk[k] = temp;
370 carryIn = carryOut;
371 }
372 // No more extra iteration to deal with `bHigh'.
373 // Roll-over a carry as necessary.
374 for (; carryIn; k++) {
375 blk[k]++;
376 carryIn = (blk[k] == 0);
377 }
378 }
379 }
380 // Zap possible leading zero
381 if (blk[len - 1] == 0)
382 len--;
383}
384
385/*
386 * DIVISION WITH REMAINDER
387 * This monstrous function mods *this by the given divisor b while storing the
388 * quotient in the given object q; at the end, *this contains the remainder.
389 * The seemingly bizarre pattern of inputs and outputs was chosen so that the
390 * function copies as little as possible (since it is implemented by repeated
391 * subtraction of multiples of b from *this).
392 *
393 * "modWithQuotient" might be a better name for this function, but I would
394 * rather not change the name now.
395 */
396void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) {
397 /* Defending against aliased calls is more complex than usual because we
398 * are writing to both *this and q.
399 *
400 * It would be silly to try to write quotient and remainder to the
401 * same variable. Rule that out right away. */
402 if (this == &q)
403#ifdef FOXIT_CHROME_BUILD
404 abort();
405#else
406 throw "BigUnsigned::divideWithRemainder: Cannot write quotient and remainder into the same variable";
407#endif
408 /* Now *this and q are separate, so the only concern is that b might be
409 * aliased to one of them. If so, use a temporary copy of b. */
410 if (this == &b || &q == &b) {
411 BigUnsigned tmpB(b);
412 divideWithRemainder(tmpB, q);
413 return;
414 }
415
416 /*
417 * Knuth's definition of mod (which this function uses) is somewhat
418 * different from the C++ definition of % in case of division by 0.
419 *
420 * We let a / 0 == 0 (it doesn't matter much) and a % 0 == a, no
421 * exceptions thrown. This allows us to preserve both Knuth's demand
422 * that a mod 0 == a and the useful property that
423 * (a / b) * b + (a % b) == a.
424 */
425 if (b.len == 0) {
426 q.len = 0;
427 return;
428 }
429
430 /*
431 * If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into
432 * *this at all. The quotient is 0 and *this is already the remainder (so leave it alone).
433 */
434 if (len < b.len) {
435 q.len = 0;
436 return;
437 }
438
439 // At this point we know (*this).len >= b.len > 0. (Whew!)
440
441 /*
442 * Overall method:
443 *
444 * For each appropriate i and i2, decreasing:
445 * Subtract (b << (i blocks and i2 bits)) from *this, storing the
446 * result in subtractBuf.
447 * If the subtraction succeeds with a nonnegative result:
448 * Turn on bit i2 of block i of the quotient q.
449 * Copy subtractBuf back into *this.
450 * Otherwise bit i2 of block i remains off, and *this is unchanged.
451 *
452 * Eventually q will contain the entire quotient, and *this will
453 * be left with the remainder.
454 *
455 * subtractBuf[x] corresponds to blk[x], not blk[x+i], since 2005.01.11.
456 * But on a single iteration, we don't touch the i lowest blocks of blk
457 * (and don't use those of subtractBuf) because these blocks are
458 * unaffected by the subtraction: we are subtracting
459 * (b << (i blocks and i2 bits)), which ends in at least `i' zero
460 * blocks. */
461 // Variables for the calculation
462 Index i, j, k;
463 unsigned int i2;
464 Blk temp;
465 bool borrowIn, borrowOut;
466
467 /*
468 * Make sure we have an extra zero block just past the value.
469 *
470 * When we attempt a subtraction, we might shift `b' so
471 * its first block begins a few bits left of the dividend,
472 * and then we'll try to compare these extra bits with
473 * a nonexistent block to the left of the dividend. The
474 * extra zero block ensures sensible behavior; we need
475 * an extra block in `subtractBuf' for exactly the same reason.
476 */
477 Index origLen = len; // Save real length.
478 /* To avoid an out-of-bounds access in case of reallocation, allocate
479 * first and then increment the logical length. */
480 allocateAndCopy(len + 1);
481 len++;
482 blk[origLen] = 0; // Zero the added block.
483
484 // subtractBuf holds part of the result of a subtraction; see above.
485 Blk *subtractBuf = new Blk[len];
486
487 // Set preliminary length for quotient and make room
488 q.len = origLen - b.len + 1;
489 q.allocate(q.len);
490 // Zero out the quotient
491 for (i = 0; i < q.len; i++)
492 q.blk[i] = 0;
493
494 // For each possible left-shift of b in blocks...
495 i = q.len;
496 while (i > 0) {
497 i--;
498 // For each possible left-shift of b in bits...
499 // (Remember, N is the number of bits in a Blk.)
500 q.blk[i] = 0;
501 i2 = N;
502 while (i2 > 0) {
503 i2--;
504 /*
505 * Subtract b, shifted left i blocks and i2 bits, from *this,
506 * and store the answer in subtractBuf. In the for loop, `k == i + j'.
507 *
508 * Compare this to the middle section of `multiply'. They
509 * are in many ways analogous. See especially the discussion
510 * of `getShiftedBlock'.
511 */
512 for (j = 0, k = i, borrowIn = false; j <= b.len; j++, k++) {
513 temp = blk[k] - getShiftedBlock(b, j, i2);
514 borrowOut = (temp > blk[k]);
515 if (borrowIn) {
516 borrowOut |= (temp == 0);
517 temp--;
518 }
519 // Since 2005.01.11, indices of `subtractBuf' directly match those of `blk', so use `k'.
520 subtractBuf[k] = temp;
521 borrowIn = borrowOut;
522 }
523 // No more extra iteration to deal with `bHigh'.
524 // Roll-over a borrow as necessary.
525 for (; k < origLen && borrowIn; k++) {
526 borrowIn = (blk[k] == 0);
527 subtractBuf[k] = blk[k] - 1;
528 }
529 /*
530 * If the subtraction was performed successfully (!borrowIn),
531 * set bit i2 in block i of the quotient.
532 *
533 * Then, copy the portion of subtractBuf filled by the subtraction
534 * back to *this. This portion starts with block i and ends--
535 * where? Not necessarily at block `i + b.len'! Well, we
536 * increased k every time we saved a block into subtractBuf, so
537 * the region of subtractBuf we copy is just [i, k).
538 */
539 if (!borrowIn) {
540 q.blk[i] |= (Blk(1) << i2);
541 while (k > i) {
542 k--;
543 blk[k] = subtractBuf[k];
544 }
545 }
546 }
547 }
548 // Zap possible leading zero in quotient
549 if (q.blk[q.len - 1] == 0)
550 q.len--;
551 // Zap any/all leading zeros in remainder
552 zapLeadingZeros();
553 // Deallocate subtractBuf.
554 // (Thanks to Brad Spencer for noticing my accidental omission of this!)
555 delete [] subtractBuf;
556}
557
558/* BITWISE OPERATORS
559 * These are straightforward blockwise operations except that they differ in
560 * the output length and the necessity of zapLeadingZeros. */
561
562void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) {
563 DTRT_ALIASED(this == &a || this == &b, bitAnd(a, b));
564 // The bitwise & can't be longer than either operand.
565 len = (a.len >= b.len) ? b.len : a.len;
566 allocate(len);
567 Index i;
568 for (i = 0; i < len; i++)
569 blk[i] = a.blk[i] & b.blk[i];
570 zapLeadingZeros();
571}
572
573void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) {
574 DTRT_ALIASED(this == &a || this == &b, bitOr(a, b));
575 Index i;
576 const BigUnsigned *a2, *b2;
577 if (a.len >= b.len) {
578 a2 = &a;
579 b2 = &b;
580 } else {
581 a2 = &b;
582 b2 = &a;
583 }
584 allocate(a2->len);
585 for (i = 0; i < b2->len; i++)
586 blk[i] = a2->blk[i] | b2->blk[i];
587 for (; i < a2->len; i++)
588 blk[i] = a2->blk[i];
589 len = a2->len;
590 // Doesn't need zapLeadingZeros.
591}
592
593void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) {
594 DTRT_ALIASED(this == &a || this == &b, bitXor(a, b));
595 Index i;
596 const BigUnsigned *a2, *b2;
597 if (a.len >= b.len) {
598 a2 = &a;
599 b2 = &b;
600 } else {
601 a2 = &b;
602 b2 = &a;
603 }
604 allocate(a2->len);
605 for (i = 0; i < b2->len; i++)
606 blk[i] = a2->blk[i] ^ b2->blk[i];
607 for (; i < a2->len; i++)
608 blk[i] = a2->blk[i];
609 len = a2->len;
610 zapLeadingZeros();
611}
612
613void BigUnsigned::bitShiftLeft(const BigUnsigned &a, int b) {
614 DTRT_ALIASED(this == &a, bitShiftLeft(a, b));
615 if (b < 0) {
616 if (b << 1 == 0)
617#ifdef FOXIT_CHROME_BUILD
618 abort();
619#else
620 throw "BigUnsigned::bitShiftLeft: "
621 "Pathological shift amount not implemented";
622#endif
623 else {
624 bitShiftRight(a, -b);
625 return;
626 }
627 }
628 Index shiftBlocks = b / N;
629 unsigned int shiftBits = b % N;
630 // + 1: room for high bits nudged left into another block
631 len = a.len + shiftBlocks + 1;
632 allocate(len);
633 Index i, j;
634 for (i = 0; i < shiftBlocks; i++)
635 blk[i] = 0;
636 for (j = 0, i = shiftBlocks; j <= a.len; j++, i++)
637 blk[i] = getShiftedBlock(a, j, shiftBits);
638 // Zap possible leading zero
639 if (blk[len - 1] == 0)
640 len--;
641}
642
643void BigUnsigned::bitShiftRight(const BigUnsigned &a, int b) {
644 DTRT_ALIASED(this == &a, bitShiftRight(a, b));
645 if (b < 0) {
646 if (b << 1 == 0)
647#ifdef FOXIT_CHROME_BUILD
648 abort();
649#else
650 throw "BigUnsigned::bitShiftRight: "
651 "Pathological shift amount not implemented";
652#endif
653 else {
654 bitShiftLeft(a, -b);
655 return;
656 }
657 }
658 // This calculation is wacky, but expressing the shift as a left bit shift
659 // within each block lets us use getShiftedBlock.
660 Index rightShiftBlocks = (b + N - 1) / N;
661 unsigned int leftShiftBits = N * rightShiftBlocks - b;
662 // Now (N * rightShiftBlocks - leftShiftBits) == b
663 // and 0 <= leftShiftBits < N.
664 if (rightShiftBlocks >= a.len + 1) {
665 // All of a is guaranteed to be shifted off, even considering the left
666 // bit shift.
667 len = 0;
668 return;
669 }
670 // Now we're allocating a positive amount.
671 // + 1: room for high bits nudged left into another block
672 len = a.len + 1 - rightShiftBlocks;
673 allocate(len);
674 Index i, j;
675 for (j = rightShiftBlocks, i = 0; j <= a.len; j++, i++)
676 blk[i] = getShiftedBlock(a, j, leftShiftBits);
677 // Zap possible leading zero
678 if (blk[len - 1] == 0)
679 len--;
680}
681
682// INCREMENT/DECREMENT OPERATORS
683
684// Prefix increment
685void BigUnsigned::operator ++() {
686 Index i;
687 bool carry = true;
688 for (i = 0; i < len && carry; i++) {
689 blk[i]++;
690 carry = (blk[i] == 0);
691 }
692 if (carry) {
693 // Allocate and then increase length, as in divideWithRemainder
694 allocateAndCopy(len + 1);
695 len++;
696 blk[i] = 1;
697 }
698}
699
700// Postfix increment: same as prefix
701void BigUnsigned::operator ++(int) {
702 operator ++();
703}
704
705// Prefix decrement
706void BigUnsigned::operator --() {
707 if (len == 0)
708#ifdef FOXIT_CHROME_BUILD
709 abort();
710#else
711 throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero";
712#endif
713 Index i;
714 bool borrow = true;
715 for (i = 0; borrow; i++) {
716 borrow = (blk[i] == 0);
717 blk[i]--;
718 }
719 // Zap possible leading zero (there can only be one)
720 if (blk[len - 1] == 0)
721 len--;
722}
723
724// Postfix decrement: same as prefix
725void BigUnsigned::operator --(int) {
726 operator --();
727}