Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(37)

Side by Side Diff: runtime/lib/bigint.dart

Issue 509153003: New bigint implementation in the vm. (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 6 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « runtime/lib/array.cc ('k') | runtime/lib/bool.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 // Copyright 2009 The Go Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style
7 // license that can be found in the LICENSE file.
8
9 /*
10 * Copyright (c) 2003-2005 Tom Wu
11 * Copyright (c) 2012 Adam Singer (adam@solvr.io)
12 * All Rights Reserved.
13 *
14 * Permission is hereby granted, free of charge, to any person obtaining
15 * a copy of this software and associated documentation files (the
16 * "Software"), to deal in the Software without restriction, including
17 * without limitation the rights to use, copy, modify, merge, publish,
18 * distribute, sublicense, and/or sell copies of the Software, and to
19 * permit persons to whom the Software is furnished to do so, subject to
20 * the following conditions:
21 *
22 * The above copyright notice and this permission notice shall be
23 * included in all copies or substantial portions of the Software.
24 *
25 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
26 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
27 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
28 *
29 * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
30 * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
31 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
32 * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
33 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34 *
35 * In addition, the following condition applies:
36 *
37 * All redistributions must retain an intact copy of this copyright notice
38 * and disclaimer.
39 */
40
41 class _Bigint extends _IntegerImplementation implements int {
42 // Bits per digit.
43 static const int DIGIT_BITS = 32;
44 static const int DIGIT_BASE = 1 << DIGIT_BITS;
45 static const int DIGIT_MASK = (1 << DIGIT_BITS) - 1;
46
47 // Bits per half digit.
48 static const int DIGIT2_BITS = DIGIT_BITS >> 1;
49 static const int DIGIT2_BASE = 1 << DIGIT2_BITS;
50 static const int DIGIT2_MASK = (1 << DIGIT2_BITS) - 1;
51
52 // Allocate extra digits so the bigint can be reused.
53 static const int EXTRA_DIGITS = 4;
54
55 // Floating-point unit integer precision.
56 static const int FP_BITS = 52;
57 static const int FP_BASE = 1 << FP_BITS;
58 static const int FP_D1 = FP_BITS - DIGIT_BITS;
59 static const int FP_D2 = 2 * DIGIT_BITS - FP_BITS;
60
61 // Min and max of non bigint values.
62 static const int MIN_INT64 = (-1) << 63;
63 static const int MAX_INT64 = 0x7fffffffffffffff;
64
65 // Bigint constant values.
66 // Note: Not declared as final in order to satisfy optimizer, which expects
67 // constants to be in canonical form (Smi).
68 static _Bigint ZERO = new _Bigint();
69 static _Bigint ONE = new _Bigint()._setInt(1);
70
71 // Digit conversion table for parsing.
72 static final Map<int, int> DIGIT_TABLE = _createDigitTable();
73
74 // Internal data structure.
75 bool get _neg native "Bigint_getNeg";
76 void set _neg(bool neg) native "Bigint_setNeg";
77 int get _used native "Bigint_getUsed";
78 void set _used(int used) native "Bigint_setUsed";
79 Uint32List get _digits native "Bigint_getDigits";
Vyacheslav Egorov (Google) 2014/09/10 11:44:12 Any reason why is this not a real field? This is
regis 2014/09/10 17:34:17 Class _Bigint being part of the integer class hier
Vyacheslav Egorov (Google) 2014/09/10 17:40:44 But we can force fields declared in the dart code
80 void set _digits(Uint32List digits) native "Bigint_setDigits";
81
82 // Factory returning an instance initialized to value 0.
83 factory _Bigint() native "Bigint_allocate";
84
85 // Factory returning an instance initialized to an integer value.
86 factory _Bigint._fromInt(int i) {
87 return new _Bigint()._setInt(i);
88 }
89
90 // Factory returning an instance initialized to a hex string.
91 factory _Bigint._fromHex(String s) {
92 return new _Bigint()._setHex(s);
93 }
94
95 // Factory returning an instance initialized to a double value given by its
96 // components.
97 factory _Bigint._fromDouble(int sign, int significand, int exponent) {
98 return new _Bigint()._setDouble(sign, significand, exponent);
99 }
100
101 // Initialize instance to the given value no larger than a Mint.
102 _Bigint _setInt(int i) {
103 assert(i is! _Bigint);
104 _ensureLength(2);
105 _used = 2;
106 var l, h;
107 if (i < 0) {
108 _neg = true;
109 if (i == MIN_INT64) {
110 l = 0;
111 h = 0x80000000;
112 } else {
113 l = (-i) & DIGIT_MASK;
114 h = (-i) >> DIGIT_BITS;
115 }
116 } else {
117 _neg = false;
118 l = i & DIGIT_MASK;
119 h = i >> DIGIT_BITS;
120 }
121 _digits[0] = l;
122 _digits[1] = h;
123 _clamp();
124 return this;
125 }
126
127 // Initialize instance to the given hex string.
128 // TODO(regis): Copy Bigint::NewFromHexCString, fewer digit accesses.
129 // TODO(regis): Unused.
130 _Bigint _setHex(String s) {
131 const int HEX_BITS = 4;
132 const int HEX_DIGITS_PER_DIGIT = 8;
133 var hexDigitIndex = s.length;
134 _ensureLength((hexDigitIndex + HEX_DIGITS_PER_DIGIT - 1) ~/ HEX_DIGITS_PER_D IGIT);
135 var bitIndex = 0;
136 while (--hexDigitIndex >= 0) {
137 var digit = DIGIT_TABLE[s.codeUnitAt(hexDigitIndex)];
138 if (digit = null) {
139 if (s[hexDigitIndex] == "-") _neg = true;
140 continue; // Ignore invalid digits.
141 }
142 _neg = false; // Ignore "-" if not at index 0.
143 if (bitIndex == 0) {
144 _digits[_used++] = digit;
145 // TODO(regis): What if too many bad digits were ignored and
146 // _used becomes larger than _digits.length? error or reallocate?
147 } else {
148 _digits[_used - 1] |= digit << bitIndex;
149 }
150 bitIndex = (bitIndex + HEX_BITS) % DIGIT_BITS;
151 }
152 _clamp();
153 return this;
154 }
155
156 // Initialize instance to the given double value.
157 _Bigint _setDouble(int sign, int significand, int exponent) {
158 assert(significand >= 0);
159 assert(exponent >= 0);
160 _setInt(significand);
161 _neg = sign < 0;
162 if (exponent > 0) {
163 _lShiftTo(exponent, this);
164 }
165 return this;
166 }
167
168 // Create digit conversion table for parsing.
169 static Map<int, int> _createDigitTable() {
170 Map table = new HashMap();
171 int digit, value;
172 digit = "0".codeUnitAt(0);
173 for(value = 0; value <= 9; ++value) table[digit++] = value;
174 digit = "a".codeUnitAt(0);
175 for(value = 10; value < 36; ++value) table[digit++] = value;
176 digit = "A".codeUnitAt(0);
177 for(value = 10; value < 36; ++value) table[digit++] = value;
178 return table;
179 }
180
181 // Return most compact integer (i.e. possibly Smi or Mint).
182 // TODO(regis): Intrinsify.
183 int _toValidInt() {
184 assert(DIGIT_BITS == 32); // Otherwise this code needs to be revised.
185 if (_used == 0) return 0;
186 if (_used == 1) return _neg ? -_digits[0] : _digits[0];
187 if (_used > 2) return this;
188 if (_neg) {
189 if (_digits[1] > 0x80000000) return this;
190 if (_digits[1] == 0x80000000) {
191 if (_digits[0] > 0) return this;
192 return MIN_INT64;
193 }
194 return -((_digits[1] << DIGIT_BITS) | _digits[0]);
195 }
196 if (_digits[1] >= 0x80000000) return this;
197 return (_digits[1] << DIGIT_BITS) | _digits[0];
198 }
199
200 // Conversion from int to bigint.
201 _Bigint _toBigint() => this;
202
203 // Make sure at least 'length' _digits are allocated.
204 // Copy existing _digits if reallocation is necessary.
205 // TODO(regis): Check that we are not preserving _digits unnecessarily.
206 void _ensureLength(int length) {
207 if (length > 0 && (_digits == null || length > _digits.length)) {
208 var new_digits = new Uint32List(length + EXTRA_DIGITS);
209 if (_digits != null) {
210 for (var i = _used; --i >= 0; ) {
211 new_digits[i] = _digits[i];
212 }
213 }
214 _digits = new_digits;
215 }
216 }
217
218 // Clamp off excess high _digits.
219 void _clamp() {
220 while (_used > 0 && _digits[_used - 1] == 0) {
221 --_used;
222 }
223 assert(_used > 0 || !_neg);
224 }
225
226 // Copy this to r.
227 void _copyTo(_Bigint r) {
228 r._ensureLength(_used);
229 for (var i = _used - 1; i >= 0; --i) {
230 r._digits[i] = _digits[i];
231 }
232 r._used = _used;
233 r._neg = _neg;
234 }
235
236 // Return the bit length of digit x.
237 int _nbits(int x) {
238 var r = 1, t;
239 if ((t = x >> 16) != 0) { x = t; r += 16; }
240 if ((t = x >> 8) != 0) { x = t; r += 8; }
241 if ((t = x >> 4) != 0) { x = t; r += 4; }
242 if ((t = x >> 2) != 0) { x = t; r += 2; }
243 if ((x >> 1) != 0) { r += 1; }
244 return r;
245 }
246
247 // r = this << n*DIGIT_BITS.
248 void _dlShiftTo(int n, _Bigint r) {
249 var r_used = _used + n;
250 r._ensureLength(r_used);
251 for (var i = _used - 1; i >= 0; --i) {
252 r._digits[i + n] = _digits[i];
253 }
254 for (var i = n - 1; i >= 0; --i) {
255 r._digits[i] = 0;
256 }
257 r._used = r_used;
258 r._neg = _neg;
259 }
260
261 // r = this >> n*DIGIT_BITS.
262 void _drShiftTo(int n, _Bigint r) {
263 var r_used = _used - n;
264 if (r_used < 0) {
265 if (_neg) {
266 // Set r to -1.
267 r._neg = true;
268 r._ensureLength(1);
269 r._used = 1;
270 r._digits[0] = 1;
271 } else {
272 // Set r to 0.
273 r._neg = false;
274 r._used = 0;
275 }
276 return;
277 }
278 r._ensureLength(r_used);
279 for (var i = n; i < _used; ++i) {
280 r._digits[i - n] = _digits[i];
281 }
282 r._used = r_used;
283 r._neg = _neg;
284 if (_neg) {
285 // Round down if any bit was shifted out.
286 for (var i = 0; i < n; i++) {
287 if (_digits[i] != 0) {
288 r._subTo(ONE, r);
289 break;
290 }
291 }
292 }
293 }
294
295 // r = this << n.
296 void _lShiftTo(int n, _Bigint r) {
297 var ds = n ~/ DIGIT_BITS;
298 var bs = n % DIGIT_BITS;
299 if (bs == 0) {
300 _dlShiftTo(ds, r);
301 return;
302 }
303 var cbs = DIGIT_BITS - bs;
304 var bm = (1 << cbs) - 1;
305 var r_used = _used + ds + 1;
306 r._ensureLength(r_used);
307 var c = 0;
308 for (var i = _used - 1; i >= 0; --i) {
309 r._digits[i + ds + 1] = (_digits[i] >> cbs) | c;
310 c = (_digits[i] & bm) << bs;
311 }
312 for (var i = ds - 1; i >= 0; --i) {
313 r._digits[i] = 0;
314 }
315 r._digits[ds] = c;
316 r._used = r_used;
317 r._neg = _neg;
318 r._clamp();
319 }
320
321 // r = this >> n.
322 void _rShiftTo(int n, _Bigint r) {
323 var ds = n ~/ DIGIT_BITS;
324 var bs = n % DIGIT_BITS;
325 if (bs == 0) {
326 _drShiftTo(ds, r);
327 return;
328 }
329 var r_used = _used - ds;
330 if (r_used <= 0) {
331 if (_neg) {
332 // Set r to -1.
333 r._neg = true;
334 r._ensureLength(1);
335 r._used = 1;
336 r._digits[0] = 1;
337 } else {
338 // Set r to 0.
339 r._neg = false;
340 r._used = 0;
341 }
342 return;
343 }
344 var cbs = DIGIT_BITS - bs;
345 var bm = (1 << bs) - 1;
346 r._ensureLength(r_used);
347 r._digits[0] = _digits[ds] >> bs;
348 for (var i = ds + 1; i < _used; ++i) {
349 r._digits[i - ds - 1] |= (_digits[i] & bm) << cbs;
350 r._digits[i - ds] = _digits[i] >> bs;
351 }
352 r._neg = _neg;
353 r._used = r_used;
354 r._clamp();
355 if (_neg) {
356 // Round down if any bit was shifted out.
357 if ((_digits[ds] & bm) != 0) {
358 r._subTo(ONE, r);
359 return;
360 }
361 for (var i = 0; i < ds; i++) {
362 if (_digits[i] != 0) {
363 r._subTo(ONE, r);
364 return;
365 }
366 }
367 }
368 }
369
370 // Return 0 if abs(this) == abs(a).
371 // Return a positive number if abs(this) > abs(a).
372 // Return a negative number if abs(this) < abs(a).
373 int _absCompareTo(_Bigint a) {
374 var r = _used - a._used;
375 if (r == 0) {
376 var i = _used;
377 while (--i >= 0 && (r = _digits[i] - a._digits[i]) == 0);
378 }
379 return r;
380 }
381
382 // Return 0 if this == a.
383 // Return a positive number if this > a.
384 // Return a negative number if this < a.
385 int _compareTo(_Bigint a) {
386 var r;
387 if (_neg == a._neg) {
388 r = _absCompareTo(a);
389 if (_neg) {
390 r = -r;
391 }
392 } else if (_neg) {
393 r = -1;
394 } else {
395 r = 1;
396 }
397 return r;
398 }
399
400 // r = abs(this) + abs(a).
401 void _absAddTo(_Bigint a, _Bigint r) {
402 if (_used < a._used) {
403 a._absAddTo(this, r);
404 return;
405 }
406 if (_used == 0) {
407 // Set r to 0.
408 r._neg = false;
409 r._used = 0;
410 return;
411 }
412 if (a._used == 0) {
413 _copyTo(r);
414 return;
415 }
416 r._ensureLength(_used + 1);
417 var c = 0;
418 for (var i = 0; i < a._used; i++) {
419 c += _digits[i] + a._digits[i];
420 r._digits[i] = c & DIGIT_MASK;
421 c >>= DIGIT_BITS;
422 }
423 for (var i = a._used; i < _used; i++) {
424 c += _digits[i];
425 r._digits[i] = c & DIGIT_MASK;
426 c >>= DIGIT_BITS;
427 }
428 r._digits[_used] = c;
429 r._used = _used + 1;
430 r._clamp();
431 }
432
433 // r = abs(this) - abs(a), with abs(this) >= abs(a).
434 void _absSubTo(_Bigint a, _Bigint r) {
435 assert(_absCompareTo(a) >= 0);
436 if (_used == 0) {
437 // Set r to 0.
438 r._neg = false;
439 r._used = 0;
440 return;
441 }
442 if (a._used == 0) {
443 _copyTo(r);
444 return;
445 }
446 r._ensureLength(_used);
447 var c = 0;
448 for (var i = 0; i < a._used; i++) {
449 c += _digits[i] - a._digits[i];
450 r._digits[i] = c & DIGIT_MASK;
451 c >>= DIGIT_BITS;
452 }
453 for (var i = a._used; i < _used; i++) {
454 c += _digits[i];
455 r._digits[i] = c & DIGIT_MASK;
456 c >>= DIGIT_BITS;
457 }
458 r._used = _used;
459 r._clamp();
460 }
461
462 // r = abs(this) & abs(a).
463 void _absAndTo(_Bigint a, _Bigint r) {
464 var r_used = (_used < a._used) ? _used : a._used;
465 r._ensureLength(r_used);
466 for (var i = 0; i < r_used; i++) {
467 r._digits[i] = _digits[i] & a._digits[i];
468 }
469 r._used = r_used;
470 r._clamp();
471 }
472
473 // r = abs(this) &~ abs(a).
474 void _absAndNotTo(_Bigint a, _Bigint r) {
475 var r_used = _used;
476 r._ensureLength(r_used);
477 var m = (r_used < a._used) ? r_used : a._used;
478 for (var i = 0; i < m; i++) {
479 r._digits[i] = _digits[i] &~ a._digits[i];
480 }
481 for (var i = m; i < r_used; i++) {
482 r._digits[i] = _digits[i];
483 }
484 r._used = r_used;
485 r._clamp();
486 }
487
488 // r = abs(this) | abs(a).
489 void _absOrTo(_Bigint a, _Bigint r) {
490 var r_used = (_used > a._used) ? _used : a._used;
491 r._ensureLength(r_used);
492 var l, m;
493 if (_used < a._used) {
494 l = a;
495 m = _used;
496 } else {
497 l = this;
498 m = a._used;
499 }
500 for (var i = 0; i < m; i++) {
501 r._digits[i] = _digits[i] | a._digits[i];
502 }
503 for (var i = m; i < r_used; i++) {
504 r._digits[i] = l._digits[i];
505 }
506 r._used = r_used;
507 r._clamp();
508 }
509
510 // r = abs(this) ^ abs(a).
511 void _absXorTo(_Bigint a, _Bigint r) {
512 var r_used = (_used > a._used) ? _used : a._used;
513 r._ensureLength(r_used);
514 var l, m;
515 if (_used < a._used) {
516 l = a;
517 m = _used;
518 } else {
519 l = this;
520 m = a._used;
521 }
522 for (var i = 0; i < m; i++) {
523 r._digits[i] = _digits[i] ^ a._digits[i];
524 }
525 for (var i = m; i < r_used; i++) {
526 r._digits[i] = l._digits[i];
527 }
528 r._used = r_used;
529 r._clamp();
530 }
531
532 // Return r = this & a.
533 _Bigint _andTo(_Bigint a, _Bigint r) {
534 if (_neg == a._neg) {
535 if (_neg) {
536 // (-this) & (-a) == ~(this-1) & ~(a-1)
537 // == ~((this-1) | (a-1))
538 // == -(((this-1) | (a-1)) + 1)
539 _Bigint t1 = new _Bigint();
540 _absSubTo(ONE, t1);
541 _Bigint a1 = new _Bigint();
542 a._absSubTo(ONE, a1);
543 t1._absOrTo(a1, r);
544 r._absAddTo(ONE, r);
545 r._neg = true; // r cannot be zero if this and a are negative.
546 return r;
547 }
548 _absAndTo(a, r);
549 r._neg = false;
550 return r;
551 }
552 // _neg != a._neg
553 var p, n;
554 if (_neg) {
555 p = a;
556 n = this;
557 } else { // & is symmetric.
558 p = this;
559 n = a;
560 }
561 // p & (-n) == p & ~(n-1) == p &~ (n-1)
562 _Bigint n1 = new _Bigint();
563 n._absSubTo(ONE, n1);
564 p._absAndNotTo(n1, r);
565 r._neg = false;
566 return r;
567 }
568
569 // Return r = this &~ a.
570 _Bigint _andNotTo(_Bigint a, _Bigint r) {
571 if (_neg == a._neg) {
572 if (_neg) {
573 // (-this) &~ (-a) == ~(this-1) &~ ~(a-1)
574 // == ~(this-1) & (a-1)
575 // == (a-1) &~ (this-1)
576 _Bigint t1 = new _Bigint();
577 _absSubTo(ONE, t1);
578 _Bigint a1 = new _Bigint();
579 a._absSubTo(ONE, a1);
580 a1._absAndNotTo(t1, r);
581 r._neg = false;
582 return r;
583 }
584 _absAndNotTo(a, r);
585 r._neg = false;
586 return r;
587 }
588 if (_neg) {
589 // (-this) &~ a == ~(this-1) &~ a
590 // == ~(this-1) & ~a
591 // == ~((this-1) | a)
592 // == -(((this-1) | a) + 1)
593 _Bigint t1 = new _Bigint();
594 _absSubTo(ONE, t1);
595 t1._absOrTo(a, r);
596 r._absAddTo(ONE, r);
597 r._neg = true; // r cannot be zero if this is negative and a is positive.
598 return r;
599 }
600 // this &~ (-a) == this &~ ~(a-1) == this & (a-1)
601 _Bigint a1 = new _Bigint();
602 a._absSubTo(ONE, a1);
603 _absAndTo(a1, r);
604 r._neg = false;
605 return r;
606 }
607
608 // Return r = this | a.
609 _Bigint _orTo(_Bigint a, _Bigint r) {
610 if (_neg == a._neg) {
611 if (_neg) {
612 // (-this) | (-a) == ~(this-1) | ~(a-1)
613 // == ~((this-1) & (a-1))
614 // == -(((this-1) & (a-1)) + 1)
615 _Bigint t1 = new _Bigint();
616 _absSubTo(ONE, t1);
617 _Bigint a1 = new _Bigint();
618 a._absSubTo(ONE, a1);
619 t1._absAndTo(a1, r);
620 r._absAddTo(ONE, r);
621 r._neg = true; // r cannot be zero if this and a are negative.
622 return r;
623 }
624 _absOrTo(a, r);
625 r._neg = false;
626 return r;
627 }
628 // _neg != a._neg
629 var p, n;
630 if (_neg) {
631 p = a;
632 n = this;
633 } else { // | is symmetric.
634 p = this;
635 n = a;
636 }
637 // p | (-n) == p | ~(n-1) == ~((n-1) &~ p) == -(~((n-1) &~ p) + 1)
638 _Bigint n1 = new _Bigint();
639 n._absSubTo(ONE, n1);
640 n1._absAndNotTo(p, r);
641 r._absAddTo(ONE, r);
642 r._neg = true; // r cannot be zero if only one of this or a is negative.
643 return r;
644 }
645
646 // Return r = this ^ a.
647 _Bigint _xorTo(_Bigint a, _Bigint r) {
648 if (_neg == a._neg) {
649 if (_neg) {
650 // (-this) ^ (-a) == ~(this-1) ^ ~(a-1) == (this-1) ^ (a-1)
651 _Bigint t1 = new _Bigint();
652 _absSubTo(ONE, t1);
653 _Bigint a1 = new _Bigint();
654 a._absSubTo(ONE, a1);
655 t1._absXorTo(a1, r);
656 r._neg = false;
657 return r;
658 }
659 _absXorTo(a, r);
660 r._neg = false;
661 return r;
662 }
663 // _neg != a._neg
664 var p, n;
665 if (_neg) {
666 p = a;
667 n = this;
668 } else { // ^ is symmetric.
669 p = this;
670 n = a;
671 }
672 // p ^ (-n) == p ^ ~(n-1) == ~(p ^ (n-1)) == -((p ^ (n-1)) + 1)
673 _Bigint n1 = new _Bigint();
674 n._absSubTo(ONE, n1);
675 p._absXorTo(n1, r);
676 r._absAddTo(ONE, r);
677 r._neg = true; // r cannot be zero if only one of this or a is negative.
678 return r;
679 }
680
681 // Return r = ~this.
682 _Bigint _notTo(_Bigint r) {
683 if (_neg) {
684 // ~(-this) == ~(~(this-1)) == this-1
685 _absSubTo(ONE, r);
686 r._neg = false;
687 return r;
688 }
689 // ~this == -this-1 == -(this+1)
690 _absAddTo(ONE, r);
691 r._neg = true; // r cannot be zero if this is positive.
692 return r;
693 }
694
695 // Return r = this + a.
696 _Bigint _addTo(_Bigint a, _Bigint r) {
697 var r_neg = _neg;
698 if (_neg == a._neg) {
699 // this + a == this + a
700 // (-this) + (-a) == -(this + a)
701 _absAddTo(a, r);
702 } else {
703 // this + (-a) == this - a == -(this - a)
704 // (-this) + a == a - this == -(this - a)
705 if (_absCompareTo(a) >= 0) {
706 _absSubTo(a, r);
707 } else {
708 r_neg = !r_neg;
709 a._absSubTo(this, r);
710 }
711 }
712 r._neg = r_neg;
713 return r;
714 }
715
716 // Return r = this - a.
717 _Bigint _subTo(_Bigint a, _Bigint r) {
718 var r_neg = _neg;
719 if (_neg != a._neg) {
720 // this - (-a) == this + a
721 // (-this) - a == -(this + a)
722 _absAddTo(a, r);
723 } else {
724 // this - a == this - a == -(this - a)
725 // (-this) - (-a) == a - this == -(this - a)
726 if (_absCompareTo(a) >= 0) {
727 _absSubTo(a, r);
728 } else {
729 r_neg = !r_neg;
730 a._absSubTo(this, r);
731 }
732 }
733 r._neg = r_neg;
734 return r;
735 }
736
737 // Accumulate multiply.
738 // this[i..i+n-1]: bigint multiplicand.
739 // x: digit multiplier.
740 // w[j..j+n-1]: bigint accumulator.
741 // c: int carry in.
742 // Returns carry out.
743 // w[j..j+n-1] += this[i..i+n-1] * x + c.
744 // Returns carry out.
745 // TODO(regis): _sqrTo is the only caller passing an x possibly larger than
746 // a digit (2*digit) and passing a non-zero carry in. Refactor?
747 int _am(int i, int x, _Bigint w, int j, int c, int n) {
748 if (x == 0 && c == 0) {
749 // No-op if both x and c are 0.
750 return 0;
751 }
752 int xl = x & DIGIT2_MASK;
753 int xh = x >> DIGIT2_BITS;
754 while (--n >= 0) {
755 int l = _digits[i] & DIGIT2_MASK;
756 int h = _digits[i++] >> DIGIT2_BITS;
757 int m = xh*l + h*xl;
758 l = xl*l + ((m & DIGIT2_MASK) << DIGIT2_BITS) + w._digits[j] + c;
759 c = (l >> DIGIT_BITS) + (m >> DIGIT2_BITS) + xh*h;
760 w._digits[j++] = l & DIGIT_MASK;
761 }
762 return c;
763 }
764
765 // r = this * a.
766 void _mulTo(_Bigint a, _Bigint r) {
767 // TODO(regis): Use karatsuba multiplication when appropriate.
768 var i = _used;
769 r._ensureLength(i + a._used);
770 r._used = i + a._used;
771 while (--i >= 0) {
772 r._digits[i] = 0;
773 }
774 for (i = 0; i < a._used; ++i) {
775 // TODO(regis): Replace _am with addMulVVW.
776 r._digits[i + _used] = _am(0, a._digits[i], r, i, 0, _used);
777 }
778 r._clamp();
779 r._neg = r._used > 0 && _neg != a._neg; // Zero cannot be negative.
780 }
781
782 // r = this^2, r != this.
783 void _sqrTo(_Bigint r) {
784 var i = 2 * _used;
785 r._ensureLength(i);
786 r._used = i;
787 while (--i >= 0) {
788 r._digits[i] = 0;
789 }
790 for (i = 0; i < _used - 1; ++i) {
791 var c = _am(i, _digits[i], r, 2*i, 0, 1);
792 var d = r._digits[i + _used];
793 d += _am(i + 1, _digits[i] << 1, r, 2*i + 1, c, _used - i - 1);
794 if (d >= DIGIT_BASE) {
795 r._digits[i + _used] = d - DIGIT_BASE;
796 r._digits[i + _used + 1] = 1;
797 } else {
798 r._digits[i + _used] = d;
799 }
800 }
801 if (r._used > 0) {
802 r._digits[r._used - 1] += _am(i, _digits[i], r, 2*i, 0, 1);
803 }
804 r._neg = false;
805 r._clamp();
806 }
807
808 // Truncating division and remainder.
809 // If q != null, q = trunc(this / a).
810 // If r != null, r = this - a * trunc(this / a).
811 void _divRemTo(_Bigint a, _Bigint q, _Bigint r) {
812 if (a._used == 0) return;
813 if (_used < a._used) {
814 if (q != null) {
815 // Set q to 0.
816 q._neg = false;
817 q._used = 0;
818 }
819 if (r != null) {
820 _copyTo(r);
821 }
822 return;
823 }
824 if (r == null) {
825 r = new _Bigint();
826 }
827 var y = new _Bigint();
828 var nsh = DIGIT_BITS - _nbits(a._digits[a._used - 1]); // normalize modulus
829 if (nsh > 0) {
830 a._lShiftTo(nsh, y);
831 _lShiftTo(nsh, r);
832 }
833 else {
834 a._copyTo(y);
835 _copyTo(r);
836 }
837 // We consider this and a positive. Ignore the copied sign.
838 y._neg = false;
839 r._neg = false;
840 var y_used = y._used;
841 var y0 = y._digits[y_used - 1];
842 if (y0 == 0) return;
843 var yt = y0*(1 << FP_D1) + ((y_used > 1) ? y._digits[y_used - 2] >> FP_D2 : 0);
844 var d1 = FP_BASE/yt;
845 var d2 = (1 << FP_D1)/yt;
846 var e = 1 << FP_D2;
847 var i = r._used;
848 var j = i - y_used;
849 _Bigint t = (q == null) ? new _Bigint() : q;
850
851 y._dlShiftTo(j, t);
852
853 if (r._compareTo(t) >= 0) {
854 r._digits[r._used++] = 1;
855 r._subTo(t, r);
856 }
857 ONE._dlShiftTo(y_used, t);
858 t._subTo(y, y); // "negative" y so we can replace sub with _am later
859 while (y._used < y_used) {
860 y._digits[y._used++] = 0;
861 }
862 while (--j >= 0) {
863 // Estimate quotient digit
864 var qd = (r._digits[--i] == y0)
865 ? DIGIT_MASK
866 : (r._digits[i]*d1 + (r._digits[i - 1] + e)*d2).floor();
867 if ((r._digits[i] += y._am(0, qd, r, j, 0, y_used)) < qd) { // Try it out
868 y._dlShiftTo(j, t);
869 r._subTo(t, r);
870 while (r._digits[i] < --qd) {
871 r._subTo(t, r);
872 }
873 }
874 }
875 if (q != null) {
876 r._drShiftTo(y_used, q);
877 if (_neg != a._neg) {
878 ZERO._subTo(q, q);
879 }
880 }
881 r._used = y_used;
882 r._clamp();
883 if (nsh > 0) {
884 r._rShiftTo(nsh, r); // Denormalize remainder
885 }
886 if (_neg) {
887 ZERO._subTo(r, r);
888 }
889 }
890
891 int get _identityHashCode {
892 return this;
893 }
894 int operator ~() {
895 _Bigint result = new _Bigint();
896 _notTo(result);
897 return result._toValidInt();
898 }
899
900 int get bitLength {
901 if (_used == 0) return 0;
902 if (_neg) return (~this).bitLength;
903 return DIGIT_BITS*(_used - 1) + _nbits(_digits[_used - 1]);
904 }
905
906 // This method must support smi._toBigint()._shrFromInt(int).
907 int _shrFromInt(int other) {
908 if (_used == 0) return other; // Shift amount is zero.
909 if (_neg) throw "negative shift amount"; // TODO(regis): What exception?
910 assert(DIGIT_BITS == 32); // Otherwise this code needs to be revised.
911 var shift;
912 if (_used > 2 || (_used == 2 && _digits[1] > 0x10000000)) {
913 if (other < 0) {
914 return -1;
915 } else {
916 return 0;
917 }
918 } else {
919 shift = ((_used == 2) ? (_digits[1] << DIGIT_BITS) : 0) + _digits[0];
920 }
921 _Bigint result = new _Bigint();
922 other._toBigint()._rShiftTo(shift, result);
923 return result._toValidInt();
924 }
925
926 // This method must support smi._toBigint()._shlFromInt(int).
927 // An out of memory exception is thrown if the result cannot be allocated.
928 int _shlFromInt(int other) {
929 if (_used == 0) return other; // Shift amount is zero.
930 if (_neg) throw "negative shift amount"; // TODO(regis): What exception?
931 assert(DIGIT_BITS == 32); // Otherwise this code needs to be revised.
932 var shift;
933 if (_used > 2 || (_used == 2 && _digits[1] > 0x10000000)) {
934 throw new OutOfMemoryError();
935 } else {
936 shift = ((_used == 2) ? (_digits[1] << DIGIT_BITS) : 0) + _digits[0];
937 }
938 _Bigint result = new _Bigint();
939 other._toBigint()._lShiftTo(shift, result);
940 return result._toValidInt();
941 }
942
943 int pow(int exponent) {
944 throw "Bigint.pow not implemented";
945 }
946
947 // Overriden operators and methods.
948
949 // The following operators override operators of _IntegerImplementation for
950 // efficiency, but are not necessary for correctness. They shortcut native
951 // calls that would return null because the receiver is _Bigint.
952 num operator +(num other) {
953 return other._toBigint()._addFromInteger(this);
954 }
955 num operator -(num other) {
956 return other._toBigint()._subFromInteger(this);
957 }
958 num operator *(num other) {
959 return other._toBigint()._mulFromInteger(this);
960 }
961 num operator ~/(num other) {
962 if ((other is int) && (other == 0)) {
963 throw const IntegerDivisionByZeroException();
964 }
965 return other._toBigint()._truncDivFromInteger(this);
966 }
967 num operator /(num other) {
968 return this.toDouble() / other.toDouble();
969 }
970 // TODO(regis): Investigate strange behavior with % double.INFINITY.
971 /*
972 num operator %(num other) {
973 if ((other is int) && (other == 0)) {
974 throw const IntegerDivisionByZeroException();
975 }
976 return other._toBigint()._moduloFromInteger(this);
977 }
978 */
979 int operator &(int other) {
980 return other._toBigint()._bitAndFromInteger(this);
981 }
982 int operator |(int other) {
983 return other._toBigint()._bitOrFromInteger(this);
984 }
985 int operator ^(int other) {
986 return other._toBigint()._bitXorFromInteger(this);
987 }
988 int operator >>(int other) {
989 return other._toBigint()._shrFromInt(this);
990 }
991 int operator <<(int other) {
992 return other._toBigint()._shlFromInt(this);
993 }
994 // End of operator shortcuts.
995
996 int operator -() {
997 if (_used == 0) {
998 return this;
999 }
1000 var r = new _Bigint();
1001 _copyTo(r);
1002 r._neg = !_neg;
1003 return r._toValidInt();
1004 }
1005
1006 int get sign {
1007 return (_used == 0) ? 0 : _neg ? -1 : 1;
1008 }
1009
1010 bool get isEven => _used == 0 || (_digits[0] & 1) == 0;
1011 bool get isNegative => _neg;
1012
1013 _leftShiftWithMask32(int count, int mask) {
1014 if (_used == 0) return 0;
1015 if (count is! _Smi) {
1016 _shlFromInt(count); // Throws out of memory exception.
1017 }
1018 assert(DIGIT_BITS == 32); // Otherwise this code needs to be revised.
1019 if (count > 31) return 0;
1020 return (_digits[0] << count) & mask;
1021 }
1022
1023 int _bitAndFromInteger(int other) {
1024 _Bigint result = new _Bigint();
1025 other._toBigint()._andTo(this, result);
1026 return result._toValidInt();
1027 }
1028 int _bitOrFromInteger(int other) {
1029 _Bigint result = new _Bigint();
1030 other._toBigint()._orTo(this, result);
1031 return result._toValidInt();
1032 }
1033 int _bitXorFromInteger(int other) {
1034 _Bigint result = new _Bigint();
1035 other._toBigint()._xorTo(this, result);
1036 return result._toValidInt();
1037 }
1038 int _addFromInteger(int other) {
1039 _Bigint result = new _Bigint();
1040 other._toBigint()._addTo(this, result);
1041 return result._toValidInt();
1042 }
1043 int _subFromInteger(int other) {
1044 _Bigint result = new _Bigint();
1045 other._toBigint()._subTo(this, result);
1046 return result._toValidInt();
1047 }
1048 int _mulFromInteger(int other) {
1049 _Bigint result = new _Bigint();
1050 other._toBigint()._mulTo(this, result);
1051 return result._toValidInt();
1052 }
1053 int _truncDivFromInteger(int other) {
1054 _Bigint result = new _Bigint();
1055 other._toBigint()._divRemTo(this, result, null);
1056 return result._toValidInt();
1057 }
1058 int _moduloFromInteger(int other) {
1059 _Bigint result = new _Bigint();
1060 var ob = other._toBigint();
1061 other._toBigint()._divRemTo(this, null, result);
1062 if (result._neg) {
1063 if (_neg) {
1064 result._subTo(this, result);
1065 } else {
1066 result._addTo(this, result);
1067 }
1068 }
1069 return result._toValidInt();
1070 }
1071 int _remainderFromInteger(int other) {
1072 _Bigint result = new _Bigint();
1073 other._toBigint()._divRemTo(this, null, result);
1074 return result._toValidInt();
1075 }
1076 bool _greaterThanFromInteger(int other) {
1077 return other._toBigint()._compareTo(this) > 0;
1078 }
1079 bool _equalToInteger(int other) {
1080 return other._toBigint()._compareTo(this) == 0;
1081 }
1082
1083 // New method to support crypto.
1084
1085 // Return this.pow(e) mod m, with 256 <= e < 1<<32.
1086 int modPow(int e, int m) {
1087 assert(e >= 256 && !m.isEven());
1088 if (e >= (1 << 32)) {
1089 throw "Bigint.modPow with exponent larger than 32-bit not implemented";
1090 }
1091 _Reduction z = new _Montgomery(m);
1092 var r = new _Bigint();
1093 var r2 = new _Bigint();
1094 var g = z.convert(this);
1095 int i = _nbits(e) - 1;
1096 g._copyTo(r);
1097 while (--i >= 0) {
1098 z.sqrTo(r, r2);
1099 if ((e & (1 << i)) > 0) {
1100 z.mulTo(r2, g, r);
1101 } else {
1102 var t = r;
1103 r = r2;
1104 r2 = t;
1105 }
1106 }
1107 return z.revert(r)._toValidInt();
1108 }
1109 }
1110
1111 // New classes to support crypto (modPow method).
1112
1113 class _Reduction {
1114 const _Reduction();
1115 _Bigint _convert(_Bigint x) => x;
1116 _Bigint _revert(_Bigint x) => x;
1117
1118 void _mulTo(_Bigint x, _Bigint y, _Bigint r) {
1119 x._mulTo(y, r);
1120 }
1121
1122 void _sqrTo(_Bigint x, _Bigint r) {
1123 x._sqrTo(r);
1124 }
1125 }
1126
1127 // Montgomery reduction on _Bigint.
1128 class _Montgomery implements _Reduction {
1129 final _Bigint _m;
1130 var _mp;
1131 var _mpl;
1132 var _mph;
1133 var _um;
1134 var _mused2;
1135
1136 _Montgomery(this._m) {
1137 _mp = _m._invDigit();
1138 _mpl = _mp & _Bigint.DIGIT2_MASK;
1139 _mph = _mp >> _Bigint.DIGIT2_BITS;
1140 _um = (1 << (_Bigint.DIGIT_BITS - _Bigint.DIGIT2_BITS)) - 1;
1141 _mused2 = 2*_m._used;
1142 }
1143
1144 // Return x*R mod _m
1145 _Bigint _convert(_Bigint x) {
1146 var r = new _Bigint();
1147 x.abs()._dlShiftTo(_m._used, r);
1148 r._divRemTo(_m, null, r);
1149 if (x._neg && !r._neg && r._used > 0) {
1150 _m._subTo(r, r);
1151 }
1152 return r;
1153 }
1154
1155 // Return x/R mod _m
1156 _Bigint _revert(_Bigint x) {
1157 var r = new _Bigint();
1158 x._copyTo(r);
1159 _reduce(r);
1160 return r;
1161 }
1162
1163 // x = x/R mod _m
1164 void _reduce(_Bigint x) {
1165 x._ensureLength(_mused2 + 1);
1166 while (x._used <= _mused2) { // Pad x so _am has enough room later.
1167 x._digits[x._used++] = 0;
1168 }
1169 for (var i = 0; i < _m._used; ++i) {
1170 // Faster way of calculating u0 = x[i]*mp mod DIGIT_BASE.
1171 var j = x._digits[i] & _Bigint.DIGIT2_MASK;
1172 var u0 = (j*_mpl + (((j*_mph + (x._digits[i] >> _Bigint.DIGIT2_BITS)
1173 *_mpl) & _um) << _Bigint.DIGIT2_BITS)) & _Bigint.DIGIT_MASK;
1174 // Use _am to combine the multiply-shift-add into one call.
1175 j = i + _m._used;
1176 var digit = x._digits[j];
1177 digit += _m ._am(0, u0, x, i, 0, _m ._used);
1178 // propagate carry
1179 while (digit >= _Bigint.DIGIT_BASE) {
1180 digit -= _Bigint.DIGIT_BASE;
1181 x._digits[j++] = digit;
1182 digit = x._digits[j];
1183 digit++;
1184 }
1185 x._digits[j] = digit;
1186 }
1187 x._clamp();
1188 x._drShiftTo(_m ._used, x);
1189 if (x._compareTo(_m ) >= 0) {
1190 x._subTo(_m , x);
1191 }
1192 }
1193
1194 // r = x^2/R mod _m ; x != r
1195 void _sqrTo(_Bigint x, _Bigint r) {
1196 x._sqrTo(r);
1197 _reduce(r);
1198 }
1199
1200 // r = x*y/R mod _m ; x, y != r
1201 void _mulTo(_Bigint x, _Bigint y, _Bigint r) {
1202 x._mulTo(y, r);
1203 _reduce(r);
1204 }
1205 }
1206
OLDNEW
« no previous file with comments | « runtime/lib/array.cc ('k') | runtime/lib/bool.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698