Old snapshot `bigint-2006.05.01'; see the ChangeLog file.
[bigint/bigint.git] / BigUnsigned.cc
CommitLineData
05780f4b
MM
1/*
2* Matt McCutchen's Big Integer Library
05780f4b
MM
3*/
4
5#include "BigUnsigned.hh"
6
b3fe29df 7// The "management" routines that used to be here are now in NumberlikeArray.hh.
05780f4b
MM
8
9/*
10* The steps for construction of a BigUnsigned
11* from an integral value x are as follows:
12* 1. If x is zero, create an empty BigUnsigned and stop.
13* 2. If x is negative, throw an exception.
14* 3. Allocate a one-block number array.
15* 4. If x is of a signed type, convert x to the unsigned
16* type of the same length.
17* 5. Expand x to a Blk, and store it in the number array.
b3fe29df
MM
18*
19* Since 2005.01.06, NumberlikeArray uses `NULL' rather
20* than a real array if one of zero length is needed.
21* These constructors implicitly call NumberlikeArray's
a8b42b68 22* default constructor, which sets `blk = NULL, cap = len = 0'.
b3fe29df
MM
23* So if the input number is zero, they can just return.
24* See remarks in `NumberlikeArray.hh'.
05780f4b
MM
25*/
26
27BigUnsigned::BigUnsigned(unsigned long x) {
b3fe29df
MM
28 if (x == 0)
29 ; // NumberlikeArray already did all the work
30 else {
05780f4b 31 cap = 1;
a8b42b68 32 blk = new Blk[1];
05780f4b
MM
33 len = 1;
34 blk[0] = Blk(x);
35 }
36}
37
38BigUnsigned::BigUnsigned(long x) {
b3fe29df
MM
39 if (x == 0)
40 ;
41 else if (x > 0) {
05780f4b 42 cap = 1;
a8b42b68 43 blk = new Blk[1];
05780f4b
MM
44 len = 1;
45 blk[0] = Blk(x);
46 } else
b3fe29df 47 throw "BigUnsigned::BigUnsigned(long): Cannot construct a BigUnsigned from a negative number";
05780f4b
MM
48}
49
50BigUnsigned::BigUnsigned(unsigned int x) {
b3fe29df
MM
51 if (x == 0)
52 ;
53 else {
05780f4b 54 cap = 1;
a8b42b68 55 blk = new Blk[1];
05780f4b
MM
56 len = 1;
57 blk[0] = Blk(x);
58 }
59}
60
61BigUnsigned::BigUnsigned(int x) {
b3fe29df
MM
62 if (x == 0)
63 ;
64 else if (x > 0) {
05780f4b 65 cap = 1;
a8b42b68 66 blk = new Blk[1];
05780f4b
MM
67 len = 1;
68 blk[0] = Blk(x);
69 } else
b3fe29df 70 throw "BigUnsigned::BigUnsigned(int): Cannot construct a BigUnsigned from a negative number";
05780f4b
MM
71}
72
73BigUnsigned::BigUnsigned(unsigned short x) {
b3fe29df
MM
74 if (x == 0)
75 ;
76 else {
05780f4b 77 cap = 1;
a8b42b68 78 blk = new Blk[1];
05780f4b
MM
79 len = 1;
80 blk[0] = Blk(x);
81 }
82}
83
84BigUnsigned::BigUnsigned(short x) {
b3fe29df
MM
85 if (x == 0)
86 ;
87 else if (x > 0) {
05780f4b 88 cap = 1;
a8b42b68 89 blk = new Blk[1];
05780f4b
MM
90 len = 1;
91 blk[0] = Blk(x);
92 } else
b3fe29df 93 throw "BigUnsigned::BigUnsigned(short): Cannot construct a BigUnsigned from a negative number";
05780f4b
MM
94}
95
96// CONVERTERS
97/*
98* The steps for conversion of a BigUnsigned to an
99* integral type are as follows:
100* 1. If the BigUnsigned is zero, return zero.
101* 2. If it is more than one block long or its lowest
102* block has bits set out of the range of the target
103* type, throw an exception.
104* 3. Otherwise, convert the lowest block to the
105* target type and return it.
106*/
107
108namespace {
109 // These masks are used to test whether a Blk has bits
110 // set out of the range of a smaller integral type. Note
111 // that this range is not considered to include the sign bit.
112 const BigUnsigned::Blk lMask = ~0 >> 1;
113 const BigUnsigned::Blk uiMask = (unsigned int)(~0);
114 const BigUnsigned::Blk iMask = uiMask >> 1;
115 const BigUnsigned::Blk usMask = (unsigned short)(~0);
116 const BigUnsigned::Blk sMask = usMask >> 1;
117}
118
119BigUnsigned::operator unsigned long() const {
120 if (len == 0)
121 return 0;
122 else if (len == 1)
123 return (unsigned long) blk[0];
124 else
125 throw "BigUnsigned::operator unsigned long: Value is too big for an unsigned long";
126}
127
128BigUnsigned::operator long() const {
129 if (len == 0)
130 return 0;
131 else if (len == 1 && (blk[0] & lMask) == blk[0])
132 return (long) blk[0];
133 else
134 throw "BigUnsigned::operator long: Value is too big for a long";
135}
136
137BigUnsigned::operator unsigned int() const {
138 if (len == 0)
139 return 0;
140 else if (len == 1 && (blk[0] & uiMask) == blk[0])
141 return (unsigned int) blk[0];
142 else
143 throw "BigUnsigned::operator unsigned int: Value is too big for an unsigned int";
144}
145
146BigUnsigned::operator int() const {
147 if (len == 0)
148 return 0;
149 else if (len == 1 && (blk[0] & iMask) == blk[0])
150 return (int) blk[0];
151 else
152 throw "BigUnsigned::operator int: Value is too big for an int";
153}
154
155BigUnsigned::operator unsigned short() const {
156 if (len == 0)
157 return 0;
158 else if (len == 1 && (blk[0] & usMask) == blk[0])
159 return (unsigned short) blk[0];
160 else
161 throw "BigUnsigned::operator unsigned short: Value is too big for an unsigned short";
162}
163
164BigUnsigned::operator short() const {
165 if (len == 0)
166 return 0;
167 else if (len == 1 && (blk[0] & sMask) == blk[0])
168 return (short) blk[0];
169 else
170 throw "BigUnsigned::operator short: Value is too big for a short";
171}
172
173// COMPARISON
174BigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {
175 // A bigger length implies a bigger number.
176 if (len < x.len)
177 return less;
178 else if (len > x.len)
179 return greater;
180 else {
181 // Compare blocks one by one from left to right.
182 Index i = len;
183 while (i > 0) {
184 i--;
185 if (blk[i] == x.blk[i])
186 continue;
187 else if (blk[i] > x.blk[i])
188 return greater;
189 else
190 return less;
191 }
192 // If no blocks differed, the numbers are equal.
193 return equal;
194 }
195}
196
197// PUT-HERE OPERATIONS
198
4efbb076
MM
199/*
200* Below are implementations of the four basic arithmetic operations
201* for `BigUnsigned's. Their purpose is to use a mechanism that can
202* calculate the sum, difference, product, and quotient/remainder of
203* two individual blocks in order to calculate the sum, difference,
204* product, and quotient/remainder of two multi-block BigUnsigned
205* numbers.
206*
207* As alluded to in the comment before class `BigUnsigned',
208* these algorithms bear a remarkable similarity (in purpose, if
209* not in implementation) to the way humans operate on big numbers.
210* The built-in `+', `-', `*', `/' and `%' operators are analogous
211* to elementary-school ``math facts'' and ``times tables''; the
212* four routines below are analogous to ``long division'' and its
213* relatives. (Only a computer can ``memorize'' a times table with
214* 18446744073709551616 entries! (For 32-bit blocks.))
215*
216* The discovery of these four algorithms, called the ``classical
217* algorithms'', marked the beginning of the study of computer science.
218* See Section 4.3.1 of Knuth's ``The Art of Computer Programming''.
219*/
220
05780f4b
MM
221// Addition
222void BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {
223 // Block unsafe calls
224 if (this == &a || this == &b)
225 throw "BigUnsigned::add: One of the arguments is the invoked object";
226 // If one argument is zero, copy the other.
227 if (a.len == 0) {
228 operator =(b);
229 return;
230 } else if (b.len == 0) {
231 operator =(a);
232 return;
233 }
4efbb076 234 // Some variables...
05780f4b
MM
235 // Carries in and out of an addition stage
236 bool carryIn, carryOut;
237 Blk temp;
238 Index i;
239 // a2 points to the longer input, b2 points to the shorter
240 const BigUnsigned *a2, *b2;
241 if (a.len >= b.len) {
242 a2 = &a;
243 b2 = &b;
244 } else {
245 a2 = &b;
246 b2 = &a;
247 }
248 // Set prelimiary length and make room in this BigUnsigned
249 len = a2->len + 1;
250 allocate(len);
251 // For each block index that is present in both inputs...
252 for (i = 0, carryIn = false; i < b2->len; i++) {
253 // Add input blocks
254 temp = a2->blk[i] + b2->blk[i];
255 // If a rollover occurred, the result is less than either input.
256 // This test is used many times in the BigUnsigned code.
257 carryOut = (temp < a2->blk[i]);
258 // If a carry was input, handle it
259 if (carryIn) {
260 temp++;
261 carryOut |= (temp == 0);
262 }
263 blk[i] = temp; // Save the addition result
264 carryIn = carryOut; // Pass the carry along
265 }
266 // If there is a carry left over, increase blocks until
267 // one does not roll over.
268 for (; i < a2->len && carryIn; i++) {
269 temp = a2->blk[i] + 1;
270 carryIn = (temp == 0);
271 blk[i] = temp;
272 }
273 // If the carry was resolved but the larger number
274 // still has blocks, copy them over.
275 for (; i < a2->len; i++)
276 blk[i] = a2->blk[i];
277 // Set the extra block if there's still a carry, decrease length otherwise
278 if (carryIn)
279 blk[i] = 1;
280 else
281 len--;
282}
283
284// Subtraction
285void BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {
286 // Block unsafe calls
287 if (this == &a || this == &b)
288 throw "BigUnsigned::subtract: One of the arguments is the invoked object";
289 // If b is zero, copy a. If a is shorter than b, the result is negative.
290 if (b.len == 0) {
291 operator =(a);
292 return;
293 } else if (a.len < b.len)
294 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
4efbb076 295 // Some variables...
05780f4b
MM
296 bool borrowIn, borrowOut;
297 Blk temp;
298 Index i;
299 // Set preliminary length and make room
300 len = a.len;
301 allocate(len);
302 // For each block index that is present in both inputs...
303 for (i = 0, borrowIn = false; i < b.len; i++) {
304 temp = a.blk[i] - b.blk[i];
305 // If a reverse rollover occurred, the result is greater than the block from a.
306 borrowOut = (temp > a.blk[i]);
307 // Handle an incoming borrow
308 if (borrowIn) {
309 borrowOut |= (temp == 0);
310 temp--;
311 }
312 blk[i] = temp; // Save the subtraction result
313 borrowIn = borrowOut; // Pass the borrow along
314 }
315 // If there is a borrow left over, decrease blocks until
316 // one does not reverse rollover.
317 for (; i < a.len && borrowIn; i++) {
318 borrowIn = (a.blk[i] == 0);
319 blk[i] = a.blk[i] - 1;
320 }
321 // If there's still a borrow, the result is negative.
322 // Throw an exception, but zero out this object first just in case.
323 if (borrowIn) {
324 len = 0;
325 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
326 } else // Copy over the rest of the blocks
327 for (; i < a.len; i++)
328 blk[i] = a.blk[i];
329 // Zap leading zeros
330 zapLeadingZeros();
331}
332
4efbb076
MM
333/*
334* About the multiplication and division algorithms:
335*
336* I searched unsucessfully for fast built-in operations like the `b_0'
337* and `c_0' Knuth describes in Section 4.3.1 of ``The Art of Computer
338* Programming'' (replace `place' by `Blk'):
339*
340* ``b_0[:] multiplication of a one-place integer by another one-place
341* integer, giving a two-place answer;
342*
343* ``c_0[:] division of a two-place integer by a one-place integer,
344* provided that the quotient is a one-place integer, and yielding
345* also a one-place remainder.''
346*
347* I also missed his note that ``[b]y adjusting the word size, if
348* necessary, nearly all computers will have these three operations
349* available'', so I gave up on trying to use algorithms similar to his.
350* A future version of the library might include such algorithms; I
351* would welcome contributions from others for this.
352*
353* I eventually decided to use bit-shifting algorithms. To multiply `a'
354* and `b', we zero out the result. Then, for each `1' bit in `a', we
355* shift `b' left the appropriate amount and add it to the result.
356* Similarly, to divide `a' by `b', we shift `b' left varying amounts,
357* repeatedly trying to subtract it from `a'. When we succeed, we note
358* the fact by setting a bit in the quotient. While these algorithms
359* have the same O(n^2) time complexity as Knuth's, the ``constant factor''
360* is likely to be larger.
361*
362* Because I used these algorithms, which require single-block addition
363* and subtraction rather than single-block multiplication and division,
364* the innermost loops of all four routines are very similar. Study one
365* of them and all will become clear.
366*/
367
368/*
369* This is a little inline function used by both the multiplication
370* routine and the division routine.
371*
372* `getShiftedBlock' returns the `x'th block of `num << y'.
373* `y' may be anything from 0 to N - 1, and `x' may be anything from
374* 0 to `num.len'.
375*
376* Two things contribute to this block:
377*
378* (1) The `N - y' low bits of `num.blk[x]', shifted `y' bits left.
379*
380* (2) The `y' high bits of `num.blk[x-1]', shifted `N - y' bits right.
381*
382* But we must be careful if `x == 0' or `x == num.len', in
383* which case we should use 0 instead of (2) or (1), respectively.
384*
385* If `y == 0', then (2) contributes 0, as it should. However,
386* in some computer environments, for a reason I cannot understand,
387* `a >> b' means `a >> (b % N)'. This means `num.blk[x-1] >> (N - y)'
388* will return `num.blk[x-1]' instead of the desired 0 when `y == 0';
389* the test `y == 0' handles this case specially.
390*/
391inline BigUnsigned::Blk getShiftedBlock(const BigUnsigned &num,
392 BigUnsigned::Index x, unsigned int y) {
393 BigUnsigned::Blk part1 = (x == 0 || y == 0) ? 0 : (num.blk[x - 1] >> (BigUnsigned::N - y));
394 BigUnsigned::Blk part2 = (x == num.len) ? 0 : (num.blk[x] << y);
395 return part1 | part2;
396}
397
05780f4b
MM
398// Multiplication
399void BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {
400 // Block unsafe calls
401 if (this == &a || this == &b)
402 throw "BigUnsigned::multiply: One of the arguments is the invoked object";
403 // If either a or b is zero, set to zero.
404 if (a.len == 0 || b.len == 0) {
405 len = 0;
406 return;
407 }
4efbb076
MM
408 /*
409 * Overall method:
410 *
411 * Set this = 0.
412 * For each 1-bit of `a' (say the `i2'th bit of block `i'):
413 * Add `b << (i blocks and i2 bits)' to *this.
414 */
05780f4b
MM
415 // Variables for the calculation
416 Index i, j, k;
417 unsigned int i2;
4efbb076 418 Blk temp;
05780f4b
MM
419 bool carryIn, carryOut;
420 // Set preliminary length and make room
421 len = a.len + b.len;
422 allocate(len);
423 // Zero out this object
424 for (i = 0; i < len; i++)
425 blk[i] = 0;
426 // For each block of the first number...
427 for (i = 0; i < a.len; i++) {
428 // For each 1-bit of that block...
4efbb076 429 for (i2 = 0; i2 < N; i2++) {
26a5f52b 430 if ((a.blk[i] & (Blk(1) << i2)) == 0)
05780f4b 431 continue;
4efbb076
MM
432 /*
433 * Add b to this, shifted left i blocks and i2 bits.
05780f4b 434 * j is the index in b, and k = i + j is the index in this.
4efbb076
MM
435 *
436 * `getShiftedBlock', a short inline function defined above,
437 * is now used for the bit handling. It replaces the more
438 * complex `bHigh' code, in which each run of the loop dealt
439 * immediately with the low bits and saved the high bits to
440 * be picked up next time. The last run of the loop used to
441 * leave leftover high bits, which were handled separately.
442 * Instead, this loop runs an additional time with j == b.len.
443 * These changes were made on 2005.01.11.
444 */
445 for (j = 0, k = i, carryIn = false; j <= b.len; j++, k++) {
446 /*
447 * The body of this loop is very similar to the body of the first loop
448 * in `add', except that this loop does a `+=' instead of a `+'.
449 */
450 temp = blk[k] + getShiftedBlock(b, j, i2);
05780f4b
MM
451 carryOut = (temp < blk[k]);
452 if (carryIn) {
453 temp++;
454 carryOut |= (temp == 0);
455 }
456 blk[k] = temp;
457 carryIn = carryOut;
05780f4b 458 }
4efbb076
MM
459 // No more extra iteration to deal with `bHigh'.
460 // Roll-over a carry as necessary.
05780f4b
MM
461 for (; carryIn; k++) {
462 blk[k]++;
463 carryIn = (blk[k] == 0);
464 }
465 }
466 }
467 // Zap possible leading zero
468 if (blk[len - 1] == 0)
469 len--;
470}
471
472/*
473* DIVISION WITH REMAINDER
474* The functionality of divide, modulo, and %= is included in this one monstrous call,
475* which deserves some explanation.
476*
477* The division *this / b is performed.
478* Afterwards, q has the quotient, and *this has the remainder.
479* Thus, a call is like q = *this / b, *this %= b.
480*
481* This seemingly bizarre pattern of inputs and outputs has a justification. The
482* ``put-here operations'' are supposed to be fast. Therefore, they accept inputs
483* and provide outputs in the most convenient places so that no value ever needs
484* to be copied in its entirety. That way, the client can perform exactly the
485* copying it needs depending on where the inputs are and where it wants the output.
486*/
487void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) {
488 // Block unsafe calls
489 if (this == &b || &q == &b || this == &q)
490 throw "BigUnsigned::divideWithRemainder: Some two objects involved are the same";
491
492 /*
493 * Note that the mathematical definition of mod (I'm trusting Knuth) is somewhat
494 * different from the way the normal C++ % operator behaves in the case of division by 0.
495 * This function does it Knuth's way.
496 *
497 * We let a / 0 == 0 (it doesn't matter) and a % 0 == a, no exceptions thrown.
498 * This allows us to preserve both Knuth's demand that a mod 0 == a
499 * and the useful property that (a / b) * b + (a % b) == a.
500 */
501 if (b.len == 0) {
502 q.len = 0;
503 return;
504 }
505
506 /*
507 * If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into
508 * *this at all. The quotient is 0 and *this is already the remainder (so leave it alone).
509 */
510 if (len < b.len) {
511 q.len = 0;
512 return;
513 }
514
515 /*
516 * At this point we know *this > b > 0. (Whew!)
517 */
518
05780f4b 519 /*
4efbb076
MM
520 * Overall method:
521 *
522 * For each appropriate i and i2, decreasing:
523 * Try to subtract (b << (i blocks and i2 bits)) from *this.
524 * (`work2' holds the result of this subtraction.)
525 * If the result is nonnegative:
526 * Turn on bit i2 of block i of the quotient q.
527 * Save the result of the subtraction back into *this.
528 * Otherwise:
529 * Bit i2 of block i remains off, and *this is unchanged.
530 *
531 * Eventually q will contain the entire quotient, and *this will
532 * be left with the remainder.
05780f4b
MM
533 *
534 * We use work2 to temporarily store the result of a subtraction.
4efbb076
MM
535 * work2[x] corresponds to blk[x], not blk[x+i], since 2005.01.11.
536 * If the subtraction is successful, we copy work2 back to blk.
537 * (There's no `work1'. In a previous version, when division was
538 * coded for a read-only dividend, `work1' played the role of
539 * the here-modifiable `*this' and got the remainder.)
540 *
541 * We never touch the i lowest blocks of either blk or work2 because
542 * they are unaffected by the subtraction: we are subtracting
543 * (b << (i blocks and i2 bits)), which ends in at least `i' zero blocks.
544 */
05780f4b
MM
545 // Variables for the calculation
546 Index i, j, k;
547 unsigned int i2;
4efbb076 548 Blk temp;
05780f4b
MM
549 bool borrowIn, borrowOut;
550
2f145f11
MM
551 /*
552 * Make sure we have an extra zero block just past the value.
2f145f11 553 *
4efbb076
MM
554 * When we attempt a subtraction, we might shift `b' so
555 * its first block begins a few bits left of the dividend,
556 * and then we'll try to compare these extra bits with
557 * a nonexistent block to the left of the dividend. The
558 * extra zero block ensures sensible behavior; we need
559 * an extra block in `work2' for exactly the same reason.
560 *
561 * See below `divideWithRemainder' for the interesting and
562 * amusing story of this section of code.
2f145f11 563 */
4efbb076
MM
564 Index origLen = len; // Save real length.
565 len++; // Increase the length.
566 allocateAndCopy(len); // Get the space.
567 blk[origLen] = 0; // Zero the extra block.
05780f4b 568
4efbb076
MM
569 // work2 holds part of the result of a subtraction; see above.
570 Blk *work2 = new Blk[len];
05780f4b
MM
571
572 // Set preliminary length for quotient and make room
2f145f11 573 q.len = origLen - b.len + 1;
05780f4b
MM
574 q.allocate(q.len);
575 // Zero out the quotient
576 for (i = 0; i < q.len; i++)
577 q.blk[i] = 0;
578
579 // For each possible left-shift of b in blocks...
580 i = q.len;
581 while (i > 0) {
582 i--;
583 // For each possible left-shift of b in bits...
4efbb076 584 // (Remember, N is the number of bits in a Blk.)
05780f4b 585 q.blk[i] = 0;
4efbb076 586 i2 = N;
05780f4b
MM
587 while (i2 > 0) {
588 i2--;
589 /*
4efbb076
MM
590 * Subtract b, shifted left i blocks and i2 bits, from *this,
591 * and store the answer in work2. In the for loop, `k == i + j'.
05780f4b
MM
592 *
593 * Compare this to the middle section of `multiply'. They
4efbb076
MM
594 * are in many ways analogous. See especially the discussion
595 * of `getShiftedBlock'.
05780f4b 596 */
4efbb076
MM
597 for (j = 0, k = i, borrowIn = false; j <= b.len; j++, k++) {
598 temp = blk[k] - getShiftedBlock(b, j, i2);
05780f4b
MM
599 borrowOut = (temp > blk[k]);
600 if (borrowIn) {
601 borrowOut |= (temp == 0);
602 temp--;
603 }
4efbb076
MM
604 // Since 2005.01.11, indices of `work2' directly match those of `blk', so use `k'.
605 work2[k] = temp;
05780f4b 606 borrowIn = borrowOut;
05780f4b 607 }
4efbb076
MM
608 // No more extra iteration to deal with `bHigh'.
609 // Roll-over a borrow as necessary.
610 for (; k < origLen && borrowIn; k++) {
05780f4b 611 borrowIn = (blk[k] == 0);
4efbb076 612 work2[k] = blk[k] - 1;
05780f4b 613 }
4efbb076
MM
614 /*
615 * If the subtraction was performed successfully (!borrowIn),
616 * set bit i2 in block i of the quotient.
617 *
618 * Then, copy the portion of work2 filled by the subtraction
619 * back to *this. This portion starts with block i and ends--
620 * where? Not necessarily at block `i + b.len'! Well, we
621 * increased k every time we saved a block into work2, so
622 * the region of work2 we copy is just [i, k).
623 */
05780f4b 624 if (!borrowIn) {
26a5f52b 625 q.blk[i] |= (Blk(1) << i2);
4efbb076 626 while (k > i) {
05780f4b 627 k--;
4efbb076 628 blk[k] = work2[k];
05780f4b
MM
629 }
630 }
631 }
632 }
633 // Zap possible leading zero in quotient
634 if (q.blk[q.len - 1] == 0)
635 q.len--;
636 // Zap any/all leading zeros in remainder
637 zapLeadingZeros();
638 // Deallocate temporary array.
639 // (Thanks to Brad Spencer for noticing my accidental omission of this!)
640 delete [] work2;
641
05780f4b 642}
4efbb076
MM
643/*
644* The out-of-bounds accesses story:
645*
646* On 2005.01.06 or 2005.01.07 (depending on your time zone),
647* Milan Tomic reported out-of-bounds memory accesses in
648* the Big Integer Library. To investigate the problem, I
649* added code to bounds-check every access to the `blk' array
650* of a `NumberlikeArray'.
651*
652* This gave me warnings that fell into two categories of false
653* positives. The bounds checker was based on length, not
654* capacity, and in two places I had accessed memory that I knew
655* was inside the capacity but that wasn't inside the length:
656*
657* (1) The extra zero block at the left of `*this'. Earlier
658* versions said `allocateAndCopy(len + 1); blk[len] = 0;'
659* but did not increment `len'.
660*
661* (2) The entire digit array in the conversion constructor
662* ``BigUnsignedInABase(BigUnsigned)''. It was allocated with
663* a conservatively high capacity, but the length wasn't set
664* until the end of the constructor.
665*
666* To simplify matters, I changed both sections of code so that
667* all accesses occurred within the length. The messages went
668* away, and I told Milan that I couldn't reproduce the problem,
669* sending a development snapshot of the bounds-checked code.
670*
671* Then, on 2005.01.09-10, he told me his debugger still found
672* problems, specifically at the line `delete [] work2'.
673* It was `work2', not `blk', that was causing the problems;
674* this possibility had not occurred to me at all. In fact,
675* the problem was that `work2' needed an extra block just
676* like `*this'. Go ahead and laugh at me for finding (1)
677* without seeing what was actually causing the trouble. :-)
678*
679* The 2005.01.11 version fixes this problem. I hope this is
680* the last of my memory-related bloopers. So this is what
681* starts happening to your C++ code if you use Java too much!
682*/
05780f4b
MM
683
684// Bitwise and
685void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) {
686 // Block unsafe calls
687 if (this == &a || this == &b)
688 throw "BigUnsigned::bitAnd: One of the arguments is the invoked object";
689 len = (a.len >= b.len) ? b.len : a.len;
690 allocate(len);
691 Index i;
692 for (i = 0; i < len; i++)
693 blk[i] = a.blk[i] & b.blk[i];
694 zapLeadingZeros();
695}
696
697// Bitwise or
698void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) {
699 // Block unsafe calls
700 if (this == &a || this == &b)
701 throw "BigUnsigned::bitOr: One of the arguments is the invoked object";
702 Index i;
703 const BigUnsigned *a2, *b2;
704 if (a.len >= b.len) {
705 a2 = &a;
706 b2 = &b;
707 } else {
708 a2 = &b;
709 b2 = &a;
710 }
711 allocate(a2->len);
712 for (i = 0; i < b2->len; i++)
713 blk[i] = a2->blk[i] | b2->blk[i];
714 for (; i < a2->len; i++)
715 blk[i] = a2->blk[i];
716 len = a2->len;
717}
718
719// Bitwise xor
720void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) {
721 // Block unsafe calls
722 if (this == &a || this == &b)
723 throw "BigUnsigned::bitXor: One of the arguments is the invoked object";
724 Index i;
725 const BigUnsigned *a2, *b2;
726 if (a.len >= b.len) {
727 a2 = &a;
728 b2 = &b;
729 } else {
730 a2 = &b;
731 b2 = &a;
732 }
733 allocate(b2->len);
734 for (i = 0; i < b2->len; i++)
735 blk[i] = a2->blk[i] ^ b2->blk[i];
736 for (; i < a2->len; i++)
737 blk[i] = a2->blk[i];
738 len = a2->len;
739 zapLeadingZeros();
740}
741
742// INCREMENT/DECREMENT OPERATORS
743
744// Prefix increment
745void BigUnsigned::operator ++() {
746 Index i;
747 bool carry = true;
748 for (i = 0; i < len && carry; i++) {
749 blk[i]++;
750 carry = (blk[i] == 0);
751 }
752 if (carry) {
753 // Matt fixed a bug 2004.12.24: next 2 lines used to say allocateAndCopy(len + 1)
918d66f2
MM
754 // Matt fixed another bug 2006.04.24:
755 // old number only has len blocks, so copy before increasing length
756 allocateAndCopy(len + 1);
05780f4b 757 len++;
05780f4b
MM
758 blk[i] = 1;
759 }
760}
761
762// Postfix increment: same as prefix
763void BigUnsigned::operator ++(int) {
764 operator ++();
765}
766
767// Prefix decrement
768void BigUnsigned::operator --() {
769 if (len == 0)
770 throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero";
771 Index i;
772 bool borrow = true;
773 for (i = 0; borrow; i++) {
774 borrow = (blk[i] == 0);
775 blk[i]--;
776 }
777 // Zap possible leading zero (there can only be one)
778 if (blk[len - 1] == 0)
779 len--;
780}
781
782// Postfix decrement: same as prefix
783void BigUnsigned::operator --(int) {
784 operator --();
785}