long.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. // Copyright 2009 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Defines a Long class for representing a 64-bit two's-complement
  16. * integer value, which faithfully simulates the behavior of a Java "long". This
  17. * implementation is derived from LongLib in GWT.
  18. *
  19. */
  20. goog.provide('goog.math.Long');
  21. goog.require('goog.asserts');
  22. goog.require('goog.reflect');
  23. /**
  24. * Constructs a 64-bit two's-complement integer, given its low and high 32-bit
  25. * values as *signed* integers. See the from* functions below for more
  26. * convenient ways of constructing Longs.
  27. *
  28. * The internal representation of a long is the two given signed, 32-bit values.
  29. * We use 32-bit pieces because these are the size of integers on which
  30. * Javascript performs bit-operations. For operations like addition and
  31. * multiplication, we split each number into 16-bit pieces, which can easily be
  32. * multiplied within Javascript's floating-point representation without overflow
  33. * or change in sign.
  34. *
  35. * In the algorithms below, we frequently reduce the negative case to the
  36. * positive case by negating the input(s) and then post-processing the result.
  37. * Note that we must ALWAYS check specially whether those values are MIN_VALUE
  38. * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
  39. * a positive number, it overflows back into a negative). Not handling this
  40. * case would often result in infinite recursion.
  41. *
  42. * @param {number} low The low (signed) 32 bits of the long.
  43. * @param {number} high The high (signed) 32 bits of the long.
  44. * @struct
  45. * @constructor
  46. * @final
  47. */
  48. goog.math.Long = function(low, high) {
  49. /**
  50. * @type {number}
  51. * @private
  52. */
  53. this.low_ = low | 0; // force into 32 signed bits.
  54. /**
  55. * @type {number}
  56. * @private
  57. */
  58. this.high_ = high | 0; // force into 32 signed bits.
  59. };
  60. // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
  61. // from* methods on which they depend.
  62. /**
  63. * A cache of the Long representations of small integer values.
  64. * @type {!Object<number, !goog.math.Long>}
  65. * @private
  66. */
  67. goog.math.Long.IntCache_ = {};
  68. /**
  69. * A cache of the Long representations of common values.
  70. * @type {!Object<goog.math.Long.ValueCacheId_, !goog.math.Long>}
  71. * @private
  72. */
  73. goog.math.Long.valueCache_ = {};
  74. /**
  75. * Returns a cached long number representing the given (32-bit) integer value.
  76. * @param {number} value The 32-bit integer in question.
  77. * @return {!goog.math.Long} The corresponding Long value.
  78. * @private
  79. */
  80. goog.math.Long.getCachedIntValue_ = function(value) {
  81. return goog.reflect.cache(goog.math.Long.IntCache_, value, function(val) {
  82. return new goog.math.Long(val, val < 0 ? -1 : 0);
  83. });
  84. };
  85. /**
  86. * The array of maximum values of a Long in string representation for a given
  87. * radix between 2 and 36, inclusive.
  88. * @private @const {!Array<string>}
  89. */
  90. goog.math.Long.MAX_VALUE_FOR_RADIX_ = [
  91. '', '', // unused
  92. '111111111111111111111111111111111111111111111111111111111111111',
  93. // base 2
  94. '2021110011022210012102010021220101220221', // base 3
  95. '13333333333333333333333333333333', // base 4
  96. '1104332401304422434310311212', // base 5
  97. '1540241003031030222122211', // base 6
  98. '22341010611245052052300', // base 7
  99. '777777777777777777777', // base 8
  100. '67404283172107811827', // base 9
  101. '9223372036854775807', // base 10
  102. '1728002635214590697', // base 11
  103. '41a792678515120367', // base 12
  104. '10b269549075433c37', // base 13
  105. '4340724c6c71dc7a7', // base 14
  106. '160e2ad3246366807', // base 15
  107. '7fffffffffffffff', // base 16
  108. '33d3d8307b214008', // base 17
  109. '16agh595df825fa7', // base 18
  110. 'ba643dci0ffeehh', // base 19
  111. '5cbfjia3fh26ja7', // base 20
  112. '2heiciiie82dh97', // base 21
  113. '1adaibb21dckfa7', // base 22
  114. 'i6k448cf4192c2', // base 23
  115. 'acd772jnc9l0l7', // base 24
  116. '64ie1focnn5g77', // base 25
  117. '3igoecjbmca687', // base 26
  118. '27c48l5b37oaop', // base 27
  119. '1bk39f3ah3dmq7', // base 28
  120. 'q1se8f0m04isb', // base 29
  121. 'hajppbc1fc207', // base 30
  122. 'bm03i95hia437', // base 31
  123. '7vvvvvvvvvvvv', // base 32
  124. '5hg4ck9jd4u37', // base 33
  125. '3tdtk1v8j6tpp', // base 34
  126. '2pijmikexrxp7', // base 35
  127. '1y2p0ij32e8e7' // base 36
  128. ];
  129. /**
  130. * The array of minimum values of a Long in string representation for a given
  131. * radix between 2 and 36, inclusive.
  132. * @private @const {!Array<string>}
  133. */
  134. goog.math.Long.MIN_VALUE_FOR_RADIX_ = [
  135. '', '', // unused
  136. '-1000000000000000000000000000000000000000000000000000000000000000',
  137. // base 2
  138. '-2021110011022210012102010021220101220222', // base 3
  139. '-20000000000000000000000000000000', // base 4
  140. '-1104332401304422434310311213', // base 5
  141. '-1540241003031030222122212', // base 6
  142. '-22341010611245052052301', // base 7
  143. '-1000000000000000000000', // base 8
  144. '-67404283172107811828', // base 9
  145. '-9223372036854775808', // base 10
  146. '-1728002635214590698', // base 11
  147. '-41a792678515120368', // base 12
  148. '-10b269549075433c38', // base 13
  149. '-4340724c6c71dc7a8', // base 14
  150. '-160e2ad3246366808', // base 15
  151. '-8000000000000000', // base 16
  152. '-33d3d8307b214009', // base 17
  153. '-16agh595df825fa8', // base 18
  154. '-ba643dci0ffeehi', // base 19
  155. '-5cbfjia3fh26ja8', // base 20
  156. '-2heiciiie82dh98', // base 21
  157. '-1adaibb21dckfa8', // base 22
  158. '-i6k448cf4192c3', // base 23
  159. '-acd772jnc9l0l8', // base 24
  160. '-64ie1focnn5g78', // base 25
  161. '-3igoecjbmca688', // base 26
  162. '-27c48l5b37oaoq', // base 27
  163. '-1bk39f3ah3dmq8', // base 28
  164. '-q1se8f0m04isc', // base 29
  165. '-hajppbc1fc208', // base 30
  166. '-bm03i95hia438', // base 31
  167. '-8000000000000', // base 32
  168. '-5hg4ck9jd4u38', // base 33
  169. '-3tdtk1v8j6tpq', // base 34
  170. '-2pijmikexrxp8', // base 35
  171. '-1y2p0ij32e8e8' // base 36
  172. ];
  173. /**
  174. * Returns a Long representing the given (32-bit) integer value.
  175. * @param {number} value The 32-bit integer in question.
  176. * @return {!goog.math.Long} The corresponding Long value.
  177. */
  178. goog.math.Long.fromInt = function(value) {
  179. var intValue = value | 0;
  180. goog.asserts.assert(value === intValue, 'value should be a 32-bit integer');
  181. if (-128 <= intValue && intValue < 128) {
  182. return goog.math.Long.getCachedIntValue_(intValue);
  183. } else {
  184. return new goog.math.Long(intValue, intValue < 0 ? -1 : 0);
  185. }
  186. };
  187. /**
  188. * Returns a Long representing the given value.
  189. * NaN will be returned as zero. Infinity is converted to max value and
  190. * -Infinity to min value.
  191. * @param {number} value The number in question.
  192. * @return {!goog.math.Long} The corresponding Long value.
  193. */
  194. goog.math.Long.fromNumber = function(value) {
  195. if (isNaN(value)) {
  196. return goog.math.Long.getZero();
  197. } else if (value <= -goog.math.Long.TWO_PWR_63_DBL_) {
  198. return goog.math.Long.getMinValue();
  199. } else if (value + 1 >= goog.math.Long.TWO_PWR_63_DBL_) {
  200. return goog.math.Long.getMaxValue();
  201. } else if (value < 0) {
  202. return goog.math.Long.fromNumber(-value).negate();
  203. } else {
  204. return new goog.math.Long(
  205. (value % goog.math.Long.TWO_PWR_32_DBL_) | 0,
  206. (value / goog.math.Long.TWO_PWR_32_DBL_) | 0);
  207. }
  208. };
  209. /**
  210. * Returns a Long representing the 64-bit integer that comes by concatenating
  211. * the given high and low bits. Each is assumed to use 32 bits.
  212. * @param {number} lowBits The low 32-bits.
  213. * @param {number} highBits The high 32-bits.
  214. * @return {!goog.math.Long} The corresponding Long value.
  215. */
  216. goog.math.Long.fromBits = function(lowBits, highBits) {
  217. return new goog.math.Long(lowBits, highBits);
  218. };
  219. /**
  220. * Returns a Long representation of the given string, written using the given
  221. * radix.
  222. * @param {string} str The textual representation of the Long.
  223. * @param {number=} opt_radix The radix in which the text is written.
  224. * @return {!goog.math.Long} The corresponding Long value.
  225. */
  226. goog.math.Long.fromString = function(str, opt_radix) {
  227. if (str.length == 0) {
  228. throw Error('number format error: empty string');
  229. }
  230. var radix = opt_radix || 10;
  231. if (radix < 2 || 36 < radix) {
  232. throw Error('radix out of range: ' + radix);
  233. }
  234. if (str.charAt(0) == '-') {
  235. return goog.math.Long.fromString(str.substring(1), radix).negate();
  236. } else if (str.indexOf('-') >= 0) {
  237. throw Error('number format error: interior "-" character: ' + str);
  238. }
  239. // Do several (8) digits each time through the loop, so as to
  240. // minimize the calls to the very expensive emulated div.
  241. var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 8));
  242. var result = goog.math.Long.getZero();
  243. for (var i = 0; i < str.length; i += 8) {
  244. var size = Math.min(8, str.length - i);
  245. var value = parseInt(str.substring(i, i + size), radix);
  246. if (size < 8) {
  247. var power = goog.math.Long.fromNumber(Math.pow(radix, size));
  248. result = result.multiply(power).add(goog.math.Long.fromNumber(value));
  249. } else {
  250. result = result.multiply(radixToPower);
  251. result = result.add(goog.math.Long.fromNumber(value));
  252. }
  253. }
  254. return result;
  255. };
  256. /**
  257. * Returns the boolean value of whether the input string is within a Long's
  258. * range. Assumes an input string containing only numeric characters with an
  259. * optional preceding '-'.
  260. * @param {string} str The textual representation of the Long.
  261. * @param {number=} opt_radix The radix in which the text is written.
  262. * @return {boolean} Whether the string is within the range of a Long.
  263. */
  264. goog.math.Long.isStringInRange = function(str, opt_radix) {
  265. var radix = opt_radix || 10;
  266. if (radix < 2 || 36 < radix) {
  267. throw Error('radix out of range: ' + radix);
  268. }
  269. var extremeValue = (str.charAt(0) == '-') ?
  270. goog.math.Long.MIN_VALUE_FOR_RADIX_[radix] :
  271. goog.math.Long.MAX_VALUE_FOR_RADIX_[radix];
  272. if (str.length < extremeValue.length) {
  273. return true;
  274. } else if (str.length == extremeValue.length && str <= extremeValue) {
  275. return true;
  276. } else {
  277. return false;
  278. }
  279. };
  280. // NOTE: the compiler should inline these constant values below and then remove
  281. // these variables, so there should be no runtime penalty for these.
  282. /**
  283. * Number used repeated below in calculations. This must appear before the
  284. * first call to any from* function below.
  285. * @type {number}
  286. * @private
  287. */
  288. goog.math.Long.TWO_PWR_16_DBL_ = 1 << 16;
  289. /**
  290. * @type {number}
  291. * @private
  292. */
  293. goog.math.Long.TWO_PWR_32_DBL_ =
  294. goog.math.Long.TWO_PWR_16_DBL_ * goog.math.Long.TWO_PWR_16_DBL_;
  295. /**
  296. * @type {number}
  297. * @private
  298. */
  299. goog.math.Long.TWO_PWR_64_DBL_ =
  300. goog.math.Long.TWO_PWR_32_DBL_ * goog.math.Long.TWO_PWR_32_DBL_;
  301. /**
  302. * @type {number}
  303. * @private
  304. */
  305. goog.math.Long.TWO_PWR_63_DBL_ = goog.math.Long.TWO_PWR_64_DBL_ / 2;
  306. /**
  307. * @return {!goog.math.Long}
  308. * @public
  309. */
  310. goog.math.Long.getZero = function() {
  311. return goog.math.Long.getCachedIntValue_(0);
  312. };
  313. /**
  314. * @return {!goog.math.Long}
  315. * @public
  316. */
  317. goog.math.Long.getOne = function() {
  318. return goog.math.Long.getCachedIntValue_(1);
  319. };
  320. /**
  321. * @return {!goog.math.Long}
  322. * @public
  323. */
  324. goog.math.Long.getNegOne = function() {
  325. return goog.math.Long.getCachedIntValue_(-1);
  326. };
  327. /**
  328. * @return {!goog.math.Long}
  329. * @public
  330. */
  331. goog.math.Long.getMaxValue = function() {
  332. return goog.reflect.cache(
  333. goog.math.Long.valueCache_, goog.math.Long.ValueCacheId_.MAX_VALUE,
  334. function() {
  335. return goog.math.Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
  336. });
  337. };
  338. /**
  339. * @return {!goog.math.Long}
  340. * @public
  341. */
  342. goog.math.Long.getMinValue = function() {
  343. return goog.reflect.cache(
  344. goog.math.Long.valueCache_, goog.math.Long.ValueCacheId_.MIN_VALUE,
  345. function() { return goog.math.Long.fromBits(0, 0x80000000 | 0); });
  346. };
  347. /**
  348. * @return {!goog.math.Long}
  349. * @public
  350. */
  351. goog.math.Long.getTwoPwr24 = function() {
  352. return goog.reflect.cache(
  353. goog.math.Long.valueCache_, goog.math.Long.ValueCacheId_.TWO_PWR_24,
  354. function() { return goog.math.Long.fromInt(1 << 24); });
  355. };
  356. /** @return {number} The value, assuming it is a 32-bit integer. */
  357. goog.math.Long.prototype.toInt = function() {
  358. return this.low_;
  359. };
  360. /** @return {number} The closest floating-point representation to this value. */
  361. goog.math.Long.prototype.toNumber = function() {
  362. return this.high_ * goog.math.Long.TWO_PWR_32_DBL_ +
  363. this.getLowBitsUnsigned();
  364. };
  365. /**
  366. * @param {number=} opt_radix The radix in which the text should be written.
  367. * @return {string} The textual representation of this value.
  368. * @override
  369. */
  370. goog.math.Long.prototype.toString = function(opt_radix) {
  371. var radix = opt_radix || 10;
  372. if (radix < 2 || 36 < radix) {
  373. throw Error('radix out of range: ' + radix);
  374. }
  375. if (this.isZero()) {
  376. return '0';
  377. }
  378. if (this.isNegative()) {
  379. if (this.equals(goog.math.Long.getMinValue())) {
  380. // We need to change the Long value before it can be negated, so we remove
  381. // the bottom-most digit in this base and then recurse to do the rest.
  382. var radixLong = goog.math.Long.fromNumber(radix);
  383. var div = this.div(radixLong);
  384. var rem = div.multiply(radixLong).subtract(this);
  385. return div.toString(radix) + rem.toInt().toString(radix);
  386. } else {
  387. return '-' + this.negate().toString(radix);
  388. }
  389. }
  390. // Do several (6) digits each time through the loop, so as to
  391. // minimize the calls to the very expensive emulated div.
  392. var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 6));
  393. var rem = this;
  394. var result = '';
  395. while (true) {
  396. var remDiv = rem.div(radixToPower);
  397. // The right shifting fixes negative values in the case when
  398. // intval >= 2^31; for more details see
  399. // https://github.com/google/closure-library/pull/498
  400. var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;
  401. var digits = intval.toString(radix);
  402. rem = remDiv;
  403. if (rem.isZero()) {
  404. return digits + result;
  405. } else {
  406. while (digits.length < 6) {
  407. digits = '0' + digits;
  408. }
  409. result = '' + digits + result;
  410. }
  411. }
  412. };
  413. /** @return {number} The high 32-bits as a signed value. */
  414. goog.math.Long.prototype.getHighBits = function() {
  415. return this.high_;
  416. };
  417. /** @return {number} The low 32-bits as a signed value. */
  418. goog.math.Long.prototype.getLowBits = function() {
  419. return this.low_;
  420. };
  421. /** @return {number} The low 32-bits as an unsigned value. */
  422. goog.math.Long.prototype.getLowBitsUnsigned = function() {
  423. return (this.low_ >= 0) ? this.low_ :
  424. goog.math.Long.TWO_PWR_32_DBL_ + this.low_;
  425. };
  426. /**
  427. * @return {number} Returns the number of bits needed to represent the absolute
  428. * value of this Long.
  429. */
  430. goog.math.Long.prototype.getNumBitsAbs = function() {
  431. if (this.isNegative()) {
  432. if (this.equals(goog.math.Long.getMinValue())) {
  433. return 64;
  434. } else {
  435. return this.negate().getNumBitsAbs();
  436. }
  437. } else {
  438. var val = this.high_ != 0 ? this.high_ : this.low_;
  439. for (var bit = 31; bit > 0; bit--) {
  440. if ((val & (1 << bit)) != 0) {
  441. break;
  442. }
  443. }
  444. return this.high_ != 0 ? bit + 33 : bit + 1;
  445. }
  446. };
  447. /** @return {boolean} Whether this value is zero. */
  448. goog.math.Long.prototype.isZero = function() {
  449. return this.high_ == 0 && this.low_ == 0;
  450. };
  451. /** @return {boolean} Whether this value is negative. */
  452. goog.math.Long.prototype.isNegative = function() {
  453. return this.high_ < 0;
  454. };
  455. /** @return {boolean} Whether this value is odd. */
  456. goog.math.Long.prototype.isOdd = function() {
  457. return (this.low_ & 1) == 1;
  458. };
  459. /**
  460. * @param {goog.math.Long} other Long to compare against.
  461. * @return {boolean} Whether this Long equals the other.
  462. */
  463. goog.math.Long.prototype.equals = function(other) {
  464. return (this.high_ == other.high_) && (this.low_ == other.low_);
  465. };
  466. /**
  467. * @param {goog.math.Long} other Long to compare against.
  468. * @return {boolean} Whether this Long does not equal the other.
  469. */
  470. goog.math.Long.prototype.notEquals = function(other) {
  471. return (this.high_ != other.high_) || (this.low_ != other.low_);
  472. };
  473. /**
  474. * @param {goog.math.Long} other Long to compare against.
  475. * @return {boolean} Whether this Long is less than the other.
  476. */
  477. goog.math.Long.prototype.lessThan = function(other) {
  478. return this.compare(other) < 0;
  479. };
  480. /**
  481. * @param {goog.math.Long} other Long to compare against.
  482. * @return {boolean} Whether this Long is less than or equal to the other.
  483. */
  484. goog.math.Long.prototype.lessThanOrEqual = function(other) {
  485. return this.compare(other) <= 0;
  486. };
  487. /**
  488. * @param {goog.math.Long} other Long to compare against.
  489. * @return {boolean} Whether this Long is greater than the other.
  490. */
  491. goog.math.Long.prototype.greaterThan = function(other) {
  492. return this.compare(other) > 0;
  493. };
  494. /**
  495. * @param {goog.math.Long} other Long to compare against.
  496. * @return {boolean} Whether this Long is greater than or equal to the other.
  497. */
  498. goog.math.Long.prototype.greaterThanOrEqual = function(other) {
  499. return this.compare(other) >= 0;
  500. };
  501. /**
  502. * Compares this Long with the given one.
  503. * @param {goog.math.Long} other Long to compare against.
  504. * @return {number} 0 if they are the same, 1 if the this is greater, and -1
  505. * if the given one is greater.
  506. */
  507. goog.math.Long.prototype.compare = function(other) {
  508. if (this.equals(other)) {
  509. return 0;
  510. }
  511. var thisNeg = this.isNegative();
  512. var otherNeg = other.isNegative();
  513. if (thisNeg && !otherNeg) {
  514. return -1;
  515. }
  516. if (!thisNeg && otherNeg) {
  517. return 1;
  518. }
  519. // at this point, the signs are the same, so subtraction will not overflow
  520. if (this.subtract(other).isNegative()) {
  521. return -1;
  522. } else {
  523. return 1;
  524. }
  525. };
  526. /** @return {!goog.math.Long} The negation of this value. */
  527. goog.math.Long.prototype.negate = function() {
  528. if (this.equals(goog.math.Long.getMinValue())) {
  529. return goog.math.Long.getMinValue();
  530. } else {
  531. return this.not().add(goog.math.Long.getOne());
  532. }
  533. };
  534. /**
  535. * Returns the sum of this and the given Long.
  536. * @param {goog.math.Long} other Long to add to this one.
  537. * @return {!goog.math.Long} The sum of this and the given Long.
  538. */
  539. goog.math.Long.prototype.add = function(other) {
  540. // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
  541. var a48 = this.high_ >>> 16;
  542. var a32 = this.high_ & 0xFFFF;
  543. var a16 = this.low_ >>> 16;
  544. var a00 = this.low_ & 0xFFFF;
  545. var b48 = other.high_ >>> 16;
  546. var b32 = other.high_ & 0xFFFF;
  547. var b16 = other.low_ >>> 16;
  548. var b00 = other.low_ & 0xFFFF;
  549. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  550. c00 += a00 + b00;
  551. c16 += c00 >>> 16;
  552. c00 &= 0xFFFF;
  553. c16 += a16 + b16;
  554. c32 += c16 >>> 16;
  555. c16 &= 0xFFFF;
  556. c32 += a32 + b32;
  557. c48 += c32 >>> 16;
  558. c32 &= 0xFFFF;
  559. c48 += a48 + b48;
  560. c48 &= 0xFFFF;
  561. return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
  562. };
  563. /**
  564. * Returns the difference of this and the given Long.
  565. * @param {goog.math.Long} other Long to subtract from this.
  566. * @return {!goog.math.Long} The difference of this and the given Long.
  567. */
  568. goog.math.Long.prototype.subtract = function(other) {
  569. return this.add(other.negate());
  570. };
  571. /**
  572. * Returns the product of this and the given long.
  573. * @param {goog.math.Long} other Long to multiply with this.
  574. * @return {!goog.math.Long} The product of this and the other.
  575. */
  576. goog.math.Long.prototype.multiply = function(other) {
  577. if (this.isZero()) {
  578. return goog.math.Long.getZero();
  579. } else if (other.isZero()) {
  580. return goog.math.Long.getZero();
  581. }
  582. if (this.equals(goog.math.Long.getMinValue())) {
  583. return other.isOdd() ? goog.math.Long.getMinValue() :
  584. goog.math.Long.getZero();
  585. } else if (other.equals(goog.math.Long.getMinValue())) {
  586. return this.isOdd() ? goog.math.Long.getMinValue() :
  587. goog.math.Long.getZero();
  588. }
  589. if (this.isNegative()) {
  590. if (other.isNegative()) {
  591. return this.negate().multiply(other.negate());
  592. } else {
  593. return this.negate().multiply(other).negate();
  594. }
  595. } else if (other.isNegative()) {
  596. return this.multiply(other.negate()).negate();
  597. }
  598. // If both longs are small, use float multiplication
  599. if (this.lessThan(goog.math.Long.getTwoPwr24()) &&
  600. other.lessThan(goog.math.Long.getTwoPwr24())) {
  601. return goog.math.Long.fromNumber(this.toNumber() * other.toNumber());
  602. }
  603. // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
  604. // We can skip products that would overflow.
  605. var a48 = this.high_ >>> 16;
  606. var a32 = this.high_ & 0xFFFF;
  607. var a16 = this.low_ >>> 16;
  608. var a00 = this.low_ & 0xFFFF;
  609. var b48 = other.high_ >>> 16;
  610. var b32 = other.high_ & 0xFFFF;
  611. var b16 = other.low_ >>> 16;
  612. var b00 = other.low_ & 0xFFFF;
  613. var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  614. c00 += a00 * b00;
  615. c16 += c00 >>> 16;
  616. c00 &= 0xFFFF;
  617. c16 += a16 * b00;
  618. c32 += c16 >>> 16;
  619. c16 &= 0xFFFF;
  620. c16 += a00 * b16;
  621. c32 += c16 >>> 16;
  622. c16 &= 0xFFFF;
  623. c32 += a32 * b00;
  624. c48 += c32 >>> 16;
  625. c32 &= 0xFFFF;
  626. c32 += a16 * b16;
  627. c48 += c32 >>> 16;
  628. c32 &= 0xFFFF;
  629. c32 += a00 * b32;
  630. c48 += c32 >>> 16;
  631. c32 &= 0xFFFF;
  632. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  633. c48 &= 0xFFFF;
  634. return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
  635. };
  636. /**
  637. * Returns this Long divided by the given one.
  638. * @param {goog.math.Long} other Long by which to divide.
  639. * @return {!goog.math.Long} This Long divided by the given one.
  640. */
  641. goog.math.Long.prototype.div = function(other) {
  642. if (other.isZero()) {
  643. throw Error('division by zero');
  644. } else if (this.isZero()) {
  645. return goog.math.Long.getZero();
  646. }
  647. if (this.equals(goog.math.Long.getMinValue())) {
  648. if (other.equals(goog.math.Long.getOne()) ||
  649. other.equals(goog.math.Long.getNegOne())) {
  650. return goog.math.Long.getMinValue(); // recall -MIN_VALUE == MIN_VALUE
  651. } else if (other.equals(goog.math.Long.getMinValue())) {
  652. return goog.math.Long.getOne();
  653. } else {
  654. // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
  655. var halfThis = this.shiftRight(1);
  656. var approx = halfThis.div(other).shiftLeft(1);
  657. if (approx.equals(goog.math.Long.getZero())) {
  658. return other.isNegative() ? goog.math.Long.getOne() :
  659. goog.math.Long.getNegOne();
  660. } else {
  661. var rem = this.subtract(other.multiply(approx));
  662. var result = approx.add(rem.div(other));
  663. return result;
  664. }
  665. }
  666. } else if (other.equals(goog.math.Long.getMinValue())) {
  667. return goog.math.Long.getZero();
  668. }
  669. if (this.isNegative()) {
  670. if (other.isNegative()) {
  671. return this.negate().div(other.negate());
  672. } else {
  673. return this.negate().div(other).negate();
  674. }
  675. } else if (other.isNegative()) {
  676. return this.div(other.negate()).negate();
  677. }
  678. // Repeat the following until the remainder is less than other: find a
  679. // floating-point that approximates remainder / other *from below*, add this
  680. // into the result, and subtract it from the remainder. It is critical that
  681. // the approximate value is less than or equal to the real value so that the
  682. // remainder never becomes negative.
  683. var res = goog.math.Long.getZero();
  684. var rem = this;
  685. while (rem.greaterThanOrEqual(other)) {
  686. // Approximate the result of division. This may be a little greater or
  687. // smaller than the actual value.
  688. var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
  689. // We will tweak the approximate result by changing it in the 48-th digit or
  690. // the smallest non-fractional digit, whichever is larger.
  691. var log2 = Math.ceil(Math.log(approx) / Math.LN2);
  692. var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
  693. // Decrease the approximation until it is smaller than the remainder. Note
  694. // that if it is too large, the product overflows and is negative.
  695. var approxRes = goog.math.Long.fromNumber(approx);
  696. var approxRem = approxRes.multiply(other);
  697. while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
  698. approx -= delta;
  699. approxRes = goog.math.Long.fromNumber(approx);
  700. approxRem = approxRes.multiply(other);
  701. }
  702. // We know the answer can't be zero... and actually, zero would cause
  703. // infinite recursion since we would make no progress.
  704. if (approxRes.isZero()) {
  705. approxRes = goog.math.Long.getOne();
  706. }
  707. res = res.add(approxRes);
  708. rem = rem.subtract(approxRem);
  709. }
  710. return res;
  711. };
  712. /**
  713. * Returns this Long modulo the given one.
  714. * @param {goog.math.Long} other Long by which to mod.
  715. * @return {!goog.math.Long} This Long modulo the given one.
  716. */
  717. goog.math.Long.prototype.modulo = function(other) {
  718. return this.subtract(this.div(other).multiply(other));
  719. };
  720. /** @return {!goog.math.Long} The bitwise-NOT of this value. */
  721. goog.math.Long.prototype.not = function() {
  722. return goog.math.Long.fromBits(~this.low_, ~this.high_);
  723. };
  724. /**
  725. * Returns the bitwise-AND of this Long and the given one.
  726. * @param {goog.math.Long} other The Long with which to AND.
  727. * @return {!goog.math.Long} The bitwise-AND of this and the other.
  728. */
  729. goog.math.Long.prototype.and = function(other) {
  730. return goog.math.Long.fromBits(
  731. this.low_ & other.low_, this.high_ & other.high_);
  732. };
  733. /**
  734. * Returns the bitwise-OR of this Long and the given one.
  735. * @param {goog.math.Long} other The Long with which to OR.
  736. * @return {!goog.math.Long} The bitwise-OR of this and the other.
  737. */
  738. goog.math.Long.prototype.or = function(other) {
  739. return goog.math.Long.fromBits(
  740. this.low_ | other.low_, this.high_ | other.high_);
  741. };
  742. /**
  743. * Returns the bitwise-XOR of this Long and the given one.
  744. * @param {goog.math.Long} other The Long with which to XOR.
  745. * @return {!goog.math.Long} The bitwise-XOR of this and the other.
  746. */
  747. goog.math.Long.prototype.xor = function(other) {
  748. return goog.math.Long.fromBits(
  749. this.low_ ^ other.low_, this.high_ ^ other.high_);
  750. };
  751. /**
  752. * Returns this Long with bits shifted to the left by the given amount.
  753. * @param {number} numBits The number of bits by which to shift.
  754. * @return {!goog.math.Long} This shifted to the left by the given amount.
  755. */
  756. goog.math.Long.prototype.shiftLeft = function(numBits) {
  757. numBits &= 63;
  758. if (numBits == 0) {
  759. return this;
  760. } else {
  761. var low = this.low_;
  762. if (numBits < 32) {
  763. var high = this.high_;
  764. return goog.math.Long.fromBits(
  765. low << numBits, (high << numBits) | (low >>> (32 - numBits)));
  766. } else {
  767. return goog.math.Long.fromBits(0, low << (numBits - 32));
  768. }
  769. }
  770. };
  771. /**
  772. * Returns this Long with bits shifted to the right by the given amount.
  773. * The new leading bits match the current sign bit.
  774. * @param {number} numBits The number of bits by which to shift.
  775. * @return {!goog.math.Long} This shifted to the right by the given amount.
  776. */
  777. goog.math.Long.prototype.shiftRight = function(numBits) {
  778. numBits &= 63;
  779. if (numBits == 0) {
  780. return this;
  781. } else {
  782. var high = this.high_;
  783. if (numBits < 32) {
  784. var low = this.low_;
  785. return goog.math.Long.fromBits(
  786. (low >>> numBits) | (high << (32 - numBits)), high >> numBits);
  787. } else {
  788. return goog.math.Long.fromBits(
  789. high >> (numBits - 32), high >= 0 ? 0 : -1);
  790. }
  791. }
  792. };
  793. /**
  794. * Returns this Long with bits shifted to the right by the given amount, with
  795. * zeros placed into the new leading bits.
  796. * @param {number} numBits The number of bits by which to shift.
  797. * @return {!goog.math.Long} This shifted to the right by the given amount, with
  798. * zeros placed into the new leading bits.
  799. */
  800. goog.math.Long.prototype.shiftRightUnsigned = function(numBits) {
  801. numBits &= 63;
  802. if (numBits == 0) {
  803. return this;
  804. } else {
  805. var high = this.high_;
  806. if (numBits < 32) {
  807. var low = this.low_;
  808. return goog.math.Long.fromBits(
  809. (low >>> numBits) | (high << (32 - numBits)), high >>> numBits);
  810. } else if (numBits == 32) {
  811. return goog.math.Long.fromBits(high, 0);
  812. } else {
  813. return goog.math.Long.fromBits(high >>> (numBits - 32), 0);
  814. }
  815. }
  816. };
  817. /**
  818. * @enum {number} Ids of commonly requested Long instances.
  819. * @private
  820. */
  821. goog.math.Long.ValueCacheId_ = {
  822. MAX_VALUE: 1,
  823. MIN_VALUE: 2,
  824. TWO_PWR_24: 6
  825. };