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

Side by Side Diff: pkg/fixnum/lib/src/int64.dart

Issue 23441004: More efficient Int64 parsing and printing. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 7 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 | « no previous file | pkg/fixnum/test/int_64_test.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 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. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 part of fixnum; 5 part of fixnum;
6 6
7 /** 7 /**
8 * An immutable 64-bit signed integer, in the range [-2^63, 2^63 - 1]. 8 * An immutable 64-bit signed integer, in the range [-2^63, 2^63 - 1].
9 * Arithmetic operations may overflow in order to maintain this range. 9 * Arithmetic operations may overflow in order to maintain this range.
10 */ 10 */
(...skipping 19 matching lines...) Expand all
30 static const int _SIGN_BIT = 19; // _BITS2 - 1 30 static const int _SIGN_BIT = 19; // _BITS2 - 1
31 static const int _SIGN_BIT_VALUE = 524288; // 1 << _SIGN_BIT 31 static const int _SIGN_BIT_VALUE = 524288; // 1 << _SIGN_BIT
32 32
33 // Cached constants 33 // Cached constants
34 static Int64 _MAX_VALUE; 34 static Int64 _MAX_VALUE;
35 static Int64 _MIN_VALUE; 35 static Int64 _MIN_VALUE;
36 static Int64 _ZERO; 36 static Int64 _ZERO;
37 static Int64 _ONE; 37 static Int64 _ONE;
38 static Int64 _TWO; 38 static Int64 _TWO;
39 39
40 // Precompute the radix strings for MIN_VALUE to avoid the problem
41 // of overflow of -MIN_VALUE.
42 static List<String> _minValues = const <String>[
43 null, null,
44 "-1000000000000000000000000000000000000000000000000000000000000000", // 2
45 "-2021110011022210012102010021220101220222", // base 3
46 "-20000000000000000000000000000000", // base 4
47 "-1104332401304422434310311213", // base 5
48 "-1540241003031030222122212", // base 6
49 "-22341010611245052052301", // base 7
50 "-1000000000000000000000", // base 8
51 "-67404283172107811828", // base 9
52 "-9223372036854775808", // base 10
53 "-1728002635214590698", // base 11
54 "-41A792678515120368", // base 12
55 "-10B269549075433C38", // base 13
56 "-4340724C6C71DC7A8", // base 14
57 "-160E2AD3246366808", // base 15
58 "-8000000000000000" // base 16
59 ];
60
61 // The remainder of the last divide operation. 40 // The remainder of the last divide operation.
62 static Int64 _remainder; 41 static Int64 _remainder;
63 42
64 /** 43 /**
65 * The maximum positive value attainable by an [Int64], namely 44 * The maximum positive value attainable by an [Int64], namely
66 * 9,223,372,036,854,775,807. 45 * 9,223,372,036,854,775,807.
67 */ 46 */
68 static Int64 get MAX_VALUE { 47 static Int64 get MAX_VALUE {
69 if (_MAX_VALUE == null) { 48 if (_MAX_VALUE == null) {
70 _MAX_VALUE = new Int64._bits(_MASK, _MASK, _MASK_2 >> 1); 49 _MAX_VALUE = new Int64._bits(_MASK, _MASK, _MASK_2 >> 1);
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
107 * An [Int64] constant equal to 2. 86 * An [Int64] constant equal to 2.
108 */ 87 */
109 static Int64 get TWO { 88 static Int64 get TWO {
110 if (_TWO == null) { 89 if (_TWO == null) {
111 _TWO = new Int64._bits(2, 0, 0); 90 _TWO = new Int64._bits(2, 0, 0);
112 } 91 }
113 return _TWO; 92 return _TWO;
114 } 93 }
115 94
116 /** 95 /**
117 * Parses a [String] in a given [radix] between 2 and 16 and returns an 96 * Parses a [String] in a given [radix] between 2 and 36 and returns an
118 * [Int64]. 97 * [Int64].
119 */ 98 */
120 // TODO(rice) - make this faster by converting several digits at once.
121 static Int64 parseRadix(String s, int radix) { 99 static Int64 parseRadix(String s, int radix) {
122 if ((radix <= 1) || (radix > 16)) { 100 if ((radix <= 1) || (radix > 36)) {
123 throw new ArgumentError("Bad radix: $radix"); 101 throw new ArgumentError("Bad radix: $radix");
124 } 102 }
125 Int64 x = ZERO; 103 return _parseRadix(s, radix);
104 }
105
106 static Int64 _parseRadix(String s, int radix) {
126 int i = 0; 107 int i = 0;
127 bool negative = false; 108 bool negative = false;
128 if (s[0] == '-') { 109 if (s[0] == '-') {
129 negative = true; 110 negative = true;
130 i++; 111 i++;
131 } 112 }
113 int d0 = 0, d1 = 0, d2 = 0; // low, middle, high components.
132 for (; i < s.length; i++) { 114 for (; i < s.length; i++) {
133 int c = s.codeUnitAt(i); 115 int c = s.codeUnitAt(i);
134 int digit = Int32._decodeHex(c); 116 int digit = Int32._decodeHex(c);
Chris Bracken 2013/08/27 21:36:02 Wasn't introduced by this CL, but might be a good
sra1 2013/08/27 22:26:22 Done.
135 if (digit < 0 || digit >= radix) { 117 if (digit < 0 || digit >= radix) {
136 throw new Exception("Non-radix char code: $c"); 118 throw new Exception("Non-radix char code: $c");
137 } 119 }
138 x = (x * radix) + digit; 120
121 // [radix] and [digit] are at most 6 bits, component is 22, so we can
122 // multiply and add within 30 bit temporary values.
123 d0 = d0 * radix + digit;
124 int carry = d0 >> _BITS;
125 d0 &= _MASK;
126
127 d1 = d1 * radix + carry;
128 carry = d1 >> _BITS;
129 d1 &= _MASK;
130
131 d2 = d2 * radix + carry;
132 d2 &= _MASK_2;
Chris Bracken 2013/08/27 21:36:02 Wasn't introduced by this CL, but might not be bad
sra1 2013/08/27 22:26:22 Done.
139 } 133 }
140 return negative ? -x : x; 134
135 if (negative) {
136 d0 = 0 - d0;
Chris Bracken 2013/08/27 21:36:02 Is there a reason for preferring the binary - to a
sra1 2013/08/27 22:26:22 It helps type inference since the receiver is a co
137 int borrow = (d0 >> _BITS) & 1;
Chris Bracken 2013/08/27 21:36:02 Is there any case in which d0 >> _BITS would be an
sra1 2013/08/27 22:26:22 There is a history of flip-flopping between >> ret
138 d0 &= _MASK;
139 d1 = 0 - d1 - borrow;
140 borrow = (d1 >> _BITS) & 1;
141 d1 &= _MASK;
142 d2 = 0 - d2 - borrow;
143 d2 &= _MASK_2;
144 }
145 return new Int64._bits(d0, d1, d2);
141 } 146 }
142 147
143 /** 148 /**
144 * Parses a decimal [String] and returns an [Int64]. 149 * Parses a decimal [String] and returns an [Int64].
145 */ 150 */
146 static Int64 parseInt(String s) => parseRadix(s, 10); 151 static Int64 parseInt(String s) => _parseRadix(s, 10);
147 152
148 /** 153 /**
149 * Parses a hexadecimal [String] and returns an [Int64]. 154 * Parses a hexadecimal [String] and returns an [Int64].
150 */ 155 */
151 static Int64 parseHex(String s) => parseRadix(s, 16); 156 static Int64 parseHex(String s) => _parseRadix(s, 16);
152 157
153 // 158 //
154 // Public constructors 159 // Public constructors
155 // 160 //
156 161
157 /** 162 /**
158 * Constructs an [Int64] equal to 0. 163 * Constructs an [Int64] equal to 0.
159 */ 164 */
160 Int64() : _l = 0, _m = 0, _h = 0; 165 Int64() : _l = 0, _m = 0, _h = 0;
161 166
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
225 bottom <<= 8; 230 bottom <<= 8;
226 bottom |= bytes[7] & 0xff; 231 bottom |= bytes[7] & 0xff;
227 232
228 return new Int64.fromInts(top, bottom); 233 return new Int64.fromInts(top, bottom);
229 } 234 }
230 235
231 /** 236 /**
232 * Constructs an [Int64] from a pair of 32-bit integers having the value 237 * Constructs an [Int64] from a pair of 32-bit integers having the value
233 * [:((top & 0xffffffff) << 32) | (bottom & 0xffffffff):]. 238 * [:((top & 0xffffffff) << 32) | (bottom & 0xffffffff):].
234 */ 239 */
235 Int64.fromInts(int top, int bottom) { 240 factory Int64.fromInts(int top, int bottom) {
236 top &= 0xffffffff; 241 top &= 0xffffffff;
237 bottom &= 0xffffffff; 242 bottom &= 0xffffffff;
238 _l = bottom & _MASK; 243 int d0 = bottom & _MASK;
239 _m = ((top & 0xfff) << 10) | ((bottom >> _BITS) & 0x3ff); 244 int d1 = ((top & 0xfff) << 10) | ((bottom >> _BITS) & 0x3ff);
240 _h = (top >> 12) & _MASK_2; 245 int d2 = (top >> 12) & _MASK_2;
246 return new Int64._bits(d0, d1, d2);
241 } 247 }
242 248
243 // Returns the [Int64] representation of the specified value. Throws 249 // Returns the [Int64] representation of the specified value. Throws
244 // [ArgumentError] for non-integer arguments. 250 // [ArgumentError] for non-integer arguments.
245 Int64 _promote(val) { 251 Int64 _promote(val) {
246 if (val is Int64) { 252 if (val is Int64) {
247 return val; 253 return val;
248 } else if (val is int) { 254 } else if (val is int) {
249 return new Int64.fromInt(val); 255 return new Int64.fromInt(val);
250 } else if (val is Int32) { 256 } else if (val is Int32) {
(...skipping 421 matching lines...) Expand 10 before | Expand all | Expand 10 after
672 } 678 }
673 679
674 /** 680 /**
675 * Returns [this]. 681 * Returns [this].
676 */ 682 */
677 Int64 toInt64() => this; 683 Int64 toInt64() => this;
678 684
679 /** 685 /**
680 * Returns the value of this [Int64] as a decimal [String]. 686 * Returns the value of this [Int64] as a decimal [String].
681 */ 687 */
682 // TODO(rice) - Make this faster by converting several digits at once. 688 String toString() => _toRadixString(10);
683 String toString() {
684 Int64 a = this;
685 if (a.isZero) {
686 return "0";
687 }
688 if (a.isMinValue) {
689 return "-9223372036854775808";
690 }
691
692 String result = "";
693 bool negative = false;
694 if (a.isNegative) {
695 negative = true;
696 a = -a;
697 }
698
699 Int64 ten = new Int64._bits(10, 0, 0);
700 while (!a.isZero) {
701 a = _divMod(a, ten, true);
702 result = "${_remainder._l}$result";
703 }
704 if (negative) {
705 result = "-$result";
706 }
707 return result;
708 }
709 689
710 // TODO(rice) - Make this faster by avoiding arithmetic. 690 // TODO(rice) - Make this faster by avoiding arithmetic.
711 String toHexString() { 691 String toHexString() {
712 Int64 x = new Int64._copy(this); 692 Int64 x = new Int64._copy(this);
713 if (isZero) { 693 if (isZero) {
714 return "0"; 694 return "0";
715 } 695 }
716 String hexStr = ""; 696 String hexStr = "";
717 Int64 digit_f = new Int64.fromInt(0xf); 697 Int64 digit_f = new Int64.fromInt(0xf);
718 while (!x.isZero) { 698 while (!x.isZero) {
719 int digit = x._l & 0xf; 699 int digit = x._l & 0xf;
720 hexStr = "${_hexDigit(digit)}$hexStr"; 700 hexStr = "${_hexDigit(digit)}$hexStr";
721 x = x.shiftRightUnsigned(4); 701 x = x.shiftRightUnsigned(4);
722 } 702 }
723 return hexStr; 703 return hexStr;
724 } 704 }
725 705
726 String toRadixString(int radix) { 706 String toRadixString(int radix) {
727 if ((radix <= 1) || (radix > 16)) { 707 if ((radix <= 1) || (radix > 36)) {
728 throw new ArgumentError("Bad radix: $radix"); 708 throw new ArgumentError("Bad radix: $radix");
729 } 709 }
730 Int64 a = this; 710 return _toRadixString(radix);
731 if (a.isZero) { 711 }
732 return "0"; 712
733 } 713 String _toRadixString(int radix) {
734 if (a.isMinValue) { 714 int d0 = _l;
735 return _minValues[radix]; 715 int d1 = _m;
716 int d2 = _h;
717
718 if (d0 == 0 && d1 == 0 && d2 == 0) return '0';
719
720 String sign = '';
721 if ((d2 & _SIGN_BIT_VALUE) != 0) {
722 sign = '-';
723
724 // Negate in-place.
725 d0 = 0 - d0;
726 int borrow = (d0 >> _BITS) & 1;
727 d0 &= _MASK;
728 d1 = 0 - d1 - borrow;
729 borrow = (d1 >> _BITS) & 1;
730 d1 &= _MASK;
731 d2 = 0 - d2 - borrow;
732 d2 &= _MASK_2;
733 // d2, d1, d0 now are an unsigned 64 bit integer for MIN_VALUE and an
734 // unsigned 63 bit integer for other values.
736 } 735 }
737 736
738 String result = ""; 737 // Rearrange components into five components where all but the most
739 bool negative = false; 738 // significant are 10 bits wide.
740 if (a.isNegative) { 739 //
741 negative = true; 740 // d4, d3, d4, d1, d0: 24 + 10 + 10 + 10 + 10 bits
742 a = -a; 741 //
742 // The choice of 10 bits allows a remainder of 20 bits to be scaled by 10
743 // bits and added during division while keeping all intermediate values
744 // within 30 bits (unsigned small integer range for 32 bit implementations
745 // of Dart VM and V8).
746
747 // Which of these diagrams works best?
748
749
750 // 2222222222222222222211111111111111111111110000000000000000000000
751 // -->
752 // 4444444444444444444444443333333333222222222211111111110000000000
753
754
755 // 22222222222222222222
756 // 1111111111111111111111
757 // 0000000000000000000000
758 // -->
759 // 444444444444444444444444
760 // 3333333333
761 // 2222222222
762 // 1111111111
763 // 0000000000
764
765 // 22222222222222222222 0000000000000000000000
766 // 1111111111111111111111
767 // -->
768 // 444444444444444444444444 2222222222 0000000000
769 // 3333333333 1111111111
770
771 // 6 6 5 4 3 2 1
772 // 3210987654321098765432109876543210987654321098765432109876543210
773 // [--------d2--------][---------d1---------][---------d0---------]
774 // -->
775 // [----------d4----------][---d3---][---d2---][---d1---][---d0---]
Chris Bracken 2013/08/27 21:36:02 Personal favourite. Second place goes to the one a
776
777
778 int d4 = (d2 << 4) | (d1 >> 18);
779 int d3 = (d1 >> 8) & 0x3ff;
780 d2 = ((d1 << 2) | (d0 >> 20)) & 0x3ff;
781 d1 = (d0 >> 10) & 0x3ff;
782 d0 = d0 & 0x3ff;
Chris Bracken 2013/08/27 21:36:02 It's pretty clear to from the comment above that 0
sra1 2013/08/27 22:26:22 I'm find the value of named constants dubious when
783
784 int fatRadix = _fatRadixTable[radix];
785
786 // Generate chunks of digits. In radix 10, generate 6 digits per chunk.
787 //
788 // This loop generates at most 3 chunks, so we store the chunks in locals
789 // rather than a list. We are trying to generate digits 20 bits at a time
790 // until we have only 30 bits left. 20 + 20 + 30 > 64 would imply that we
791 // need only two chunks, but radix values 17-19 and 33-36 generate only 15
792 // or 16 bits per iteration, so sometime the third chunk is needed.
793
794 String chunk1 = "", chunk2 = "", chunk3 = "";
795
796 while (!(d4 == 0 && d3 == 0)) {
Chris Bracken 2013/08/27 21:36:02 (d4 != 0 || d3 != 0) saves an operation, though th
797 int q = d4 ~/ fatRadix;
798 int r = d4 - q * fatRadix;
Chris Bracken 2013/08/27 21:36:02 Is this more efficient than that modulo operator?
sra1 2013/08/27 22:26:22 I don't know. It really depends if the JS or VM j
799 d4 = q;
800 d3 += r * 1024;
Chris Bracken 2013/08/27 21:36:02 d3 += r << 10 might be more indicative of the gene
sra1 2013/08/27 22:26:22 Done.
801
802 q = d3 ~/ fatRadix;
803 r = d3 - q * fatRadix;
804 d3 = q;
805 d2 += r * 1024;
806
807 q = d2 ~/ fatRadix;
808 r = d2 - q * fatRadix;
809 d2 = q;
810 d1 += r * 1024;
811
812 q = d1 ~/ fatRadix;
813 r = d1 - q * fatRadix;
814 d1 = q;
815 d0 += r * 1024;
816
817 q = d0 ~/ fatRadix;
818 r = d0 - q * fatRadix;
819 d0 = q;
820
821 assert(chunk2 == "");
822 chunk3 = chunk2;
823 chunk2 = chunk1;
824 // Adding [fatRadix] Forces an extra digit which we discard to get a fixed
825 // width. E.g. (1000000 + 123) -> "1000123" -> "000123". An alternative
826 // would be to pad to the left with zeroes.
827 chunk1 = (fatRadix + r).toRadixString(radix).substring(1);
743 } 828 }
829 int residue = 1024 * 1024 * d2 + 1024 * d1 + d0;
830 String leadingDigits = residue == 0 ? '' : residue.toRadixString(radix);
831 return '$sign$leadingDigits$chunk1$chunk2$chunk3';
832 }
744 833
745 Int64 r = new Int64._bits(radix, 0, 0); 834 // Table of 'fat' radix values. Each entry for index `i` is the largest power
746 while (!a.isZero) { 835 // of `i` whose remainder fits in 20 bits.
747 a = _divMod(a, r, true); 836 static final _fatRadixTable = const <int>[
748 result = "${_hexDigit(_remainder._l)}$result"; 837 0,
749 } 838 0,
750 return negative ? "-$result" : result; 839 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
751 } 840 * 2,
841 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3,
842 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4,
843 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
844 6 * 6 * 6 * 6 * 6 * 6 * 6,
845 7 * 7 * 7 * 7 * 7 * 7 * 7,
846 8 * 8 * 8 * 8 * 8 * 8,
847 9 * 9 * 9 * 9 * 9 * 9,
848 10 * 10 * 10 * 10 * 10 * 10,
849 11 * 11 * 11 * 11 * 11,
850 12 * 12 * 12 * 12 * 12,
851 13 * 13 * 13 * 13 * 13,
852 14 * 14 * 14 * 14 * 14,
853 15 * 15 * 15 * 15 * 15,
854 16 * 16 * 16 * 16 * 16,
855 17 * 17 * 17 * 17,
856 18 * 18 * 18 * 18,
857 19 * 19 * 19 * 19,
858 20 * 20 * 20 * 20,
859 21 * 21 * 21 * 21,
860 22 * 22 * 22 * 22,
861 23 * 23 * 23 * 23,
862 24 * 24 * 24 * 24,
863 25 * 25 * 25 * 25,
864 26 * 26 * 26 * 26,
865 27 * 27 * 27 * 27,
866 28 * 28 * 28 * 28,
867 29 * 29 * 29 * 29,
868 30 * 30 * 30 * 30,
869 31 * 31 * 31 * 31,
870 32 * 32 * 32 * 32,
871 33 * 33 * 33,
872 34 * 34 * 34,
873 35 * 35 * 35,
874 36 * 36 * 36
875 ];
752 876
753 String toDebugString() { 877 String toDebugString() {
754 return "Int64[_l=$_l, _m=$_m, _h=$_h]"; 878 return "Int64[_l=$_l, _m=$_m, _h=$_h]";
755 } 879 }
756 880
757 /** 881 /**
758 * Constructs an [Int64] with a given bitwise representation. No validation 882 * Constructs an [Int64] with a given bitwise representation. No validation
759 * is performed. 883 * is performed.
760 */ 884 */
761 Int64._bits(int this._l, int this._m, int this._h); 885 Int64._bits(int this._l, int this._m, int this._h);
762 886
763 /** 887 /**
764 * Constructs an [Int64] with the same value as an existing [Int64]. 888 * Constructs an [Int64] with the same value as an existing [Int64].
765 */ 889 */
766 Int64._copy(Int64 other) { 890 Int64._copy(Int64 other)
767 _l = other._l; 891 : _l = other._l,
768 _m = other._m; 892 _m = other._m,
769 _h = other._h; 893 _h = other._h;
770 }
771 894
772 // Determine whether the platform supports ints greater than 2^53 895 // Determine whether the platform supports ints greater than 2^53
773 // without loss of precision. 896 // without loss of precision.
774 static bool _haveBigIntsCached = null; 897 static bool _haveBigIntsCached = null;
775 898
776 static bool get _haveBigInts { 899 static bool get _haveBigInts {
777 if (_haveBigIntsCached == null) { 900 if (_haveBigIntsCached == null) {
778 var x = 9007199254740992; 901 var x = 9007199254740992;
779 // Defeat compile-time constant folding. 902 // Defeat compile-time constant folding.
780 if (2 + 2 != 4) { 903 if (2 + 2 != 4) {
(...skipping 313 matching lines...) Expand 10 before | Expand all | Expand 10 after
1094 } 1217 }
1095 } 1218 }
1096 return ZERO; 1219 return ZERO;
1097 } 1220 }
1098 1221
1099 // Generate the quotient using bit-at-a-time long division. 1222 // Generate the quotient using bit-at-a-time long division.
1100 return _divModHelper(aIsCopy ? a : new Int64._copy(a), b, negative, 1223 return _divModHelper(aIsCopy ? a : new Int64._copy(a), b, negative,
1101 aIsNegative, aIsMinValue, computeRemainder); 1224 aIsNegative, aIsMinValue, computeRemainder);
1102 } 1225 }
1103 } 1226 }
OLDNEW
« no previous file with comments | « no previous file | pkg/fixnum/test/int_64_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698