1 // Copyright 2014 The PDFium Authors
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 #ifndef BIGUNSIGNED_H
8 #define BIGUNSIGNED_H
9
10 #include "NumberlikeArray.hh"
11
12 /* A BigUnsigned object represents a nonnegative integer of size limited only by
13 * available memory. BigUnsigneds support most mathematical operators and can
14 * be converted to and from most primitive integer types.
15 *
16 * The number is stored as a NumberlikeArray of unsigned longs as if it were
17 * written in base 256^sizeof(unsigned long). The least significant block is
18 * first, and the length is such that the most significant block is nonzero. */
19 class BigUnsigned : protected NumberlikeArray<unsigned long> {
20
21 public:
22 // Enumeration for the result of a comparison.
23 enum CmpRes { less = -1, equal = 0, greater = 1 };
24
25 // BigUnsigneds are built with a Blk type of unsigned long.
26 typedef unsigned long Blk;
27
28 typedef NumberlikeArray<Blk>::Index Index;
29 using NumberlikeArray<Blk>::N;
30
31 protected:
32 // Creates a BigUnsigned with a capacity; for internal use.
BigUnsigned(int,Index c)33 BigUnsigned(int, Index c) : NumberlikeArray<Blk>(0, c) {}
34
35 // Decreases len to eliminate any leading zero blocks.
zapLeadingZeros()36 void zapLeadingZeros() {
37 while (len > 0 && blk[len - 1] == 0)
38 len--;
39 }
40
41 public:
42 // Constructs zero.
BigUnsigned()43 BigUnsigned() : NumberlikeArray<Blk>() {}
44
45 // Copy constructor
BigUnsigned(const BigUnsigned & x)46 BigUnsigned(const BigUnsigned &x) : NumberlikeArray<Blk>(x) {}
47
48 // Assignment operator
operator =(const BigUnsigned & x)49 BigUnsigned& operator=(const BigUnsigned &x) {
50 NumberlikeArray<Blk>::operator =(x);
51 return *this;
52 }
53
54 // Constructor that copies from a given array of blocks.
BigUnsigned(const Blk * b,Index blen)55 BigUnsigned(const Blk *b, Index blen) : NumberlikeArray<Blk>(b, blen) {
56 // Eliminate any leading zeros we may have been passed.
57 zapLeadingZeros();
58 }
59
60 // Destructor. NumberlikeArray does the delete for us.
~BigUnsigned()61 ~BigUnsigned() {}
62
63 // Constructors from primitive integer types
64 BigUnsigned(unsigned long x);
65 BigUnsigned( long x);
66 BigUnsigned(unsigned int x);
67 BigUnsigned( int x);
68 BigUnsigned(unsigned short x);
69 BigUnsigned( short x);
70 protected:
71 // Helpers
72 template <class X> void initFromPrimitive (X x);
73 template <class X> void initFromSignedPrimitive(X x);
74 public:
75
76 /* Converters to primitive integer types
77 * The implicit conversion operators caused trouble, so these are now
78 * named. */
79 unsigned long toUnsignedLong () const;
80 long toLong () const;
81 unsigned int toUnsignedInt () const;
82 int toInt () const;
83 unsigned short toUnsignedShort() const;
84 short toShort () const;
85 protected:
86 // Helpers
87 template <class X> X convertToSignedPrimitive() const;
88 template <class X> X convertToPrimitive () const;
89 public:
90
91 // BIT/BLOCK ACCESSORS
92
93 // Expose these from NumberlikeArray directly.
94 using NumberlikeArray<Blk>::getCapacity;
95 using NumberlikeArray<Blk>::getLength;
96
97 /* Returns the requested block, or 0 if it is beyond the length (as if
98 * the number had 0s infinitely to the left). */
getBlock(Index i) const99 Blk getBlock(Index i) const { return i >= len ? 0 : blk[i]; }
100 /* Sets the requested block. The number grows or shrinks as necessary. */
101 void setBlock(Index i, Blk newBlock);
102
103 // The number is zero if and only if the canonical length is zero.
isZero() const104 bool isZero() const { return NumberlikeArray<Blk>::isEmpty(); }
105
106 /* Returns the length of the number in bits, i.e., zero if the number
107 * is zero and otherwise one more than the largest value of bi for
108 * which getBit(bi) returns true. */
109 Index bitLength() const;
110 /* Get the state of bit bi, which has value 2^bi. Bits beyond the
111 * number's length are considered to be 0. */
getBit(Index bi) const112 bool getBit(Index bi) const {
113 return (getBlock(bi / N) & (Blk(1) << (bi % N))) != 0;
114 }
115 /* Sets the state of bit bi to newBit. The number grows or shrinks as
116 * necessary. */
117 void setBit(Index bi, bool newBit);
118
119 // COMPARISONS
120
121 // Compares this to x like Perl's <=>
122 CmpRes compareTo(const BigUnsigned &x) const;
123
124 // Ordinary comparison operators
operator ==(const BigUnsigned & x) const125 bool operator ==(const BigUnsigned &x) const {
126 return NumberlikeArray<Blk>::operator ==(x);
127 }
operator !=(const BigUnsigned & x) const128 bool operator !=(const BigUnsigned &x) const {
129 return NumberlikeArray<Blk>::operator !=(x);
130 }
operator <(const BigUnsigned & x) const131 bool operator < (const BigUnsigned &x) const { return compareTo(x) == less ; }
operator <=(const BigUnsigned & x) const132 bool operator <=(const BigUnsigned &x) const { return compareTo(x) != greater; }
operator >=(const BigUnsigned & x) const133 bool operator >=(const BigUnsigned &x) const { return compareTo(x) != less ; }
operator >(const BigUnsigned & x) const134 bool operator > (const BigUnsigned &x) const { return compareTo(x) == greater; }
135
136 /*
137 * BigUnsigned and BigInteger both provide three kinds of operators.
138 * Here ``big-integer'' refers to BigInteger or BigUnsigned.
139 *
140 * (1) Overloaded ``return-by-value'' operators:
141 * +, -, *, /, %, unary -, &, |, ^, <<, >>.
142 * Big-integer code using these operators looks identical to code using
143 * the primitive integer types. These operators take one or two
144 * big-integer inputs and return a big-integer result, which can then
145 * be assigned to a BigInteger variable or used in an expression.
146 * Example:
147 * BigInteger a(1), b = 1;
148 * BigInteger c = a + b;
149 *
150 * (2) Overloaded assignment operators:
151 * +=, -=, *=, /=, %=, flipSign, &=, |=, ^=, <<=, >>=, ++, --.
152 * Again, these are used on big integers just like on ints. They take
153 * one writable big integer that both provides an operand and receives a
154 * result. Most also take a second read-only operand.
155 * Example:
156 * BigInteger a(1), b(1);
157 * a += b;
158 *
159 * (3) Copy-less operations: `add', `subtract', etc.
160 * These named methods take operands as arguments and store the result
161 * in the receiver (*this), avoiding unnecessary copies and allocations.
162 * `divideWithRemainder' is special: it both takes the dividend from and
163 * stores the remainder into the receiver, and it takes a separate
164 * object in which to store the quotient. NOTE: If you are wondering
165 * why these don't return a value, you probably mean to use the
166 * overloaded return-by-value operators instead.
167 *
168 * Examples:
169 * BigInteger a(43), b(7), c, d;
170 *
171 * c = a + b; // Now c == 50.
172 * c.add(a, b); // Same effect but without the two copies.
173 *
174 * c.divideWithRemainder(b, d);
175 * // 50 / 7; now d == 7 (quotient) and c == 1 (remainder).
176 *
177 * // ``Aliased'' calls now do the right thing using a temporary
178 * // copy, but see note on `divideWithRemainder'.
179 * a.add(a, b);
180 */
181
182 // COPY-LESS OPERATIONS
183
184 // These 8: Arguments are read-only operands, result is saved in *this.
185 void add(const BigUnsigned &a, const BigUnsigned &b);
186 void subtract(const BigUnsigned &a, const BigUnsigned &b);
187 void multiply(const BigUnsigned &a, const BigUnsigned &b);
188 void bitAnd(const BigUnsigned &a, const BigUnsigned &b);
189 void bitOr(const BigUnsigned &a, const BigUnsigned &b);
190 void bitXor(const BigUnsigned &a, const BigUnsigned &b);
191 /* Negative shift amounts translate to opposite-direction shifts,
192 * except for -2^(8*sizeof(int)-1) which is unimplemented. */
193 void bitShiftLeft(const BigUnsigned &a, int b);
194 void bitShiftRight(const BigUnsigned &a, int b);
195
196 /* `a.divideWithRemainder(b, q)' is like `q = a / b, a %= b'.
197 * / and % use semantics similar to Knuth's, which differ from the
198 * primitive integer semantics under division by zero. See the
199 * implementation in BigUnsigned.cc for details.
200 * `a.divideWithRemainder(b, a)' throws an exception: it doesn't make
201 * sense to write quotient and remainder into the same variable. */
202 void divideWithRemainder(const BigUnsigned &b, BigUnsigned &q);
203
204 /* `divide' and `modulo' are no longer offered. Use
205 * `divideWithRemainder' instead. */
206
207 // OVERLOADED RETURN-BY-VALUE OPERATORS
208 BigUnsigned operator +(const BigUnsigned &x) const;
209 BigUnsigned operator -(const BigUnsigned &x) const;
210 BigUnsigned operator *(const BigUnsigned &x) const;
211 BigUnsigned operator /(const BigUnsigned &x) const;
212 BigUnsigned operator %(const BigUnsigned &x) const;
213 /* OK, maybe unary minus could succeed in one case, but it really
214 * shouldn't be used, so it isn't provided. */
215 BigUnsigned operator &(const BigUnsigned &x) const;
216 BigUnsigned operator |(const BigUnsigned &x) const;
217 BigUnsigned operator ^(const BigUnsigned &x) const;
218 BigUnsigned operator <<(int b) const;
219 BigUnsigned operator >>(int b) const;
220
221 // OVERLOADED ASSIGNMENT OPERATORS
222 BigUnsigned& operator +=(const BigUnsigned &x);
223 BigUnsigned& operator -=(const BigUnsigned &x);
224 BigUnsigned& operator *=(const BigUnsigned &x);
225 BigUnsigned& operator /=(const BigUnsigned &x);
226 BigUnsigned& operator %=(const BigUnsigned &x);
227 BigUnsigned& operator &=(const BigUnsigned &x);
228 BigUnsigned& operator |=(const BigUnsigned &x);
229 BigUnsigned& operator ^=(const BigUnsigned &x);
230 BigUnsigned& operator <<=(int b);
231 BigUnsigned& operator >>=(int b);
232
233 /* INCREMENT/DECREMENT OPERATORS
234 * To discourage messy coding, these do not return *this, so prefix
235 * and postfix behave the same. */
236 BigUnsigned& operator ++( );
237 BigUnsigned operator ++(int);
238 BigUnsigned& operator --( );
239 BigUnsigned operator --(int);
240
241 // Helper function that needs access to BigUnsigned internals
242 friend Blk getShiftedBlock(const BigUnsigned &num, Index x,
243 unsigned int y);
244
245 // See BigInteger.cc.
246 template <class X>
247 friend X convertBigUnsignedToPrimitiveAccess(const BigUnsigned &a);
248 };
249
250 /* Implementing the return-by-value and assignment operators in terms of the
251 * copy-less operations. The copy-less operations are responsible for making
252 * any necessary temporary copies to work around aliasing. */
253
operator +(const BigUnsigned & x) const254 inline BigUnsigned BigUnsigned::operator +(const BigUnsigned &x) const {
255 BigUnsigned ans;
256 ans.add(*this, x);
257 return ans;
258 }
operator -(const BigUnsigned & x) const259 inline BigUnsigned BigUnsigned::operator -(const BigUnsigned &x) const {
260 BigUnsigned ans;
261 ans.subtract(*this, x);
262 return ans;
263 }
operator *(const BigUnsigned & x) const264 inline BigUnsigned BigUnsigned::operator *(const BigUnsigned &x) const {
265 BigUnsigned ans;
266 ans.multiply(*this, x);
267 return ans;
268 }
operator /(const BigUnsigned & x) const269 inline BigUnsigned BigUnsigned::operator /(const BigUnsigned &x) const {
270 if (x.isZero())
271 abort();
272 BigUnsigned q, r;
273 r = *this;
274 r.divideWithRemainder(x, q);
275 return q;
276 }
operator %(const BigUnsigned & x) const277 inline BigUnsigned BigUnsigned::operator %(const BigUnsigned &x) const {
278 if (x.isZero())
279 abort();
280 BigUnsigned q, r;
281 r = *this;
282 r.divideWithRemainder(x, q);
283 return r;
284 }
operator &(const BigUnsigned & x) const285 inline BigUnsigned BigUnsigned::operator &(const BigUnsigned &x) const {
286 BigUnsigned ans;
287 ans.bitAnd(*this, x);
288 return ans;
289 }
operator |(const BigUnsigned & x) const290 inline BigUnsigned BigUnsigned::operator |(const BigUnsigned &x) const {
291 BigUnsigned ans;
292 ans.bitOr(*this, x);
293 return ans;
294 }
operator ^(const BigUnsigned & x) const295 inline BigUnsigned BigUnsigned::operator ^(const BigUnsigned &x) const {
296 BigUnsigned ans;
297 ans.bitXor(*this, x);
298 return ans;
299 }
operator <<(int b) const300 inline BigUnsigned BigUnsigned::operator <<(int b) const {
301 BigUnsigned ans;
302 ans.bitShiftLeft(*this, b);
303 return ans;
304 }
operator >>(int b) const305 inline BigUnsigned BigUnsigned::operator >>(int b) const {
306 BigUnsigned ans;
307 ans.bitShiftRight(*this, b);
308 return ans;
309 }
310
operator +=(const BigUnsigned & x)311 inline BigUnsigned& BigUnsigned::operator +=(const BigUnsigned &x) {
312 add(*this, x);
313 return *this;
314 }
operator -=(const BigUnsigned & x)315 inline BigUnsigned& BigUnsigned::operator -=(const BigUnsigned &x) {
316 subtract(*this, x);
317 return *this;
318 }
operator *=(const BigUnsigned & x)319 inline BigUnsigned& BigUnsigned::operator *=(const BigUnsigned &x) {
320 multiply(*this, x);
321 return *this;
322 }
operator /=(const BigUnsigned & x)323 inline BigUnsigned& BigUnsigned::operator /=(const BigUnsigned &x) {
324 if (x.isZero())
325 abort();
326 /* The following technique is slightly faster than copying *this first
327 * when x is large. */
328 BigUnsigned q;
329 divideWithRemainder(x, q);
330 // *this contains the remainder, but we overwrite it with the quotient.
331 *this = q;
332 return *this;
333 }
operator %=(const BigUnsigned & x)334 inline BigUnsigned& BigUnsigned::operator %=(const BigUnsigned &x) {
335 if (x.isZero())
336 abort();
337 BigUnsigned q;
338 // Mods *this by x. Don't care about quotient left in q.
339 divideWithRemainder(x, q);
340 return *this;
341 }
operator &=(const BigUnsigned & x)342 inline BigUnsigned& BigUnsigned::operator &=(const BigUnsigned &x) {
343 bitAnd(*this, x);
344 return *this;
345 }
operator |=(const BigUnsigned & x)346 inline BigUnsigned& BigUnsigned::operator |=(const BigUnsigned &x) {
347 bitOr(*this, x);
348 return *this;
349 }
operator ^=(const BigUnsigned & x)350 inline BigUnsigned& BigUnsigned::operator ^=(const BigUnsigned &x) {
351 bitXor(*this, x);
352 return *this;
353 }
operator <<=(int b)354 inline BigUnsigned& BigUnsigned::operator <<=(int b) {
355 bitShiftLeft(*this, b);
356 return *this;
357 }
operator >>=(int b)358 inline BigUnsigned& BigUnsigned::operator >>=(int b) {
359 bitShiftRight(*this, b);
360 return *this;
361 }
362
363 /* Templates for conversions of BigUnsigned to and from primitive integers.
364 * BigInteger.cc needs to instantiate convertToPrimitive, and the uses in
365 * BigUnsigned.cc didn't do the trick; I think g++ inlined convertToPrimitive
366 * instead of generating linkable instantiations. So for consistency, I put
367 * all the templates here. */
368
369 // CONSTRUCTION FROM PRIMITIVE INTEGERS
370
371 /* Initialize this BigUnsigned from the given primitive integer. The same
372 * pattern works for all primitive integer types, so I put it into a template to
373 * reduce code duplication. (Don't worry: this is protected and we instantiate
374 * it only with primitive integer types.) Type X could be signed, but x is
375 * known to be nonnegative. */
376 template <class X>
initFromPrimitive(X x)377 void BigUnsigned::initFromPrimitive(X x) {
378 if (x == 0)
379 ; // NumberlikeArray already initialized us to zero.
380 else {
381 // Create a single block. blk is NULL; no need to delete it.
382 cap = 1;
383 blk = new Blk[1];
384 len = 1;
385 blk[0] = Blk(x);
386 }
387 }
388
389 /* Ditto, but first check that x is nonnegative. I could have put the check in
390 * initFromPrimitive and let the compiler optimize it out for unsigned-type
391 * instantiations, but I wanted to avoid the warning stupidly issued by g++ for
392 * a condition that is constant in *any* instantiation, even if not in all. */
393 template <class X>
initFromSignedPrimitive(X x)394 void BigUnsigned::initFromSignedPrimitive(X x) {
395 if (x < 0)
396 abort();
397 else
398 initFromPrimitive(x);
399 }
400
401 // CONVERSION TO PRIMITIVE INTEGERS
402
403 /* Template with the same idea as initFromPrimitive. This might be slightly
404 * slower than the previous version with the masks, but it's much shorter and
405 * clearer, which is the library's stated goal. */
406 template <class X>
convertToPrimitive() const407 X BigUnsigned::convertToPrimitive() const {
408 if (len == 0)
409 // The number is zero; return zero.
410 return 0;
411 else if (len == 1) {
412 // The single block might fit in an X. Try the conversion.
413 X x = X(blk[0]);
414 // Make sure the result accurately represents the block.
415 if (Blk(x) == blk[0])
416 // Successful conversion.
417 return x;
418 // Otherwise fall through.
419 }
420 abort();
421 }
422
423 /* Wrap the above in an x >= 0 test to make sure we got a nonnegative result,
424 * not a negative one that happened to convert back into the correct nonnegative
425 * one. (E.g., catch incorrect conversion of 2^31 to the long -2^31.) Again,
426 * separated to avoid a g++ warning. */
427 template <class X>
convertToSignedPrimitive() const428 X BigUnsigned::convertToSignedPrimitive() const {
429 X x = convertToPrimitive<X>();
430 if (x >= 0)
431 return x;
432 else
433 abort();
434 }
435
436 #endif
437