• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/**
32 * @fileoverview This file contains helper code used by jspb.BinaryReader
33 * and BinaryWriter.
34 *
35 * @author aappleby@google.com (Austin Appleby)
36 */
37
38goog.provide('jspb.utils');
39
40goog.require('goog.asserts');
41goog.require('goog.crypt');
42goog.require('goog.crypt.base64');
43goog.require('goog.string');
44goog.require('jspb.BinaryConstants');
45
46
47/**
48 * Javascript can't natively handle 64-bit data types, so to manipulate them we
49 * have to split them into two 32-bit halves and do the math manually.
50 *
51 * Instead of instantiating and passing small structures around to do this, we
52 * instead just use two global temporary values. This one stores the low 32
53 * bits of a split value - for example, if the original value was a 64-bit
54 * integer, this temporary value will contain the low 32 bits of that integer.
55 * If the original value was a double, this temporary value will contain the
56 * low 32 bits of the binary representation of that double, etcetera.
57 * @type {number}
58 */
59jspb.utils.split64Low = 0;
60
61
62/**
63 * And correspondingly, this temporary variable will contain the high 32 bits
64 * of whatever value was split.
65 * @type {number}
66 */
67jspb.utils.split64High = 0;
68
69
70/**
71 * Splits an unsigned Javascript integer into two 32-bit halves and stores it
72 * in the temp values above.
73 * @param {number} value The number to split.
74 */
75jspb.utils.splitUint64 = function(value) {
76  // Extract low 32 bits and high 32 bits as unsigned integers.
77  var lowBits = value >>> 0;
78  var highBits = Math.floor((value - lowBits) /
79                            jspb.BinaryConstants.TWO_TO_32) >>> 0;
80
81  jspb.utils.split64Low = lowBits;
82  jspb.utils.split64High = highBits;
83};
84
85
86/**
87 * Splits a signed Javascript integer into two 32-bit halves and stores it in
88 * the temp values above.
89 * @param {number} value The number to split.
90 */
91jspb.utils.splitInt64 = function(value) {
92  // Convert to sign-magnitude representation.
93  var sign = (value < 0);
94  value = Math.abs(value);
95
96  // Extract low 32 bits and high 32 bits as unsigned integers.
97  var lowBits = value >>> 0;
98  var highBits = Math.floor((value - lowBits) /
99                            jspb.BinaryConstants.TWO_TO_32);
100  highBits = highBits >>> 0;
101
102  // Perform two's complement conversion if the sign bit was set.
103  if (sign) {
104    highBits = ~highBits >>> 0;
105    lowBits = ~lowBits >>> 0;
106    lowBits += 1;
107    if (lowBits > 0xFFFFFFFF) {
108      lowBits = 0;
109      highBits++;
110      if (highBits > 0xFFFFFFFF) highBits = 0;
111    }
112  }
113
114  jspb.utils.split64Low = lowBits;
115  jspb.utils.split64High = highBits;
116};
117
118
119/**
120 * Convers a signed Javascript integer into zigzag format, splits it into two
121 * 32-bit halves, and stores it in the temp values above.
122 * @param {number} value The number to split.
123 */
124jspb.utils.splitZigzag64 = function(value) {
125  // Convert to sign-magnitude and scale by 2 before we split the value.
126  var sign = (value < 0);
127  value = Math.abs(value) * 2;
128
129  jspb.utils.splitUint64(value);
130  var lowBits = jspb.utils.split64Low;
131  var highBits = jspb.utils.split64High;
132
133  // If the value is negative, subtract 1 from the split representation so we
134  // don't lose the sign bit due to precision issues.
135  if (sign) {
136    if (lowBits == 0) {
137      if (highBits == 0) {
138        lowBits = 0xFFFFFFFF;
139        highBits = 0xFFFFFFFF;
140      } else {
141        highBits--;
142        lowBits = 0xFFFFFFFF;
143      }
144    } else {
145      lowBits--;
146    }
147  }
148
149  jspb.utils.split64Low = lowBits;
150  jspb.utils.split64High = highBits;
151};
152
153
154/**
155 * Converts a floating-point number into 32-bit IEEE representation and stores
156 * it in the temp values above.
157 * @param {number} value
158 */
159jspb.utils.splitFloat32 = function(value) {
160  var sign = (value < 0) ? 1 : 0;
161  value = sign ? -value : value;
162  var exp;
163  var mant;
164
165  // Handle zeros.
166  if (value === 0) {
167    if ((1 / value) > 0) {
168      // Positive zero.
169      jspb.utils.split64High = 0;
170      jspb.utils.split64Low = 0x00000000;
171    } else {
172      // Negative zero.
173      jspb.utils.split64High = 0;
174      jspb.utils.split64Low = 0x80000000;
175    }
176    return;
177  }
178
179  // Handle nans.
180  if (isNaN(value)) {
181    jspb.utils.split64High = 0;
182    jspb.utils.split64Low = 0x7FFFFFFF;
183    return;
184  }
185
186  // Handle infinities.
187  if (value > jspb.BinaryConstants.FLOAT32_MAX) {
188    jspb.utils.split64High = 0;
189    jspb.utils.split64Low = ((sign << 31) | (0x7F800000)) >>> 0;
190    return;
191  }
192
193  // Handle denormals.
194  if (value < jspb.BinaryConstants.FLOAT32_MIN) {
195    // Number is a denormal.
196    mant = Math.round(value / Math.pow(2, -149));
197    jspb.utils.split64High = 0;
198    jspb.utils.split64Low = ((sign << 31) | mant) >>> 0;
199    return;
200  }
201
202  exp = Math.floor(Math.log(value) / Math.LN2);
203  mant = value * Math.pow(2, -exp);
204  mant = Math.round(mant * jspb.BinaryConstants.TWO_TO_23) & 0x7FFFFF;
205
206  jspb.utils.split64High = 0;
207  jspb.utils.split64Low = ((sign << 31) | ((exp + 127) << 23) | mant) >>> 0;
208};
209
210
211/**
212 * Converts a floating-point number into 64-bit IEEE representation and stores
213 * it in the temp values above.
214 * @param {number} value
215 */
216jspb.utils.splitFloat64 = function(value) {
217  var sign = (value < 0) ? 1 : 0;
218  value = sign ? -value : value;
219
220  // Handle zeros.
221  if (value === 0) {
222    if ((1 / value) > 0) {
223      // Positive zero.
224      jspb.utils.split64High = 0x00000000;
225      jspb.utils.split64Low = 0x00000000;
226    } else {
227      // Negative zero.
228      jspb.utils.split64High = 0x80000000;
229      jspb.utils.split64Low = 0x00000000;
230    }
231    return;
232  }
233
234  // Handle nans.
235  if (isNaN(value)) {
236    jspb.utils.split64High = 0x7FFFFFFF;
237    jspb.utils.split64Low = 0xFFFFFFFF;
238    return;
239  }
240
241  // Handle infinities.
242  if (value > jspb.BinaryConstants.FLOAT64_MAX) {
243    jspb.utils.split64High = ((sign << 31) | (0x7FF00000)) >>> 0;
244    jspb.utils.split64Low = 0;
245    return;
246  }
247
248  // Handle denormals.
249  if (value < jspb.BinaryConstants.FLOAT64_MIN) {
250    // Number is a denormal.
251    var mant = value / Math.pow(2, -1074);
252    var mantHigh = (mant / jspb.BinaryConstants.TWO_TO_32);
253    jspb.utils.split64High = ((sign << 31) | mantHigh) >>> 0;
254    jspb.utils.split64Low = (mant >>> 0);
255    return;
256  }
257
258  var exp = Math.floor(Math.log(value) / Math.LN2);
259  if (exp == 1024) exp = 1023;
260  var mant = value * Math.pow(2, -exp);
261
262  var mantHigh = (mant * jspb.BinaryConstants.TWO_TO_20) & 0xFFFFF;
263  var mantLow = (mant * jspb.BinaryConstants.TWO_TO_52) >>> 0;
264
265  jspb.utils.split64High =
266      ((sign << 31) | ((exp + 1023) << 20) | mantHigh) >>> 0;
267  jspb.utils.split64Low = mantLow;
268};
269
270
271/**
272 * Converts an 8-character hash string into two 32-bit numbers and stores them
273 * in the temp values above.
274 * @param {string} hash
275 */
276jspb.utils.splitHash64 = function(hash) {
277  var a = hash.charCodeAt(0);
278  var b = hash.charCodeAt(1);
279  var c = hash.charCodeAt(2);
280  var d = hash.charCodeAt(3);
281  var e = hash.charCodeAt(4);
282  var f = hash.charCodeAt(5);
283  var g = hash.charCodeAt(6);
284  var h = hash.charCodeAt(7);
285
286  jspb.utils.split64Low = (a + (b << 8) + (c << 16) + (d << 24)) >>> 0;
287  jspb.utils.split64High = (e + (f << 8) + (g << 16) + (h << 24)) >>> 0;
288};
289
290
291/**
292 * Joins two 32-bit values into a 64-bit unsigned integer. Precision will be
293 * lost if the result is greater than 2^52.
294 * @param {number} bitsLow
295 * @param {number} bitsHigh
296 * @return {number}
297 */
298jspb.utils.joinUint64 = function(bitsLow, bitsHigh) {
299  return bitsHigh * jspb.BinaryConstants.TWO_TO_32 + bitsLow;
300};
301
302
303/**
304 * Joins two 32-bit values into a 64-bit signed integer. Precision will be lost
305 * if the result is greater than 2^52.
306 * @param {number} bitsLow
307 * @param {number} bitsHigh
308 * @return {number}
309 */
310jspb.utils.joinInt64 = function(bitsLow, bitsHigh) {
311  // If the high bit is set, do a manual two's complement conversion.
312  var sign = (bitsHigh & 0x80000000);
313  if (sign) {
314    bitsLow = (~bitsLow + 1) >>> 0;
315    bitsHigh = ~bitsHigh >>> 0;
316    if (bitsLow == 0) {
317      bitsHigh = (bitsHigh + 1) >>> 0;
318    }
319  }
320
321  var result = jspb.utils.joinUint64(bitsLow, bitsHigh);
322  return sign ? -result : result;
323};
324
325
326/**
327 * Joins two 32-bit values into a 64-bit unsigned integer and applies zigzag
328 * decoding. Precision will be lost if the result is greater than 2^52.
329 * @param {number} bitsLow
330 * @param {number} bitsHigh
331 * @return {number}
332 */
333jspb.utils.joinZigzag64 = function(bitsLow, bitsHigh) {
334  // Extract the sign bit and shift right by one.
335  var sign = bitsLow & 1;
336  bitsLow = ((bitsLow >>> 1) | (bitsHigh << 31)) >>> 0;
337  bitsHigh = bitsHigh >>> 1;
338
339  // Increment the split value if the sign bit was set.
340  if (sign) {
341    bitsLow = (bitsLow + 1) >>> 0;
342    if (bitsLow == 0) {
343      bitsHigh = (bitsHigh + 1) >>> 0;
344    }
345  }
346
347  var result = jspb.utils.joinUint64(bitsLow, bitsHigh);
348  return sign ? -result : result;
349};
350
351
352/**
353 * Joins two 32-bit values into a 32-bit IEEE floating point number and
354 * converts it back into a Javascript number.
355 * @param {number} bitsLow The low 32 bits of the binary number;
356 * @param {number} bitsHigh The high 32 bits of the binary number.
357 * @return {number}
358 */
359jspb.utils.joinFloat32 = function(bitsLow, bitsHigh) {
360  var sign = ((bitsLow >> 31) * 2 + 1);
361  var exp = (bitsLow >>> 23) & 0xFF;
362  var mant = bitsLow & 0x7FFFFF;
363
364  if (exp == 0xFF) {
365    if (mant) {
366      return NaN;
367    } else {
368      return sign * Infinity;
369    }
370  }
371
372  if (exp == 0) {
373    // Denormal.
374    return sign * Math.pow(2, -149) * mant;
375  } else {
376    return sign * Math.pow(2, exp - 150) *
377           (mant + Math.pow(2, 23));
378  }
379};
380
381
382/**
383 * Joins two 32-bit values into a 64-bit IEEE floating point number and
384 * converts it back into a Javascript number.
385 * @param {number} bitsLow The low 32 bits of the binary number;
386 * @param {number} bitsHigh The high 32 bits of the binary number.
387 * @return {number}
388 */
389jspb.utils.joinFloat64 = function(bitsLow, bitsHigh) {
390  var sign = ((bitsHigh >> 31) * 2 + 1);
391  var exp = (bitsHigh >>> 20) & 0x7FF;
392  var mant = jspb.BinaryConstants.TWO_TO_32 * (bitsHigh & 0xFFFFF) + bitsLow;
393
394  if (exp == 0x7FF) {
395    if (mant) {
396      return NaN;
397    } else {
398      return sign * Infinity;
399    }
400  }
401
402  if (exp == 0) {
403    // Denormal.
404    return sign * Math.pow(2, -1074) * mant;
405  } else {
406    return sign * Math.pow(2, exp - 1075) *
407           (mant + jspb.BinaryConstants.TWO_TO_52);
408  }
409};
410
411
412/**
413 * Joins two 32-bit values into an 8-character hash string.
414 * @param {number} bitsLow
415 * @param {number} bitsHigh
416 * @return {string}
417 */
418jspb.utils.joinHash64 = function(bitsLow, bitsHigh) {
419  var a = (bitsLow >>> 0) & 0xFF;
420  var b = (bitsLow >>> 8) & 0xFF;
421  var c = (bitsLow >>> 16) & 0xFF;
422  var d = (bitsLow >>> 24) & 0xFF;
423  var e = (bitsHigh >>> 0) & 0xFF;
424  var f = (bitsHigh >>> 8) & 0xFF;
425  var g = (bitsHigh >>> 16) & 0xFF;
426  var h = (bitsHigh >>> 24) & 0xFF;
427
428  return String.fromCharCode(a, b, c, d, e, f, g, h);
429};
430
431
432/**
433 * Individual digits for number->string conversion.
434 * @const {!Array<string>}
435 */
436jspb.utils.DIGITS = [
437  '0', '1', '2', '3', '4', '5', '6', '7',
438  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
439];
440
441
442/**
443 * Losslessly converts a 64-bit unsigned integer in 32:32 split representation
444 * into a decimal string.
445 * @param {number} bitsLow The low 32 bits of the binary number;
446 * @param {number} bitsHigh The high 32 bits of the binary number.
447 * @return {string} The binary number represented as a string.
448 */
449jspb.utils.joinUnsignedDecimalString = function(bitsLow, bitsHigh) {
450  // Skip the expensive conversion if the number is small enough to use the
451  // built-in conversions.
452  if (bitsHigh <= 0x1FFFFF) {
453    return '' + (jspb.BinaryConstants.TWO_TO_32 * bitsHigh + bitsLow);
454  }
455
456  // What this code is doing is essentially converting the input number from
457  // base-2 to base-1e7, which allows us to represent the 64-bit range with
458  // only 3 (very large) digits. Those digits are then trivial to convert to
459  // a base-10 string.
460
461  // The magic numbers used here are -
462  // 2^24 = 16777216 = (1,6777216) in base-1e7.
463  // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
464
465  // Split 32:32 representation into 16:24:24 representation so our
466  // intermediate digits don't overflow.
467  var low = bitsLow & 0xFFFFFF;
468  var mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
469  var high = (bitsHigh >> 16) & 0xFFFF;
470
471  // Assemble our three base-1e7 digits, ignoring carries. The maximum
472  // value in a digit at this step is representable as a 48-bit integer, which
473  // can be stored in a 64-bit floating point number.
474  var digitA = low + (mid * 6777216) + (high * 6710656);
475  var digitB = mid + (high * 8147497);
476  var digitC = (high * 2);
477
478  // Apply carries from A to B and from B to C.
479  var base = 10000000;
480  if (digitA >= base) {
481    digitB += Math.floor(digitA / base);
482    digitA %= base;
483  }
484
485  if (digitB >= base) {
486    digitC += Math.floor(digitB / base);
487    digitB %= base;
488  }
489
490  // Convert base-1e7 digits to base-10, omitting leading zeroes.
491  var table = jspb.utils.DIGITS;
492  var start = false;
493  var result = '';
494
495  function emit(digit) {
496    var temp = base;
497    for (var i = 0; i < 7; i++) {
498      temp /= 10;
499      var decimalDigit = ((digit / temp) % 10) >>> 0;
500      if ((decimalDigit == 0) && !start) continue;
501      start = true;
502      result += table[decimalDigit];
503    }
504  }
505
506  if (digitC || start) emit(digitC);
507  if (digitB || start) emit(digitB);
508  if (digitA || start) emit(digitA);
509
510  return result;
511};
512
513
514/**
515 * Losslessly converts a 64-bit signed integer in 32:32 split representation
516 * into a decimal string.
517 * @param {number} bitsLow The low 32 bits of the binary number;
518 * @param {number} bitsHigh The high 32 bits of the binary number.
519 * @return {string} The binary number represented as a string.
520 */
521jspb.utils.joinSignedDecimalString = function(bitsLow, bitsHigh) {
522  // If we're treating the input as a signed value and the high bit is set, do
523  // a manual two's complement conversion before the decimal conversion.
524  var negative = (bitsHigh & 0x80000000);
525  if (negative) {
526    bitsLow = (~bitsLow + 1) >>> 0;
527    var carry = (bitsLow == 0) ? 1 : 0;
528    bitsHigh = (~bitsHigh + carry) >>> 0;
529  }
530
531  var result = jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
532  return negative ? '-' + result : result;
533};
534
535
536/**
537 * Convert an 8-character hash string representing either a signed or unsigned
538 * 64-bit integer into its decimal representation without losing accuracy.
539 * @param {string} hash The hash string to convert.
540 * @param {boolean} signed True if we should treat the hash string as encoding
541 *     a signed integer.
542 * @return {string}
543 */
544jspb.utils.hash64ToDecimalString = function(hash, signed) {
545  jspb.utils.splitHash64(hash);
546  var bitsLow = jspb.utils.split64Low;
547  var bitsHigh = jspb.utils.split64High;
548  return signed ?
549      jspb.utils.joinSignedDecimalString(bitsLow, bitsHigh) :
550      jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
551};
552
553
554/**
555 * Converts an array of 8-character hash strings into their decimal
556 * representations.
557 * @param {!Array<string>} hashes The array of hash strings to convert.
558 * @param {boolean} signed True if we should treat the hash string as encoding
559 *     a signed integer.
560 * @return {!Array<string>}
561 */
562jspb.utils.hash64ArrayToDecimalStrings = function(hashes, signed) {
563  var result = new Array(hashes.length);
564  for (var i = 0; i < hashes.length; i++) {
565    result[i] = jspb.utils.hash64ToDecimalString(hashes[i], signed);
566  }
567  return result;
568};
569
570
571/**
572 * Converts a signed or unsigned decimal string into its hash string
573 * representation.
574 * @param {string} dec
575 * @return {string}
576 */
577jspb.utils.decimalStringToHash64 = function(dec) {
578  goog.asserts.assert(dec.length > 0);
579
580  // Check for minus sign.
581  var minus = false;
582  if (dec[0] === '-') {
583    minus = true;
584    dec = dec.slice(1);
585  }
586
587  // Store result as a byte array.
588  var resultBytes = [0, 0, 0, 0, 0, 0, 0, 0];
589
590  // Set result to m*result + c.
591  function muladd(m, c) {
592    for (var i = 0; i < 8 && (m !== 1 || c > 0); i++) {
593      var r = m * resultBytes[i] + c;
594      resultBytes[i] = r & 0xFF;
595      c = r >>> 8;
596    }
597  }
598
599  // Negate the result bits.
600  function neg() {
601    for (var i = 0; i < 8; i++) {
602      resultBytes[i] = (~resultBytes[i]) & 0xFF;
603    }
604  }
605
606  // For each decimal digit, set result to 10*result + digit.
607  for (var i = 0; i < dec.length; i++) {
608    muladd(10, jspb.utils.DIGITS.indexOf(dec[i]));
609  }
610
611  // If there's a minus sign, convert into two's complement.
612  if (minus) {
613    neg();
614    muladd(1, 1);
615  }
616
617  return goog.crypt.byteArrayToString(resultBytes);
618};
619
620
621/**
622 * Converts a signed or unsigned decimal string into two 32-bit halves, and
623 * stores them in the temp variables listed above.
624 * @param {string} value The decimal string to convert.
625 */
626jspb.utils.splitDecimalString = function(value) {
627  jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
628};
629
630
631/**
632 * Converts an 8-character hash string into its hexadecimal representation.
633 * @param {string} hash
634 * @return {string}
635 */
636jspb.utils.hash64ToHexString = function(hash) {
637  var temp = new Array(18);
638  temp[0] = '0';
639  temp[1] = 'x';
640
641  for (var i = 0; i < 8; i++) {
642    var c = hash.charCodeAt(7 - i);
643    temp[i * 2 + 2] = jspb.utils.DIGITS[c >> 4];
644    temp[i * 2 + 3] = jspb.utils.DIGITS[c & 0xF];
645  }
646
647  var result = temp.join('');
648  return result;
649};
650
651
652/**
653 * Converts a '0x<16 digits>' hex string into its hash string representation.
654 * @param {string} hex
655 * @return {string}
656 */
657jspb.utils.hexStringToHash64 = function(hex) {
658  hex = hex.toLowerCase();
659  goog.asserts.assert(hex.length == 18);
660  goog.asserts.assert(hex[0] == '0');
661  goog.asserts.assert(hex[1] == 'x');
662
663  var result = '';
664  for (var i = 0; i < 8; i++) {
665    var hi = jspb.utils.DIGITS.indexOf(hex[i * 2 + 2]);
666    var lo = jspb.utils.DIGITS.indexOf(hex[i * 2 + 3]);
667    result = String.fromCharCode(hi * 16 + lo) + result;
668  }
669
670  return result;
671};
672
673
674/**
675 * Convert an 8-character hash string representing either a signed or unsigned
676 * 64-bit integer into a Javascript number. Will lose accuracy if the result is
677 * larger than 2^52.
678 * @param {string} hash The hash string to convert.
679 * @param {boolean} signed True if the has should be interpreted as a signed
680 *     number.
681 * @return {number}
682 */
683jspb.utils.hash64ToNumber = function(hash, signed) {
684  jspb.utils.splitHash64(hash);
685  var bitsLow = jspb.utils.split64Low;
686  var bitsHigh = jspb.utils.split64High;
687  return signed ? jspb.utils.joinInt64(bitsLow, bitsHigh) :
688                  jspb.utils.joinUint64(bitsLow, bitsHigh);
689};
690
691
692/**
693 * Convert a Javascript number into an 8-character hash string. Will lose
694 * precision if the value is non-integral or greater than 2^64.
695 * @param {number} value The integer to convert.
696 * @return {string}
697 */
698jspb.utils.numberToHash64 = function(value) {
699  jspb.utils.splitInt64(value);
700  return jspb.utils.joinHash64(jspb.utils.split64Low,
701                                  jspb.utils.split64High);
702};
703
704
705/**
706 * Counts the number of contiguous varints in a buffer.
707 * @param {!Uint8Array} buffer The buffer to scan.
708 * @param {number} start The starting point in the buffer to scan.
709 * @param {number} end The end point in the buffer to scan.
710 * @return {number} The number of varints in the buffer.
711 */
712jspb.utils.countVarints = function(buffer, start, end) {
713  // Count how many high bits of each byte were set in the buffer.
714  var count = 0;
715  for (var i = start; i < end; i++) {
716    count += buffer[i] >> 7;
717  }
718
719  // The number of varints in the buffer equals the size of the buffer minus
720  // the number of non-terminal bytes in the buffer (those with the high bit
721  // set).
722  return (end - start) - count;
723};
724
725
726/**
727 * Counts the number of contiguous varint fields with the given field number in
728 * the buffer.
729 * @param {!Uint8Array} buffer The buffer to scan.
730 * @param {number} start The starting point in the buffer to scan.
731 * @param {number} end The end point in the buffer to scan.
732 * @param {number} field The field number to count.
733 * @return {number} The number of matching fields in the buffer.
734 */
735jspb.utils.countVarintFields = function(buffer, start, end, field) {
736  var count = 0;
737  var cursor = start;
738  var tag = field * 8 + jspb.BinaryConstants.WireType.VARINT;
739
740  if (tag < 128) {
741    // Single-byte field tag, we can use a slightly quicker count.
742    while (cursor < end) {
743      // Skip the field tag, or exit if we find a non-matching tag.
744      if (buffer[cursor++] != tag) return count;
745
746      // Field tag matches, we've found a valid field.
747      count++;
748
749      // Skip the varint.
750      while (1) {
751        var x = buffer[cursor++];
752        if ((x & 0x80) == 0) break;
753      }
754    }
755  } else {
756    while (cursor < end) {
757      // Skip the field tag, or exit if we find a non-matching tag.
758      var temp = tag;
759      while (temp > 128) {
760        if (buffer[cursor] != ((temp & 0x7F) | 0x80)) return count;
761        cursor++;
762        temp >>= 7;
763      }
764      if (buffer[cursor++] != temp) return count;
765
766      // Field tag matches, we've found a valid field.
767      count++;
768
769      // Skip the varint.
770      while (1) {
771        var x = buffer[cursor++];
772        if ((x & 0x80) == 0) break;
773      }
774    }
775  }
776  return count;
777};
778
779
780/**
781 * Counts the number of contiguous fixed32 fields with the given tag in the
782 * buffer.
783 * @param {!Uint8Array} buffer The buffer to scan.
784 * @param {number} start The starting point in the buffer to scan.
785 * @param {number} end The end point in the buffer to scan.
786 * @param {number} tag The tag value to count.
787 * @param {number} stride The number of bytes to skip per field.
788 * @return {number} The number of fields with a matching tag in the buffer.
789 * @private
790 */
791jspb.utils.countFixedFields_ =
792    function(buffer, start, end, tag, stride) {
793  var count = 0;
794  var cursor = start;
795
796  if (tag < 128) {
797    // Single-byte field tag, we can use a slightly quicker count.
798    while (cursor < end) {
799      // Skip the field tag, or exit if we find a non-matching tag.
800      if (buffer[cursor++] != tag) return count;
801
802      // Field tag matches, we've found a valid field.
803      count++;
804
805      // Skip the value.
806      cursor += stride;
807    }
808  } else {
809    while (cursor < end) {
810      // Skip the field tag, or exit if we find a non-matching tag.
811      var temp = tag;
812      while (temp > 128) {
813        if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
814        temp >>= 7;
815      }
816      if (buffer[cursor++] != temp) return count;
817
818      // Field tag matches, we've found a valid field.
819      count++;
820
821      // Skip the value.
822      cursor += stride;
823    }
824  }
825  return count;
826};
827
828
829/**
830 * Counts the number of contiguous fixed32 fields with the given field number
831 * in the buffer.
832 * @param {!Uint8Array} buffer The buffer to scan.
833 * @param {number} start The starting point in the buffer to scan.
834 * @param {number} end The end point in the buffer to scan.
835 * @param {number} field The field number to count.
836 * @return {number} The number of matching fields in the buffer.
837 */
838jspb.utils.countFixed32Fields = function(buffer, start, end, field) {
839  var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED32;
840  return jspb.utils.countFixedFields_(buffer, start, end, tag, 4);
841};
842
843
844/**
845 * Counts the number of contiguous fixed64 fields with the given field number
846 * in the buffer.
847 * @param {!Uint8Array} buffer The buffer to scan.
848 * @param {number} start The starting point in the buffer to scan.
849 * @param {number} end The end point in the buffer to scan.
850 * @param {number} field The field number to count
851 * @return {number} The number of matching fields in the buffer.
852 */
853jspb.utils.countFixed64Fields = function(buffer, start, end, field) {
854  var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED64;
855  return jspb.utils.countFixedFields_(buffer, start, end, tag, 8);
856};
857
858
859/**
860 * Counts the number of contiguous delimited fields with the given field number
861 * in the buffer.
862 * @param {!Uint8Array} buffer The buffer to scan.
863 * @param {number} start The starting point in the buffer to scan.
864 * @param {number} end The end point in the buffer to scan.
865 * @param {number} field The field number to count.
866 * @return {number} The number of matching fields in the buffer.
867 */
868jspb.utils.countDelimitedFields = function(buffer, start, end, field) {
869  var count = 0;
870  var cursor = start;
871  var tag = field * 8 + jspb.BinaryConstants.WireType.DELIMITED;
872
873  while (cursor < end) {
874    // Skip the field tag, or exit if we find a non-matching tag.
875    var temp = tag;
876    while (temp > 128) {
877      if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
878      temp >>= 7;
879    }
880    if (buffer[cursor++] != temp) return count;
881
882    // Field tag matches, we've found a valid field.
883    count++;
884
885    // Decode the length prefix.
886    var length = 0;
887    var shift = 1;
888    while (1) {
889      temp = buffer[cursor++];
890      length += (temp & 0x7f) * shift;
891      shift *= 128;
892      if ((temp & 0x80) == 0) break;
893    }
894
895    // Advance the cursor past the blob.
896    cursor += length;
897  }
898  return count;
899};
900
901
902/**
903 * String-ify bytes for text format. Should be optimized away in non-debug.
904 * The returned string uses \xXX escapes for all values and is itself quoted.
905 * [1, 31] serializes to '"\x01\x1f"'.
906 * @param {jspb.ByteSource} byteSource The bytes to serialize.
907 * @return {string} Stringified bytes for text format.
908 */
909jspb.utils.debugBytesToTextFormat = function(byteSource) {
910  var s = '"';
911  if (byteSource) {
912    var bytes = jspb.utils.byteSourceToUint8Array(byteSource);
913    for (var i = 0; i < bytes.length; i++) {
914      s += '\\x';
915      if (bytes[i] < 16) s += '0';
916      s += bytes[i].toString(16);
917    }
918  }
919  return s + '"';
920};
921
922
923/**
924 * String-ify a scalar for text format. Should be optimized away in non-debug.
925 * @param {string|number|boolean} scalar The scalar to stringify.
926 * @return {string} Stringified scalar for text format.
927 */
928jspb.utils.debugScalarToTextFormat = function(scalar) {
929  if (goog.isString(scalar)) {
930    return goog.string.quote(scalar);
931  } else {
932    return scalar.toString();
933  }
934};
935
936
937/**
938 * Utility function: convert a string with codepoints 0--255 inclusive to a
939 * Uint8Array. If any codepoints greater than 255 exist in the string, throws an
940 * exception.
941 * @param {string} str
942 * @return {!Uint8Array}
943 */
944jspb.utils.stringToByteArray = function(str) {
945  var arr = new Uint8Array(str.length);
946  for (var i = 0; i < str.length; i++) {
947    var codepoint = str.charCodeAt(i);
948    if (codepoint > 255) {
949      throw new Error('Conversion error: string contains codepoint ' +
950                      'outside of byte range');
951    }
952    arr[i] = codepoint;
953  }
954  return arr;
955};
956
957
958/**
959 * Converts any type defined in jspb.ByteSource into a Uint8Array.
960 * @param {!jspb.ByteSource} data
961 * @return {!Uint8Array}
962 * @suppress {invalidCasts}
963 */
964jspb.utils.byteSourceToUint8Array = function(data) {
965  if (data.constructor === Uint8Array) {
966    return /** @type {!Uint8Array} */(data);
967  }
968
969  if (data.constructor === ArrayBuffer) {
970    data = /** @type {!ArrayBuffer} */(data);
971    return /** @type {!Uint8Array} */(new Uint8Array(data));
972  }
973
974  if (typeof Buffer != 'undefined' && data.constructor === Buffer) {
975    return /** @type {!Uint8Array} */ (
976        new Uint8Array(/** @type {?} */ (data)));
977  }
978
979  if (data.constructor === Array) {
980    data = /** @type {!Array<number>} */(data);
981    return /** @type {!Uint8Array} */(new Uint8Array(data));
982  }
983
984  if (data.constructor === String) {
985    data = /** @type {string} */(data);
986    return goog.crypt.base64.decodeStringToUint8Array(data);
987  }
988
989  goog.asserts.fail('Type not convertible to Uint8Array.');
990  return /** @type {!Uint8Array} */(new Uint8Array(0));
991};
992