arith.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. /**
  31. * @fileoverview This file contains helper code used by jspb.utils to
  32. * handle 64-bit integer conversion to/from strings.
  33. *
  34. * @author cfallin@google.com (Chris Fallin)
  35. *
  36. * TODO(haberman): move this to javascript/closure/math?
  37. */
  38. goog.provide('jspb.arith.Int64');
  39. goog.provide('jspb.arith.UInt64');
  40. /**
  41. * UInt64 implements some 64-bit arithmetic routines necessary for properly
  42. * handling 64-bit integer fields. It implements lossless integer arithmetic on
  43. * top of JavaScript's number type, which has only 53 bits of precision, by
  44. * representing 64-bit integers as two 32-bit halves.
  45. *
  46. * @param {number} lo The low 32 bits.
  47. * @param {number} hi The high 32 bits.
  48. * @constructor
  49. */
  50. jspb.arith.UInt64 = function(lo, hi) {
  51. /**
  52. * The low 32 bits.
  53. * @public {number}
  54. */
  55. this.lo = lo;
  56. /**
  57. * The high 32 bits.
  58. * @public {number}
  59. */
  60. this.hi = hi;
  61. };
  62. /**
  63. * Compare two 64-bit numbers. Returns -1 if the first is
  64. * less, +1 if the first is greater, or 0 if both are equal.
  65. * @param {!jspb.arith.UInt64} other
  66. * @return {number}
  67. */
  68. jspb.arith.UInt64.prototype.cmp = function(other) {
  69. if (this.hi < other.hi || (this.hi == other.hi && this.lo < other.lo)) {
  70. return -1;
  71. } else if (this.hi == other.hi && this.lo == other.lo) {
  72. return 0;
  73. } else {
  74. return 1;
  75. }
  76. };
  77. /**
  78. * Right-shift this number by one bit.
  79. * @return {!jspb.arith.UInt64}
  80. */
  81. jspb.arith.UInt64.prototype.rightShift = function() {
  82. var hi = this.hi >>> 1;
  83. var lo = (this.lo >>> 1) | ((this.hi & 1) << 31);
  84. return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
  85. };
  86. /**
  87. * Left-shift this number by one bit.
  88. * @return {!jspb.arith.UInt64}
  89. */
  90. jspb.arith.UInt64.prototype.leftShift = function() {
  91. var lo = this.lo << 1;
  92. var hi = (this.hi << 1) | (this.lo >>> 31);
  93. return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
  94. };
  95. /**
  96. * Test the MSB.
  97. * @return {boolean}
  98. */
  99. jspb.arith.UInt64.prototype.msb = function() {
  100. return !!(this.hi & 0x80000000);
  101. };
  102. /**
  103. * Test the LSB.
  104. * @return {boolean}
  105. */
  106. jspb.arith.UInt64.prototype.lsb = function() {
  107. return !!(this.lo & 1);
  108. };
  109. /**
  110. * Test whether this number is zero.
  111. * @return {boolean}
  112. */
  113. jspb.arith.UInt64.prototype.zero = function() {
  114. return this.lo == 0 && this.hi == 0;
  115. };
  116. /**
  117. * Add two 64-bit numbers to produce a 64-bit number.
  118. * @param {!jspb.arith.UInt64} other
  119. * @return {!jspb.arith.UInt64}
  120. */
  121. jspb.arith.UInt64.prototype.add = function(other) {
  122. var lo = ((this.lo + other.lo) & 0xffffffff) >>> 0;
  123. var hi =
  124. (((this.hi + other.hi) & 0xffffffff) >>> 0) +
  125. (((this.lo + other.lo) >= 0x100000000) ? 1 : 0);
  126. return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
  127. };
  128. /**
  129. * Subtract two 64-bit numbers to produce a 64-bit number.
  130. * @param {!jspb.arith.UInt64} other
  131. * @return {!jspb.arith.UInt64}
  132. */
  133. jspb.arith.UInt64.prototype.sub = function(other) {
  134. var lo = ((this.lo - other.lo) & 0xffffffff) >>> 0;
  135. var hi =
  136. (((this.hi - other.hi) & 0xffffffff) >>> 0) -
  137. (((this.lo - other.lo) < 0) ? 1 : 0);
  138. return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
  139. };
  140. /**
  141. * Multiply two 32-bit numbers to produce a 64-bit number.
  142. * @param {number} a The first integer: must be in [0, 2^32-1).
  143. * @param {number} b The second integer: must be in [0, 2^32-1).
  144. * @return {!jspb.arith.UInt64}
  145. */
  146. jspb.arith.UInt64.mul32x32 = function(a, b) {
  147. // Directly multiplying two 32-bit numbers may produce up to 64 bits of
  148. // precision, thus losing precision because of the 53-bit mantissa of
  149. // JavaScript numbers. So we multiply with 16-bit digits (radix 65536)
  150. // instead.
  151. var aLow = (a & 0xffff);
  152. var aHigh = (a >>> 16);
  153. var bLow = (b & 0xffff);
  154. var bHigh = (b >>> 16);
  155. var productLow =
  156. // 32-bit result, result bits 0-31, take all 32 bits
  157. (aLow * bLow) +
  158. // 32-bit result, result bits 16-47, take bottom 16 as our top 16
  159. ((aLow * bHigh) & 0xffff) * 0x10000 +
  160. // 32-bit result, result bits 16-47, take bottom 16 as our top 16
  161. ((aHigh * bLow) & 0xffff) * 0x10000;
  162. var productHigh =
  163. // 32-bit result, result bits 32-63, take all 32 bits
  164. (aHigh * bHigh) +
  165. // 32-bit result, result bits 16-47, take top 16 as our bottom 16
  166. ((aLow * bHigh) >>> 16) +
  167. // 32-bit result, result bits 16-47, take top 16 as our bottom 16
  168. ((aHigh * bLow) >>> 16);
  169. // Carry. Note that we actually have up to *two* carries due to addition of
  170. // three terms.
  171. while (productLow >= 0x100000000) {
  172. productLow -= 0x100000000;
  173. productHigh += 1;
  174. }
  175. return new jspb.arith.UInt64(productLow >>> 0, productHigh >>> 0);
  176. };
  177. /**
  178. * Multiply this number by a 32-bit number, producing a 96-bit number, then
  179. * truncate the top 32 bits.
  180. * @param {number} a The multiplier.
  181. * @return {!jspb.arith.UInt64}
  182. */
  183. jspb.arith.UInt64.prototype.mul = function(a) {
  184. // Produce two parts: at bits 0-63, and 32-95.
  185. var lo = jspb.arith.UInt64.mul32x32(this.lo, a);
  186. var hi = jspb.arith.UInt64.mul32x32(this.hi, a);
  187. // Left-shift hi by 32 bits, truncating its top bits. The parts will then be
  188. // aligned for addition.
  189. hi.hi = hi.lo;
  190. hi.lo = 0;
  191. return lo.add(hi);
  192. };
  193. /**
  194. * Divide a 64-bit number by a 32-bit number to produce a
  195. * 64-bit quotient and a 32-bit remainder.
  196. * @param {number} _divisor
  197. * @return {Array<jspb.arith.UInt64>} array of [quotient, remainder],
  198. * unless divisor is 0, in which case an empty array is returned.
  199. */
  200. jspb.arith.UInt64.prototype.div = function(_divisor) {
  201. if (_divisor == 0) {
  202. return [];
  203. }
  204. // We perform long division using a radix-2 algorithm, for simplicity (i.e.,
  205. // one bit at a time). TODO: optimize to a radix-2^32 algorithm, taking care
  206. // to get the variable shifts right.
  207. var quotient = new jspb.arith.UInt64(0, 0);
  208. var remainder = new jspb.arith.UInt64(this.lo, this.hi);
  209. var divisor = new jspb.arith.UInt64(_divisor, 0);
  210. var unit = new jspb.arith.UInt64(1, 0);
  211. // Left-shift the divisor and unit until the high bit of divisor is set.
  212. while (!divisor.msb()) {
  213. divisor = divisor.leftShift();
  214. unit = unit.leftShift();
  215. }
  216. // Perform long division one bit at a time.
  217. while (!unit.zero()) {
  218. // If divisor < remainder, add unit to quotient and subtract divisor from
  219. // remainder.
  220. if (divisor.cmp(remainder) <= 0) {
  221. quotient = quotient.add(unit);
  222. remainder = remainder.sub(divisor);
  223. }
  224. // Right-shift the divisor and unit.
  225. divisor = divisor.rightShift();
  226. unit = unit.rightShift();
  227. }
  228. return [quotient, remainder];
  229. };
  230. /**
  231. * Convert a 64-bit number to a string.
  232. * @return {string}
  233. * @override
  234. */
  235. jspb.arith.UInt64.prototype.toString = function() {
  236. var result = '';
  237. var num = this;
  238. while (!num.zero()) {
  239. var divResult = num.div(10);
  240. var quotient = divResult[0], remainder = divResult[1];
  241. result = remainder.lo + result;
  242. num = quotient;
  243. }
  244. if (result == '') {
  245. result = '0';
  246. }
  247. return result;
  248. };
  249. /**
  250. * Parse a string into a 64-bit number. Returns `null` on a parse error.
  251. * @param {string} s
  252. * @return {?jspb.arith.UInt64}
  253. */
  254. jspb.arith.UInt64.fromString = function(s) {
  255. var result = new jspb.arith.UInt64(0, 0);
  256. // optimization: reuse this instance for each digit.
  257. var digit64 = new jspb.arith.UInt64(0, 0);
  258. for (var i = 0; i < s.length; i++) {
  259. if (s[i] < '0' || s[i] > '9') {
  260. return null;
  261. }
  262. var digit = parseInt(s[i], 10);
  263. digit64.lo = digit;
  264. result = result.mul(10).add(digit64);
  265. }
  266. return result;
  267. };
  268. /**
  269. * Make a copy of the uint64.
  270. * @return {!jspb.arith.UInt64}
  271. */
  272. jspb.arith.UInt64.prototype.clone = function() {
  273. return new jspb.arith.UInt64(this.lo, this.hi);
  274. };
  275. /**
  276. * Int64 is like UInt64, but modifies string conversions to interpret the stored
  277. * 64-bit value as a twos-complement-signed integer. It does *not* support the
  278. * full range of operations that UInt64 does: only add, subtract, and string
  279. * conversions.
  280. *
  281. * N.B. that multiply and divide routines are *NOT* supported. They will throw
  282. * exceptions. (They are not necessary to implement string conversions, which
  283. * are the only operations we really need in jspb.)
  284. *
  285. * @param {number} lo The low 32 bits.
  286. * @param {number} hi The high 32 bits.
  287. * @constructor
  288. */
  289. jspb.arith.Int64 = function(lo, hi) {
  290. /**
  291. * The low 32 bits.
  292. * @public {number}
  293. */
  294. this.lo = lo;
  295. /**
  296. * The high 32 bits.
  297. * @public {number}
  298. */
  299. this.hi = hi;
  300. };
  301. /**
  302. * Add two 64-bit numbers to produce a 64-bit number.
  303. * @param {!jspb.arith.Int64} other
  304. * @return {!jspb.arith.Int64}
  305. */
  306. jspb.arith.Int64.prototype.add = function(other) {
  307. var lo = ((this.lo + other.lo) & 0xffffffff) >>> 0;
  308. var hi =
  309. (((this.hi + other.hi) & 0xffffffff) >>> 0) +
  310. (((this.lo + other.lo) >= 0x100000000) ? 1 : 0);
  311. return new jspb.arith.Int64(lo >>> 0, hi >>> 0);
  312. };
  313. /**
  314. * Subtract two 64-bit numbers to produce a 64-bit number.
  315. * @param {!jspb.arith.Int64} other
  316. * @return {!jspb.arith.Int64}
  317. */
  318. jspb.arith.Int64.prototype.sub = function(other) {
  319. var lo = ((this.lo - other.lo) & 0xffffffff) >>> 0;
  320. var hi =
  321. (((this.hi - other.hi) & 0xffffffff) >>> 0) -
  322. (((this.lo - other.lo) < 0) ? 1 : 0);
  323. return new jspb.arith.Int64(lo >>> 0, hi >>> 0);
  324. };
  325. /**
  326. * Make a copy of the int64.
  327. * @return {!jspb.arith.Int64}
  328. */
  329. jspb.arith.Int64.prototype.clone = function() {
  330. return new jspb.arith.Int64(this.lo, this.hi);
  331. };
  332. /**
  333. * Convert a 64-bit number to a string.
  334. * @return {string}
  335. * @override
  336. */
  337. jspb.arith.Int64.prototype.toString = function() {
  338. // If the number is negative, find its twos-complement inverse.
  339. var sign = (this.hi & 0x80000000) != 0;
  340. var num = new jspb.arith.UInt64(this.lo, this.hi);
  341. if (sign) {
  342. num = new jspb.arith.UInt64(0, 0).sub(num);
  343. }
  344. return (sign ? '-' : '') + num.toString();
  345. };
  346. /**
  347. * Parse a string into a 64-bit number. Returns `null` on a parse error.
  348. * @param {string} s
  349. * @return {?jspb.arith.Int64}
  350. */
  351. jspb.arith.Int64.fromString = function(s) {
  352. var hasNegative = (s.length > 0 && s[0] == '-');
  353. if (hasNegative) {
  354. s = s.substring(1);
  355. }
  356. var num = jspb.arith.UInt64.fromString(s);
  357. if (num === null) {
  358. return null;
  359. }
  360. if (hasNegative) {
  361. num = new jspb.arith.UInt64(0, 0).sub(num);
  362. }
  363. return new jspb.arith.Int64(num.lo, num.hi);
  364. };