diff --git a/BUILD.bazel b/BUILD.bazel index 2b4b0e3..5483303 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -27,6 +27,7 @@ pkg_files( "package.json", "README.md", "LICENSE.md", + "LICENSE-asserts.md", ], strip_prefix = strip_prefix.from_root(""), ) diff --git a/LICENSE-asserts.md b/LICENSE-asserts.md new file mode 100644 index 0000000..d9a10c0 --- /dev/null +++ b/LICENSE-asserts.md @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/asserts.js b/asserts.js new file mode 100644 index 0000000..b4a1e5f --- /dev/null +++ b/asserts.js @@ -0,0 +1,159 @@ +/** + * @license + * Copyright The Closure Library Authors. + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview Utilities to check the preconditions, postconditions and + * invariants runtime. + */ + +goog.provide('jspb.asserts'); + +/** + * Throws an exception with the given message and "Assertion failed" prefixed + * onto it. + * @param {string} defaultMessage The message to use if givenMessage is empty. + * @param {?Array<*>} defaultArgs The substitution arguments for defaultMessage. + * @param {string|undefined} givenMessage Message supplied by the caller. + * @param {!Array<*>} givenArgs The substitution arguments for givenMessage. + * @throws {Error} When the value is not a number. + */ +jspb.asserts.doAssertFailure = function(defaultMessage, defaultArgs, givenMessage, givenArgs) { + let message = 'Assertion failed'; + let args; + if (givenMessage) { + message += ': ' + givenMessage; + args = givenArgs; + } else if (defaultMessage) { + message += ': ' + defaultMessage; + args = defaultArgs; + } + // The '' + works around an Opera 10 bug in the unit tests. Without it, + // a stack trace is added to var message above. With this, a stack trace is + // not added until this line (it causes the extra garbage to be added after + // the assertion message instead of in the middle of it). + throw new Error('' + message, args || []); +} + +/** + * Checks if the condition evaluates to true. + * @template T + * @param {T} condition The condition to check. + * @param {string=} opt_message Error message in case of failure. + * @param {...*} args The items to substitute into the failure message. + * @return {T} The value of the condition. + * @throws {Error} When the condition evaluates to false. + */ + +jspb.asserts.assert = function(condition, opt_message, ...args) { + if (!condition) { + jspb.asserts.doAssertFailure('', null, opt_message, args); + } + return condition; +}; + + +/** + * Checks if the value is a string. + * @param {*} value The value to check. + * @param {string=} opt_message Error message in case of failure. + * @param {...*} args The items to substitute into the failure message. + * @return {string} The value, guaranteed to be a string when asserts enabled. + * @throws {Error} When the value is not a string. + */ +jspb.asserts.assertString = function(value, opt_message, ...args) { + if (typeof value !== 'string') { + jspb.asserts.doAssertFailure( + 'Expected string but got %s: %s.', [goog.typeOf(value), value], + opt_message, args); + } + return /** @type {string} */ (value); +}; + + +/** + * Checks if the value is an Array. + * @param {*} value The value to check. + * @param {string=} opt_message Error message in case of failure. + * @param {...*} args The items to substitute into the failure message. + * @return {!Array>} The value, guaranteed to be a non-null array. + * @throws {Error} When the value is not an array. + */ +jspb.asserts.assertArray = function(value, opt_message, ...args) { + if (!Array.isArray(value)) { + jspb.asserts.doAssertFailure( + 'Expected array but got %s: %s.', [goog.typeOf(value), value], + opt_message, args); + } + return /** @type {!Array>} */ (value); +}; + +/** + * Triggers a failure. This function is useful in case when we want to add a + * check in the unreachable area like switch-case statement: + * + *
+ * switch(type) { + * case FOO: doSomething(); break; + * case BAR: doSomethingElse(); break; + * default: jspb.asserts.JspbFail('Unrecognized type: ' + type); + * // We have only 2 types - "default:" section is unreachable code. + * } + *+ * + * @param {string=} opt_message Error message in case of failure. + * @param {...*} args The items to substitute into the failure message. + * @return {void} + * @throws {Error} Failure. + */ +jspb.asserts.fail = function(opt_message, ...args) { + throw new Error( + 'Failure' + (opt_message ? ': ' + opt_message : ''), + args); +}; + +/** + * Checks if the value is an instance of the user-defined type. + * + * Do not use this to ensure a value is an HTMLElement or a subclass! Cross- + * document DOM inherits from separate - though identical - browser classes, and + * such a check will unexpectedly fail. + * + * @param {?} value The value to check. + * @param {function(new: T, ...)} type A user-defined constructor. + * @param {string=} opt_message Error message in case of failure. + * @param {...*} args The items to substitute into the failure message. + * @throws {Error} When the value is not an instance of + * type. + * @return {T} + * @template T + */ +jspb.asserts.assertInstanceof = function(value, type, opt_message, ...args) { + if (!(value instanceof type)) { + jspb.assert.doAssertFailure( + 'Expected instanceof %s but got %s.', + [jspb.asserts.getType(type), jspb.asseerts.getType(value)], + opt_message, args); + } + return value; +}; + +/** + * Returns the type of a value. If a constructor is passed, and a suitable + * string cannot be found, 'unknown type name' will be returned. + * @param {*} value A constructor, object, or primitive. + * @return {string} The best display name for the value, or 'unknown type name'. + * @private + */ +jspb.asserts.getType = function(value) { + if (value instanceof Function) { + return value.displayName || value.name || 'unknown type name'; + } else if (value instanceof Object) { + return /** @type {string} */ (value.constructor.displayName) || + value.constructor.name || Object.prototype.toString.call(value); + } else { + return value === null ? 'null' : typeof value; + } +} diff --git a/binary/arith_test.js b/binary/arith_test.js index dd5791a..37d42ff 100644 --- a/binary/arith_test.js +++ b/binary/arith_test.js @@ -45,8 +45,8 @@ describe('binaryArithTest', function() { * Tests comparison operations. */ it('testCompare', function() { - var a = new jspb.arith.UInt64(1234, 5678); - var b = new jspb.arith.UInt64(1234, 5678); + const a = new jspb.arith.UInt64(1234, 5678); + const b = new jspb.arith.UInt64(1234, 5678); expect(a.cmp(b)).toEqual(0); expect(b.cmp(a)).toEqual(0); b.lo -= 1; @@ -78,10 +78,10 @@ describe('binaryArithTest', function() { * Tests shifts. */ it('testShifts', function() { - var a = new jspb.arith.UInt64(1, 0); + let a = new jspb.arith.UInt64(1, 0); expect(a.lo).toEqual(1); expect(a.hi).toEqual(0); - var orig = a; + const orig = a; a = a.leftShift(); expect(orig.lo).toEqual(1); // original unmodified. expect(orig.hi).toEqual(0); @@ -90,7 +90,7 @@ describe('binaryArithTest', function() { a = a.leftShift(); expect(a.lo).toEqual(4); expect(a.hi).toEqual(0); - for (var i = 0; i < 29; i++) { + for (let i = 0; i < 29; i++) { a = a.leftShift(); } expect(a.lo).toEqual(0x80000000); @@ -115,12 +115,14 @@ describe('binaryArithTest', function() { * Tests additions. */ it('testAdd', function() { - var a = new jspb.arith.UInt64(/* lo = */ 0x89abcdef, - /* hi = */ 0x01234567); - var b = new jspb.arith.UInt64(/* lo = */ 0xff52ab91, - /* hi = */ 0x92fa2123); + const a = new jspb.arith.UInt64( + /* lo = */ 0x89abcdef, + /* hi = */ 0x01234567); + const b = new jspb.arith.UInt64( + /* lo = */ 0xff52ab91, + /* hi = */ 0x92fa2123); // Addition with carry. - var c = a.add(b); + let c = a.add(b); expect(a.lo).toEqual(0x89abcdef); // originals unmodified. expect(a.hi).toEqual(0x01234567); expect(b.lo).toEqual(0xff52ab91); @@ -143,32 +145,20 @@ describe('binaryArithTest', function() { * Test subtractions. */ it('testSub', function() { - var kLength = 10; - var hiValues = [0x1682ef32, - 0x583902f7, - 0xb62f5955, - 0x6ea99bbf, - 0x25a39c20, - 0x0700a08b, - 0x00f7304d, - 0x91a5b5af, - 0x89077fd2, - 0xe09e347c]; - var loValues = [0xe1538b18, - 0xbeacd556, - 0x74100758, - 0x96e3cb26, - 0x56c37c3f, - 0xe00b3f7d, - 0x859f25d7, - 0xc2ee614a, - 0xe1d21cd7, - 0x30aae6a4]; - for (var i = 0; i < kLength; i++) { - for (var j = 0; j < kLength; j++) { - var a = new jspb.arith.UInt64(loValues[i], hiValues[j]); - var b = new jspb.arith.UInt64(loValues[j], hiValues[i]); - var c = a.add(b).sub(b); + const kLength = 10; + const hiValues = [ + 0x1682ef32, 0x583902f7, 0xb62f5955, 0x6ea99bbf, 0x25a39c20, 0x0700a08b, + 0x00f7304d, 0x91a5b5af, 0x89077fd2, 0xe09e347c + ]; + const loValues = [ + 0xe1538b18, 0xbeacd556, 0x74100758, 0x96e3cb26, 0x56c37c3f, 0xe00b3f7d, + 0x859f25d7, 0xc2ee614a, 0xe1d21cd7, 0x30aae6a4 + ]; + for (let i = 0; i < kLength; i++) { + for (let j = 0; j < kLength; j++) { + const a = new jspb.arith.UInt64(loValues[i], hiValues[j]); + const b = new jspb.arith.UInt64(loValues[j], hiValues[i]); + const c = a.add(b).sub(b); expect(c.hi).toEqual(a.hi); expect(c.lo).toEqual(a.lo); } @@ -180,7 +170,7 @@ describe('binaryArithTest', function() { * Tests 32-by-32 multiplication. */ it('testMul32x32', function() { - var testData = [ + const testData = [ // a b low(a*b) high(a*b) [0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8], [0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc], @@ -194,12 +184,12 @@ describe('binaryArithTest', function() { [0x0dd0bfa9, 0x916e27b1, 0x6e2542d9, 0x07d92e65] ]; - for (var i = 0; i < testData.length; i++) { - var a = testData[i][0] >>> 0; - var b = testData[i][1] >>> 0; - var cLow = testData[i][2] >>> 0; - var cHigh = testData[i][3] >>> 0; - var c = jspb.arith.UInt64.mul32x32(a, b); + for (let i = 0; i < testData.length; i++) { + const a = testData[i][0] >>> 0; + const b = testData[i][1] >>> 0; + const cLow = testData[i][2] >>> 0; + const cHigh = testData[i][3] >>> 0; + const c = jspb.arith.UInt64.mul32x32(a, b); expect(c.lo).toEqual(cLow); expect(c.hi).toEqual(cHigh); } @@ -213,7 +203,7 @@ describe('binaryArithTest', function() { // 64x32 bits produces 96 bits of product. The multiplication function under // test truncates the top 32 bits, so we compare against a 64-bit expected // product. - var testData = [ + const testData = [ // low(a) high(a) low(a*b) high(a*b) [0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f], [0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b], @@ -227,9 +217,9 @@ describe('binaryArithTest', function() { [0xe4f2ce21, 0x2e74b7bd, 0xd801b38b, 0xbc17feeb, 0xc6c44e0f] ]; - for (var i = 0; i < testData.length; i++) { - var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); - var prod = a.mul(testData[i][2]); + for (let i = 0; i < testData.length; i++) { + const a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); + const prod = a.mul(testData[i][2]); expect(prod.lo).toEqual(testData[i][3]); expect(prod.hi).toEqual(testData[i][4]); } @@ -241,7 +231,7 @@ describe('binaryArithTest', function() { */ it('testDiv', function() { // Compute a/b, yielding quot = a/b and rem = a%b. - var testData = [ + const testData = [ // --- divisors in (0, 2^32-1) to test full divisor range // low(a) high(a) b low(quot) high(quot) rem [0x712443f1, 0xe85cefcc, 0xc1a7050b, 0x332c79ad, 0x00000001, 0x92ffa882], @@ -268,11 +258,11 @@ describe('binaryArithTest', function() { [0x7179a74c, 0x46083fff, 0x0000253c, 0x4d39ba6e, 0x0001e17f, 0x00000f84] ]; - for (var i = 0; i < testData.length; i++) { - var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); - var result = a.div(testData[i][2]); - var quotient = result[0]; - var remainder = result[1]; + for (let i = 0; i < testData.length; i++) { + const a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); + const result = a.div(testData[i][2]); + const quotient = result[0]; + const remainder = result[1]; expect(quotient.lo).toEqual(testData[i][3]); expect(quotient.hi).toEqual(testData[i][4]); expect(remainder.lo).toEqual(testData[i][5]); @@ -284,32 +274,32 @@ describe('binaryArithTest', function() { * Tests .toString() and .fromString(). */ it('testStrings', function() { - var testData = [ - [0x5e84c935, 0xcae33d0e, '14619595947299359029'], - [0x62b3b8b8, 0x93480544, '10612738313170434232'], - [0x319bfb13, 0xc01c4172, '13843011313344445203'], - [0x5b8a65fb, 0xa5885b31, '11927883880638080507'], - [0x6bdb80f1, 0xb0d1b16b, '12741159895737008369'], - [0x4b82b442, 0x2e0d8c97, '3318463081876730946'], - [0x780d5208, 0x7d76752c, '9040542135845999112'], - [0x2e46800f, 0x0993778d, '690026616168284175'], - [0xf00a7e32, 0xcd8e3931, '14811839111111540274'], - [0x1baeccd6, 0x923048c4, '10533999535534820566'], - [0x03669d29, 0xbff3ab72, '13831587386756603177'], - [0x2526073e, 0x01affc81, '121593346566522686'], - [0xc24244e0, 0xd7f40d0e, '15561076969511732448'], - [0xc56a341e, 0xa68b66a7, '12000798502816461854'], - [0x8738d64d, 0xbfe78604, '13828168534871037517'], - [0x5baff03b, 0xd7572aea, '15516918227177304123'], - [0x4a843d8a, 0x864e132b, '9677693725920476554'], - [0x25b4e94d, 0x22b54dc6, '2500990681505655117'], - [0x6bbe664b, 0x55a5cc0e, '6171563226690381387'], - [0xee916c81, 0xb00aabb3, '12685140089732426881'] + const testData = [ + [0x5e84c935, 0xcae33d0e, '14619595947299359029'], + [0x62b3b8b8, 0x93480544, '10612738313170434232'], + [0x319bfb13, 0xc01c4172, '13843011313344445203'], + [0x5b8a65fb, 0xa5885b31, '11927883880638080507'], + [0x6bdb80f1, 0xb0d1b16b, '12741159895737008369'], + [0x4b82b442, 0x2e0d8c97, '3318463081876730946'], + [0x780d5208, 0x7d76752c, '9040542135845999112'], + [0x2e46800f, 0x0993778d, '690026616168284175'], + [0xf00a7e32, 0xcd8e3931, '14811839111111540274'], + [0x1baeccd6, 0x923048c4, '10533999535534820566'], + [0x03669d29, 0xbff3ab72, '13831587386756603177'], + [0x2526073e, 0x01affc81, '121593346566522686'], + [0xc24244e0, 0xd7f40d0e, '15561076969511732448'], + [0xc56a341e, 0xa68b66a7, '12000798502816461854'], + [0x8738d64d, 0xbfe78604, '13828168534871037517'], + [0x5baff03b, 0xd7572aea, '15516918227177304123'], + [0x4a843d8a, 0x864e132b, '9677693725920476554'], + [0x25b4e94d, 0x22b54dc6, '2500990681505655117'], + [0x6bbe664b, 0x55a5cc0e, '6171563226690381387'], + [0xee916c81, 0xb00aabb3, '12685140089732426881'] ]; - for (var i = 0; i < testData.length; i++) { - var a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); - var roundtrip = jspb.arith.UInt64.fromString(a.toString()); + for (let i = 0; i < testData.length; i++) { + const a = new jspb.arith.UInt64(testData[i][0], testData[i][1]); + const roundtrip = jspb.arith.UInt64.fromString(a.toString()); expect(roundtrip.lo).toEqual(a.lo); expect(roundtrip.hi).toEqual(a.hi); expect(a.toString()).toEqual(testData[i][2]); @@ -322,32 +312,18 @@ describe('binaryArithTest', function() { * the explicit overrides: .toString() and .fromString(). */ it('testSignedInt64', function() { - var testStrings = [ - '-7847499644178593666', - '3771946501229139523', - '2872856549054995060', - '-5780049594274350904', - '3383785956695105201', - '2973055184857072610', - '-3879428459215627206', - '4589812431064156631', - '8484075557333689940', - '1075325817098092407', - '-4346697501012292314', - '2488620459718316637', - '6112655187423520672', - '-3655278273928612104', - '3439154019435803196', - '1004112478843763757', - '-6587790776614368413', - '664320065099714586', - '4760412909973292912', - '-7911903989602274672' + const testStrings = [ + '-7847499644178593666', '3771946501229139523', '2872856549054995060', + '-5780049594274350904', '3383785956695105201', '2973055184857072610', + '-3879428459215627206', '4589812431064156631', '8484075557333689940', + '1075325817098092407', '-4346697501012292314', '2488620459718316637', + '6112655187423520672', '-3655278273928612104', '3439154019435803196', + '1004112478843763757', '-6587790776614368413', '664320065099714586', + '4760412909973292912', '-7911903989602274672' ]; - for (var i = 0; i < testStrings.length; i++) { - var roundtrip = - jspb.arith.Int64.fromString(testStrings[i]).toString(); + for (let i = 0; i < testStrings.length; i++) { + const roundtrip = jspb.arith.Int64.fromString(testStrings[i]).toString(); expect(roundtrip).toEqual(testStrings[i]); } }); diff --git a/binary/decoder.js b/binary/decoder.js index 8f4cb3a..eaa0082 100644 --- a/binary/decoder.js +++ b/binary/decoder.js @@ -46,7 +46,7 @@ goog.provide('jspb.BinaryDecoder'); -goog.require('goog.asserts'); +goog.require('jspb.asserts'); goog.require('goog.crypt'); goog.require('jspb.utils'); @@ -145,8 +145,8 @@ jspb.BinaryDecoder.prototype.free = function() { * @return {!jspb.BinaryDecoder} */ jspb.BinaryDecoder.prototype.clone = function() { - return jspb.BinaryDecoder.alloc(this.bytes_, - this.start_, this.end_ - this.start_); + return jspb.BinaryDecoder.alloc( + this.bytes_, this.start_, this.end_ - this.start_); }; @@ -178,8 +178,7 @@ jspb.BinaryDecoder.prototype.getBuffer = function() { * @param {number=} opt_length The optional length of the block to read - * we'll throw an assertion if we go off the end of the block. */ -jspb.BinaryDecoder.prototype.setBlock = - function(data, opt_start, opt_length) { +jspb.BinaryDecoder.prototype.setBlock = function(data, opt_start, opt_length) { this.bytes_ = jspb.utils.byteSourceToUint8Array(data); this.start_ = (opt_start !== undefined) ? opt_start : 0; this.end_ = (opt_length !== undefined) ? this.start_ + opt_length : @@ -236,7 +235,7 @@ jspb.BinaryDecoder.prototype.setCursor = function(cursor) { */ jspb.BinaryDecoder.prototype.advance = function(count) { this.cursor_ += count; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); }; @@ -263,9 +262,7 @@ jspb.BinaryDecoder.prototype.pastEnd = function() { * @return {boolean} */ jspb.BinaryDecoder.prototype.getError = function() { - return this.error_ || - (this.cursor_ < 0) || - (this.cursor_ > this.end_); + return this.error_ || (this.cursor_ < 0) || (this.cursor_ > this.end_); }; @@ -319,7 +316,7 @@ jspb.BinaryDecoder.prototype.readSplitVarint64 = function(convert) { } // If we did not see the terminator, the encoding was invalid. - goog.asserts.fail('Failed to read varint, encoding is invalid.'); + jspb.asserts.fail('Failed to read varint, encoding is invalid.'); this.error_ = true; }; @@ -425,7 +422,7 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() { var x = (temp & 0x7F); if (temp < 128) { this.cursor_ += 1; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return x; } @@ -433,7 +430,7 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() { x |= (temp & 0x7F) << 7; if (temp < 128) { this.cursor_ += 2; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return x; } @@ -441,7 +438,7 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() { x |= (temp & 0x7F) << 14; if (temp < 128) { this.cursor_ += 3; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return x; } @@ -449,7 +446,7 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() { x |= (temp & 0x7F) << 21; if (temp < 128) { this.cursor_ += 4; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return x; } @@ -459,23 +456,21 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() { // We're reading the high bits of an unsigned varint. The byte we just read // also contains bits 33 through 35, which we're going to discard. this.cursor_ += 5; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return x >>> 0; } // If we get here, we need to truncate coming bytes. However we need to make // sure cursor place is correct. this.cursor_ += 5; - if (bytes[this.cursor_++] >= 128 && - bytes[this.cursor_++] >= 128 && - bytes[this.cursor_++] >= 128 && - bytes[this.cursor_++] >= 128 && + if (bytes[this.cursor_++] >= 128 && bytes[this.cursor_++] >= 128 && + bytes[this.cursor_++] >= 128 && bytes[this.cursor_++] >= 128 && bytes[this.cursor_++] >= 128) { // If we get here, the varint is too long. - goog.asserts.assert(false); + jspb.asserts.assert(false); } - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return x; }; @@ -485,19 +480,21 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() { * * @return {number} The decoded signed 32-bit varint. */ -jspb.BinaryDecoder.prototype.readSignedVarint32 = function() { - // The `~` operator coerces to int32, and `~~` is the shortest expression of a cast. - // This has some edge cases (e.g. NaN becomes 0) but should be okay here. +jspb.BinaryDecoder.prototype.readSignedVarint32 = + function() { + // The `~` operator coerces to int32, and `~~` is the shortest expression of a + // cast. This has some edge cases (e.g. NaN becomes 0) but should be okay + // here. return ~~(this.readUnsignedVarint32()); } -/** - * Reads a 32-bit unsigned variant and returns its value as a string. - * - * @return {string} The decoded unsigned 32-bit varint as a string. - */ -jspb.BinaryDecoder.prototype.readUnsignedVarint32String = function() { + /** + * Reads a 32-bit unsigned variant and returns its value as a string. + * + * @return {string} The decoded unsigned 32-bit varint as a string. + */ + jspb.BinaryDecoder.prototype.readUnsignedVarint32String = function() { // 32-bit integers fit in JavaScript numbers without loss of precision, so // string variants of 32-bit varint readers can simply delegate then convert // to string. @@ -531,7 +528,7 @@ jspb.BinaryDecoder.prototype.readSignedVarint32String = function() { */ jspb.BinaryDecoder.prototype.readZigzagVarint32 = function() { var result = this.readUnsignedVarint32(); - return (result >>> 1) ^ - (result & 1); + return (result >>> 1) ^ -(result & 1); }; @@ -641,7 +638,7 @@ jspb.BinaryDecoder.prototype.readZigzagVarint64String = function() { jspb.BinaryDecoder.prototype.readUint8 = function() { var a = this.bytes_[this.cursor_ + 0]; this.cursor_ += 1; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return a; }; @@ -655,7 +652,7 @@ jspb.BinaryDecoder.prototype.readUint16 = function() { var a = this.bytes_[this.cursor_ + 0]; var b = this.bytes_[this.cursor_ + 1]; this.cursor_ += 2; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return (a << 0) | (b << 8); }; @@ -671,7 +668,7 @@ jspb.BinaryDecoder.prototype.readUint32 = function() { var c = this.bytes_[this.cursor_ + 2]; var d = this.bytes_[this.cursor_ + 3]; this.cursor_ += 4; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return ((a << 0) | (b << 8) | (c << 16) | (d << 24)) >>> 0; }; @@ -713,7 +710,7 @@ jspb.BinaryDecoder.prototype.readUint64String = function() { jspb.BinaryDecoder.prototype.readInt8 = function() { var a = this.bytes_[this.cursor_ + 0]; this.cursor_ += 1; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return (a << 24) >> 24; }; @@ -727,7 +724,7 @@ jspb.BinaryDecoder.prototype.readInt16 = function() { var a = this.bytes_[this.cursor_ + 0]; var b = this.bytes_[this.cursor_ + 1]; this.cursor_ += 2; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return (((a << 0) | (b << 8)) << 16) >> 16; }; @@ -743,7 +740,7 @@ jspb.BinaryDecoder.prototype.readInt32 = function() { var c = this.bytes_[this.cursor_ + 2]; var d = this.bytes_[this.cursor_ + 3]; this.cursor_ += 4; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return (a << 0) | (b << 8) | (c << 16) | (d << 24); }; @@ -839,27 +836,28 @@ jspb.BinaryDecoder.prototype.readString = function(length) { var result = ''; while (cursor < end) { var c = bytes[cursor++]; - if (c < 128) { // Regular 7-bit ASCII. + if (c < 128) { // Regular 7-bit ASCII. codeUnits.push(c); } else if (c < 192) { // UTF-8 continuation mark. We are out of sync. This // might happen if we attempted to read a character // with more than four bytes. continue; - } else if (c < 224) { // UTF-8 with two bytes. + } else if (c < 224) { // UTF-8 with two bytes. var c2 = bytes[cursor++]; codeUnits.push(((c & 31) << 6) | (c2 & 63)); - } else if (c < 240) { // UTF-8 with three bytes. + } else if (c < 240) { // UTF-8 with three bytes. var c2 = bytes[cursor++]; var c3 = bytes[cursor++]; codeUnits.push(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - } else if (c < 248) { // UTF-8 with 4 bytes. + } else if (c < 248) { // UTF-8 with 4 bytes. var c2 = bytes[cursor++]; var c3 = bytes[cursor++]; var c4 = bytes[cursor++]; // Characters written on 4 bytes have 21 bits for a codepoint. // We can't fit that on 16bit characters, so we use surrogates. - var codepoint = ((c & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63); + var codepoint = + ((c & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63); // Surrogates formula from wikipedia. // 1. Subtract 0x10000 from codepoint codepoint -= 0x10000; @@ -902,17 +900,16 @@ jspb.BinaryDecoder.prototype.readStringWithLength = function() { * length was invalid. */ jspb.BinaryDecoder.prototype.readBytes = function(length) { - if (length < 0 || - this.cursor_ + length > this.bytes_.length) { + if (length < 0 || this.cursor_ + length > this.bytes_.length) { this.error_ = true; - goog.asserts.fail('Invalid byte length!'); + jspb.asserts.fail('Invalid byte length!'); return new Uint8Array(0); } var result = this.bytes_.subarray(this.cursor_, this.cursor_ + length); this.cursor_ += length; - goog.asserts.assert(this.cursor_ <= this.end_); + jspb.asserts.assert(this.cursor_ <= this.end_); return result; }; diff --git a/binary/decoder_test.js b/binary/decoder_test.js index f97518e..20766b2 100644 --- a/binary/decoder_test.js +++ b/binary/decoder_test.js @@ -41,10 +41,10 @@ * @author aappleby@google.com (Austin Appleby) */ -goog.require('goog.testing.asserts'); goog.require('jspb.BinaryConstants'); goog.require('jspb.BinaryDecoder'); goog.require('jspb.BinaryEncoder'); + goog.require('jspb.utils'); @@ -57,9 +57,9 @@ goog.require('jspb.utils'); * @param {Function} filter * @suppress {missingProperties|visibility} */ -function doTestUnsignedValue(readValue, - writeValue, epsilon, upperLimit, filter) { - var encoder = new jspb.BinaryEncoder(); +function doTestUnsignedValue( + readValue, writeValue, epsilon, upperLimit, filter) { + const encoder = new jspb.BinaryEncoder(); // Encode zero and limits. writeValue.call(encoder, filter(0)); @@ -67,25 +67,29 @@ function doTestUnsignedValue(readValue, writeValue.call(encoder, filter(upperLimit)); // Encode positive values. - for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { + for (let cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { writeValue.call(encoder, filter(cursor)); } - var decoder = jspb.BinaryDecoder.alloc(encoder.end()); + const decoder = jspb.BinaryDecoder.alloc(encoder.end()); // Check zero and limits. - assertEquals(filter(0), readValue.call(decoder)); - assertEquals(filter(epsilon), readValue.call(decoder)); - assertEquals(filter(upperLimit), readValue.call(decoder)); + expect(readValue.call(decoder)).toEqual(filter(0)); + expect(readValue.call(decoder)).toEqual(filter(epsilon)); + expect(readValue.call(decoder)).toEqual(filter(upperLimit)); // Check positive values. - for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { + for (let cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { if (filter(cursor) != readValue.call(decoder)) throw 'fail!'; } // Encoding values outside the valid range should assert. - assertThrows(function() {writeValue.call(encoder, -1);}); - assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);}); + expect(() => { + writeValue.call(encoder, -1); + }).toThrow(); + expect(() => { + writeValue.call(encoder, upperLimit * 1.1); + }).toThrow(); } @@ -99,9 +103,9 @@ function doTestUnsignedValue(readValue, * @param {Function} filter * @suppress {missingProperties} */ -function doTestSignedValue(readValue, - writeValue, epsilon, lowerLimit, upperLimit, filter) { - var encoder = new jspb.BinaryEncoder(); +function doTestSignedValue( + readValue, writeValue, epsilon, lowerLimit, upperLimit, filter) { + const encoder = new jspb.BinaryEncoder(); // Encode zero and limits. writeValue.call(encoder, filter(lowerLimit)); @@ -110,39 +114,39 @@ function doTestSignedValue(readValue, writeValue.call(encoder, filter(epsilon)); writeValue.call(encoder, filter(upperLimit)); - var inputValues = []; + const inputValues = []; // Encode negative values. - for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) { - var val = filter(cursor); + for (let cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) { + let val = filter(cursor); writeValue.call(encoder, val); inputValues.push(val); } // Encode positive values. - for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { - var val = filter(cursor); + for (let cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { + const val = filter(cursor); writeValue.call(encoder, val); inputValues.push(val); } - var decoder = jspb.BinaryDecoder.alloc(encoder.end()); + const decoder = jspb.BinaryDecoder.alloc(encoder.end()); // Check zero and limits. - assertEquals(filter(lowerLimit), readValue.call(decoder)); - assertEquals(filter(-epsilon), readValue.call(decoder)); - assertEquals(filter(0), readValue.call(decoder)); - assertEquals(filter(epsilon), readValue.call(decoder)); - assertEquals(filter(upperLimit), readValue.call(decoder)); + expect(readValue.call(decoder)).toEqual(filter(lowerLimit)); + expect(readValue.call(decoder)).toEqual(filter(-epsilon)); + expect(readValue.call(decoder)).toEqual(filter(0)); + expect(readValue.call(decoder)).toEqual(filter(epsilon)); + expect(readValue.call(decoder)).toEqual(filter(upperLimit)); // Verify decoded values. - for (var i = 0; i < inputValues.length; i++) { - assertEquals(inputValues[i], readValue.call(decoder)); + for (let i = 0; i < inputValues.length; i++) { + expect(readValue.call(decoder)).toEqual(inputValues[i]); } // Encoding values outside the valid range should assert. - var pastLowerLimit = lowerLimit * 1.1; - var pastUpperLimit = upperLimit * 1.1; + const pastLowerLimit = lowerLimit * 1.1; + const pastUpperLimit = upperLimit * 1.1; if (pastLowerLimit !== -Infinity) { expect(() => void writeValue.call(encoder, pastLowerLimit)).toThrow(); } @@ -151,11 +155,11 @@ function doTestSignedValue(readValue, } } -describe('binaryDecoderTest', function() { +describe('binaryDecoderTest', () => { /** * Tests the decoder instance cache. */ - it('testInstanceCache', /** @suppress {visibility} */ function() { + it('testInstanceCache', /** @suppress {visibility} */ () => { // Empty the instance caches. jspb.BinaryDecoder.instanceCache_ = []; @@ -163,35 +167,35 @@ describe('binaryDecoderTest', function() { // cache. jspb.BinaryDecoder.alloc().free(); - assertEquals(1, jspb.BinaryDecoder.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(1); // Allocating and then freeing three decoders should leave us with three in // the cache. - var decoder1 = jspb.BinaryDecoder.alloc(); - var decoder2 = jspb.BinaryDecoder.alloc(); - var decoder3 = jspb.BinaryDecoder.alloc(); + const decoder1 = jspb.BinaryDecoder.alloc(); + const decoder2 = jspb.BinaryDecoder.alloc(); + const decoder3 = jspb.BinaryDecoder.alloc(); decoder1.free(); decoder2.free(); decoder3.free(); - assertEquals(3, jspb.BinaryDecoder.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(3); }); - describe('varint64', function() { - var /** !jspb.BinaryEncoder */ encoder; - var /** !jspb.BinaryDecoder */ decoder; + describe('varint64', () => { + let /** !jspb.BinaryEncoder */ encoder; + let /** !jspb.BinaryDecoder */ decoder; - var hashA = String.fromCharCode(0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00); - var hashB = String.fromCharCode(0x12, 0x34, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00); - var hashC = String.fromCharCode(0x12, 0x34, 0x56, 0x78, - 0x87, 0x65, 0x43, 0x21); - var hashD = String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF); - beforeEach(function() { + const hashA = + String.fromCharCode(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); + const hashB = + String.fromCharCode(0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); + const hashC = + String.fromCharCode(0x12, 0x34, 0x56, 0x78, 0x87, 0x65, 0x43, 0x21); + const hashD = + String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF); + beforeEach(() => { encoder = new jspb.BinaryEncoder(); encoder.writeVarintHash64(hashA); @@ -207,19 +211,19 @@ describe('binaryDecoderTest', function() { decoder = jspb.BinaryDecoder.alloc(encoder.end()); }); - it('reads 64-bit integers as hash strings', function() { - assertEquals(hashA, decoder.readVarintHash64()); - assertEquals(hashB, decoder.readVarintHash64()); - assertEquals(hashC, decoder.readVarintHash64()); - assertEquals(hashD, decoder.readVarintHash64()); + it('reads 64-bit integers as hash strings', () => { + expect(hashA).toEqual(decoder.readVarintHash64()); + expect(hashB).toEqual(decoder.readVarintHash64()); + expect(hashC).toEqual(decoder.readVarintHash64()); + expect(hashD).toEqual(decoder.readVarintHash64()); - assertEquals(hashA, decoder.readFixedHash64()); - assertEquals(hashB, decoder.readFixedHash64()); - assertEquals(hashC, decoder.readFixedHash64()); - assertEquals(hashD, decoder.readFixedHash64()); + expect(hashA).toEqual(decoder.readFixedHash64()); + expect(hashB).toEqual(decoder.readFixedHash64()); + expect(hashC).toEqual(decoder.readFixedHash64()); + expect(hashD).toEqual(decoder.readFixedHash64()); }); - it('reads split 64 bit integers', function() { + it('reads split 64 bit integers', () => { function hexJoin(bitsLow, bitsHigh) { return `0x${(bitsHigh >>> 0).toString(16)}:0x${ (bitsLow >>> 0).toString(16)}`; @@ -241,19 +245,19 @@ describe('binaryDecoderTest', function() { }); }); - describe('sint64', function() { - var /** !jspb.BinaryDecoder */ decoder; + describe('sint64', () => { + let /** !jspb.BinaryDecoder */ decoder; - var hashA = + const hashA = String.fromCharCode(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); - var hashB = + const hashB = String.fromCharCode(0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); - var hashC = + const hashC = String.fromCharCode(0x12, 0x34, 0x56, 0x78, 0x87, 0x65, 0x43, 0x21); - var hashD = + const hashD = String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF); - beforeEach(function() { - var encoder = new jspb.BinaryEncoder(); + beforeEach(() => { + const encoder = new jspb.BinaryEncoder(); encoder.writeZigzagVarintHash64(hashA); encoder.writeZigzagVarintHash64(hashB); @@ -263,7 +267,7 @@ describe('binaryDecoderTest', function() { decoder = jspb.BinaryDecoder.alloc(encoder.end()); }); - it('reads 64-bit integers as decimal strings', function() { + it('reads 64-bit integers as decimal strings', () => { const signed = true; expect(decoder.readZigzagVarint64String()) .toEqual(jspb.utils.hash64ToDecimalString(hashA, signed)); @@ -275,14 +279,14 @@ describe('binaryDecoderTest', function() { .toEqual(jspb.utils.hash64ToDecimalString(hashD, signed)); }); - it('reads 64-bit integers as hash strings', function() { + it('reads 64-bit integers as hash strings', () => { expect(decoder.readZigzagVarintHash64()).toEqual(hashA); expect(decoder.readZigzagVarintHash64()).toEqual(hashB); expect(decoder.readZigzagVarintHash64()).toEqual(hashC); expect(decoder.readZigzagVarintHash64()).toEqual(hashD); }); - it('reads split 64 bit zigzag integers', function() { + it('reads split 64 bit zigzag integers', () => { function hexJoin(bitsLow, bitsHigh) { return `0x${(bitsHigh >>> 0).toString(16)}:0x${ (bitsLow >>> 0).toString(16)}`; @@ -302,10 +306,10 @@ describe('binaryDecoderTest', function() { .toEqual(hexJoinHash(hashD)); }); - it('does zigzag encoding properly', function() { + it('does zigzag encoding properly', () => { // Test cases directly from the protobuf dev guide. // https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types - var testCases = [ + const testCases = [ {original: '0', zigzag: '0'}, {original: '-1', zigzag: '1'}, {original: '1', zigzag: '2'}, @@ -319,13 +323,13 @@ describe('binaryDecoderTest', function() { // 0x1FFFFF. The following used to be broken. {original: '72000000000', zigzag: '144000000000'}, ]; - var encoder = new jspb.BinaryEncoder(); + const encoder = new jspb.BinaryEncoder(); testCases.forEach(function(c) { encoder.writeZigzagVarint64String(c.original); }); - var buffer = encoder.end(); - var zigzagDecoder = jspb.BinaryDecoder.alloc(buffer); - var varintDecoder = jspb.BinaryDecoder.alloc(buffer); + const buffer = encoder.end(); + const zigzagDecoder = jspb.BinaryDecoder.alloc(buffer); + const varintDecoder = jspb.BinaryDecoder.alloc(buffer); testCases.forEach(function(c) { expect(zigzagDecoder.readZigzagVarint64String()).toEqual(c.original); expect(varintDecoder.readUnsignedVarint64String()).toEqual(c.zigzag); @@ -336,176 +340,186 @@ describe('binaryDecoderTest', function() { /** * Tests reading and writing large strings */ - it('testLargeStrings', function() { - var encoder = new jspb.BinaryEncoder(); + it('testLargeStrings', () => { + const encoder = new jspb.BinaryEncoder(); - var len = 150000; - var long_string = ''; - for (var i = 0; i < len; i++) { + const len = 150000; + let long_string = ''; + for (let i = 0; i < len; i++) { long_string += 'a'; } encoder.writeString(long_string); - var decoder = jspb.BinaryDecoder.alloc(encoder.end()); + const decoder = jspb.BinaryDecoder.alloc(encoder.end()); - assertEquals(long_string, decoder.readString(len)); + expect(decoder.readString(len)).toEqual(long_string); }); /** * Test encoding and decoding utf-8. */ - it('testUtf8', function() { - var encoder = new jspb.BinaryEncoder(); + it('testUtf8', () => { + const encoder = new jspb.BinaryEncoder(); - var ascii = "ASCII should work in 3, 2, 1..."; - var utf8_two_bytes = "©"; - var utf8_three_bytes = "❄"; - var utf8_four_bytes = "😁"; + const ascii = 'ASCII should work in 3, 2, 1...'; + const utf8_two_bytes = '©'; + const utf8_three_bytes = '❄'; + const utf8_four_bytes = '😁'; encoder.writeString(ascii); encoder.writeString(utf8_two_bytes); encoder.writeString(utf8_three_bytes); encoder.writeString(utf8_four_bytes); - var decoder = jspb.BinaryDecoder.alloc(encoder.end()); + const decoder = jspb.BinaryDecoder.alloc(encoder.end()); - assertEquals(ascii, decoder.readString(ascii.length)); - assertEquals(utf8_two_bytes, decoder.readString(utf8_two_bytes.length)); - assertEquals(utf8_three_bytes, decoder.readString(utf8_three_bytes.length)); - assertEquals(utf8_four_bytes, decoder.readString(utf8_four_bytes.length)); - }); + expect(decoder.readString(ascii.length)).toEqual(ascii); + expect(utf8_two_bytes).toEqual(decoder.readString(utf8_two_bytes.length)); + expect(utf8_three_bytes) + .toEqual(decoder.readString(utf8_three_bytes.length)); + expect(utf8_four_bytes).toEqual(decoder.readString(utf8_four_bytes.length)); + }); /** * Verifies that passing a non-string to writeString raises an error. */ - it('testBadString', function() { - var encoder = new jspb.BinaryEncoder(); - - assertThrows(function() {encoder.writeString(42)}); - assertThrows(function() {encoder.writeString(null)}); + it('testBadString', () => { + const encoder = new jspb.BinaryEncoder(); + + expect(() => { + encoder.writeString(42) + }).toThrow(); + expect(() => { + encoder.writeString(null) + }).toThrow(); }); /** * Verifies that misuse of the decoder class triggers assertions. */ - it('testDecodeErrors', function() { + it('testDecodeErrors', () => { // Reading a value past the end of the stream should trigger an assertion. - var decoder = jspb.BinaryDecoder.alloc([0, 1, 2]); - assertThrows(function() {decoder.readUint64()}); + const decoder = jspb.BinaryDecoder.alloc([0, 1, 2]); + expect(() => { + decoder.readUint64() + }).toThrow(); // Overlong varints should trigger assertions. - decoder.setBlock([255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 0]); - assertThrows(function() {decoder.readUnsignedVarint64()}); + decoder.setBlock( + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0]); + expect(() => { + decoder.readUnsignedVarint64() + }).toThrow(); decoder.reset(); - assertThrows(function() {decoder.readSignedVarint64()}); + expect(() => { + decoder.readSignedVarint64() + }).toThrow(); decoder.reset(); - assertThrows(function() {decoder.readZigzagVarint64()}); + expect(() => { + decoder.readZigzagVarint64() + }).toThrow(); decoder.reset(); - assertThrows(function() {decoder.readUnsignedVarint32()}); + expect(() => { + decoder.readUnsignedVarint32() + }).toThrow(); }); /** * Tests encoding and decoding of unsigned integers. */ - it('testUnsignedIntegers', function() { + it('testUnsignedIntegers', () => { doTestUnsignedValue( jspb.BinaryDecoder.prototype.readUint8, - jspb.BinaryEncoder.prototype.writeUint8, - 1, 0xFF, Math.round); + jspb.BinaryEncoder.prototype.writeUint8, 1, 0xFF, Math.round); doTestUnsignedValue( jspb.BinaryDecoder.prototype.readUint16, - jspb.BinaryEncoder.prototype.writeUint16, - 1, 0xFFFF, Math.round); + jspb.BinaryEncoder.prototype.writeUint16, 1, 0xFFFF, Math.round); doTestUnsignedValue( jspb.BinaryDecoder.prototype.readUint32, - jspb.BinaryEncoder.prototype.writeUint32, - 1, 0xFFFFFFFF, Math.round); + jspb.BinaryEncoder.prototype.writeUint32, 1, 0xFFFFFFFF, Math.round); doTestUnsignedValue( - jspb.BinaryDecoder.prototype.readUnsignedVarint32, - jspb.BinaryEncoder.prototype.writeUnsignedVarint32, - 1, 0xFFFFFFFF, Math.round); - + jspb.BinaryDecoder.prototype.readUnsignedVarint32, + jspb.BinaryEncoder.prototype.writeUnsignedVarint32, 1, 0xFFFFFFFF, + Math.round); + doTestUnsignedValue( jspb.BinaryDecoder.prototype.readUint64, - jspb.BinaryEncoder.prototype.writeUint64, - 1, Math.pow(2, 64) - 1025, Math.round); + jspb.BinaryEncoder.prototype.writeUint64, 1, Math.pow(2, 64) - 1025, + Math.round); doTestUnsignedValue( - jspb.BinaryDecoder.prototype.readUnsignedVarint64, - jspb.BinaryEncoder.prototype.writeUnsignedVarint64, - 1, Math.pow(2, 64) - 1025, Math.round); + jspb.BinaryDecoder.prototype.readUnsignedVarint64, + jspb.BinaryEncoder.prototype.writeUnsignedVarint64, 1, + Math.pow(2, 64) - 1025, Math.round); }); /** * Tests encoding and decoding of signed integers. */ - it('testSignedIntegers', function() { + it('testSignedIntegers', () => { doTestSignedValue( jspb.BinaryDecoder.prototype.readInt8, - jspb.BinaryEncoder.prototype.writeInt8, - 1, -0x80, 0x7F, Math.round); + jspb.BinaryEncoder.prototype.writeInt8, 1, -0x80, 0x7F, Math.round); doTestSignedValue( jspb.BinaryDecoder.prototype.readInt16, - jspb.BinaryEncoder.prototype.writeInt16, - 1, -0x8000, 0x7FFF, Math.round); + jspb.BinaryEncoder.prototype.writeInt16, 1, -0x8000, 0x7FFF, + Math.round); doTestSignedValue( jspb.BinaryDecoder.prototype.readInt32, - jspb.BinaryEncoder.prototype.writeInt32, - 1, -0x80000000, 0x7FFFFFFF, Math.round); + jspb.BinaryEncoder.prototype.writeInt32, 1, -0x80000000, 0x7FFFFFFF, + Math.round); doTestSignedValue( - jspb.BinaryDecoder.prototype.readSignedVarint32, - jspb.BinaryEncoder.prototype.writeSignedVarint32, - 1, -0x80000000, 0x7FFFFFFF, Math.round); + jspb.BinaryDecoder.prototype.readSignedVarint32, + jspb.BinaryEncoder.prototype.writeSignedVarint32, 1, -0x80000000, + 0x7FFFFFFF, Math.round); doTestSignedValue( jspb.BinaryDecoder.prototype.readInt64, - jspb.BinaryEncoder.prototype.writeInt64, - 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round); + jspb.BinaryEncoder.prototype.writeInt64, 1, -Math.pow(2, 63), + Math.pow(2, 63) - 513, Math.round); doTestSignedValue( - jspb.BinaryDecoder.prototype.readSignedVarint64, - jspb.BinaryEncoder.prototype.writeSignedVarint64, - 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round); + jspb.BinaryDecoder.prototype.readSignedVarint64, + jspb.BinaryEncoder.prototype.writeSignedVarint64, 1, -Math.pow(2, 63), + Math.pow(2, 63) - 513, Math.round); }); /** * Tests encoding and decoding of floats. */ - it('testFloats', function() { + it('testFloats', () => { /** * @param {number} x * @return {number} */ function truncate(x) { - var temp = new Float32Array(1); + const temp = new Float32Array(1); temp[0] = x; return temp[0]; } doTestSignedValue( jspb.BinaryDecoder.prototype.readFloat, jspb.BinaryEncoder.prototype.writeFloat, - jspb.BinaryConstants.FLOAT32_EPS, - -jspb.BinaryConstants.FLOAT32_MAX, - jspb.BinaryConstants.FLOAT32_MAX, - truncate); + jspb.BinaryConstants.FLOAT32_EPS, -jspb.BinaryConstants.FLOAT32_MAX, + jspb.BinaryConstants.FLOAT32_MAX, truncate); doTestSignedValue( jspb.BinaryDecoder.prototype.readDouble, jspb.BinaryEncoder.prototype.writeDouble, jspb.BinaryConstants.FLOAT64_EPS * 10, - -jspb.BinaryConstants.FLOAT64_MAX, - jspb.BinaryConstants.FLOAT64_MAX, - function(x) { return x; }); + -jspb.BinaryConstants.FLOAT64_MAX, jspb.BinaryConstants.FLOAT64_MAX, + function(x) { + return x; + }); }); }); diff --git a/binary/encoder.js b/binary/encoder.js index de08748..6a47e24 100644 --- a/binary/encoder.js +++ b/binary/encoder.js @@ -37,7 +37,7 @@ goog.provide('jspb.BinaryEncoder'); -goog.require('goog.asserts'); +goog.require('jspb.asserts'); goog.require('jspb.BinaryConstants'); goog.require('jspb.utils'); @@ -81,12 +81,12 @@ jspb.BinaryEncoder.prototype.end = function() { * @param {number} highBits The high 32 bits of the int. */ jspb.BinaryEncoder.prototype.writeSplitVarint64 = function(lowBits, highBits) { - goog.asserts.assert(lowBits == Math.floor(lowBits)); - goog.asserts.assert(highBits == Math.floor(highBits)); - goog.asserts.assert((lowBits >= 0) && - (lowBits < jspb.BinaryConstants.TWO_TO_32)); - goog.asserts.assert((highBits >= 0) && - (highBits < jspb.BinaryConstants.TWO_TO_32)); + jspb.asserts.assert(lowBits == Math.floor(lowBits)); + jspb.asserts.assert(highBits == Math.floor(highBits)); + jspb.asserts.assert( + (lowBits >= 0) && (lowBits < jspb.BinaryConstants.TWO_TO_32)); + jspb.asserts.assert( + (highBits >= 0) && (highBits < jspb.BinaryConstants.TWO_TO_32)); // Break the binary representation into chunks of 7 bits, set the 8th bit // in each chunk if it's not the final chunk, and append to the result. @@ -106,12 +106,12 @@ jspb.BinaryEncoder.prototype.writeSplitVarint64 = function(lowBits, highBits) { * @param {number} highBits The high 32 bits of the int. */ jspb.BinaryEncoder.prototype.writeSplitFixed64 = function(lowBits, highBits) { - goog.asserts.assert(lowBits == Math.floor(lowBits)); - goog.asserts.assert(highBits == Math.floor(highBits)); - goog.asserts.assert((lowBits >= 0) && - (lowBits < jspb.BinaryConstants.TWO_TO_32)); - goog.asserts.assert((highBits >= 0) && - (highBits < jspb.BinaryConstants.TWO_TO_32)); + jspb.asserts.assert(lowBits == Math.floor(lowBits)); + jspb.asserts.assert(highBits == Math.floor(highBits)); + jspb.asserts.assert( + (lowBits >= 0) && (lowBits < jspb.BinaryConstants.TWO_TO_32)); + jspb.asserts.assert( + (highBits >= 0) && (highBits < jspb.BinaryConstants.TWO_TO_32)); this.writeUint32(lowBits); this.writeUint32(highBits); }; @@ -123,9 +123,9 @@ jspb.BinaryEncoder.prototype.writeSplitFixed64 = function(lowBits, highBits) { * @param {number} value The integer to convert. */ jspb.BinaryEncoder.prototype.writeUnsignedVarint32 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= 0) && - (value < jspb.BinaryConstants.TWO_TO_32)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= 0) && (value < jspb.BinaryConstants.TWO_TO_32)); while (value > 127) { this.buffer_.push((value & 0x7f) | 0x80); @@ -142,9 +142,10 @@ jspb.BinaryEncoder.prototype.writeUnsignedVarint32 = function(value) { * @param {number} value The integer to convert. */ jspb.BinaryEncoder.prototype.writeSignedVarint32 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && - (value < jspb.BinaryConstants.TWO_TO_31)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); // Use the unsigned version if the value is not negative. if (value >= 0) { @@ -171,12 +172,11 @@ jspb.BinaryEncoder.prototype.writeSignedVarint32 = function(value) { * @param {number} value The integer to convert. */ jspb.BinaryEncoder.prototype.writeUnsignedVarint64 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= 0) && - (value < jspb.BinaryConstants.TWO_TO_64)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= 0) && (value < jspb.BinaryConstants.TWO_TO_64)); jspb.utils.splitInt64(value); - this.writeSplitVarint64(jspb.utils.split64Low, - jspb.utils.split64High); + this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High); }; @@ -187,12 +187,12 @@ jspb.BinaryEncoder.prototype.writeUnsignedVarint64 = function(value) { * @param {number} value The integer to convert. */ jspb.BinaryEncoder.prototype.writeSignedVarint64 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) && - (value < jspb.BinaryConstants.TWO_TO_63)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_63) && + (value < jspb.BinaryConstants.TWO_TO_63)); jspb.utils.splitInt64(value); - this.writeSplitVarint64(jspb.utils.split64Low, - jspb.utils.split64High); + this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High); }; @@ -202,9 +202,10 @@ jspb.BinaryEncoder.prototype.writeSignedVarint64 = function(value) { * @param {number} value The integer to convert. */ jspb.BinaryEncoder.prototype.writeZigzagVarint32 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && - (value < jspb.BinaryConstants.TWO_TO_31)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); this.writeUnsignedVarint32(((value << 1) ^ (value >> 31)) >>> 0); }; @@ -216,12 +217,12 @@ jspb.BinaryEncoder.prototype.writeZigzagVarint32 = function(value) { * @param {number} value The integer to convert. */ jspb.BinaryEncoder.prototype.writeZigzagVarint64 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) && - (value < jspb.BinaryConstants.TWO_TO_63)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_63) && + (value < jspb.BinaryConstants.TWO_TO_63)); jspb.utils.splitZigzag64(value); - this.writeSplitVarint64(jspb.utils.split64Low, - jspb.utils.split64High); + this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High); }; @@ -257,8 +258,8 @@ jspb.BinaryEncoder.prototype.writeZigzagVarintHash64 = function(hash) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeUint8 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= 0) && (value < 256)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert((value >= 0) && (value < 256)); this.buffer_.push((value >>> 0) & 0xFF); }; @@ -269,8 +270,8 @@ jspb.BinaryEncoder.prototype.writeUint8 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeUint16 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= 0) && (value < 65536)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert((value >= 0) && (value < 65536)); this.buffer_.push((value >>> 0) & 0xFF); this.buffer_.push((value >>> 8) & 0xFF); }; @@ -282,9 +283,9 @@ jspb.BinaryEncoder.prototype.writeUint16 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeUint32 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= 0) && - (value < jspb.BinaryConstants.TWO_TO_32)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= 0) && (value < jspb.BinaryConstants.TWO_TO_32)); this.buffer_.push((value >>> 0) & 0xFF); this.buffer_.push((value >>> 8) & 0xFF); this.buffer_.push((value >>> 16) & 0xFF); @@ -298,9 +299,9 @@ jspb.BinaryEncoder.prototype.writeUint32 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeUint64 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= 0) && - (value < jspb.BinaryConstants.TWO_TO_64)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= 0) && (value < jspb.BinaryConstants.TWO_TO_64)); jspb.utils.splitUint64(value); this.writeUint32(jspb.utils.split64Low); this.writeUint32(jspb.utils.split64High); @@ -313,8 +314,8 @@ jspb.BinaryEncoder.prototype.writeUint64 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeInt8 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -128) && (value < 128)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert((value >= -128) && (value < 128)); this.buffer_.push((value >>> 0) & 0xFF); }; @@ -325,8 +326,8 @@ jspb.BinaryEncoder.prototype.writeInt8 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeInt16 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -32768) && (value < 32768)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert((value >= -32768) && (value < 32768)); this.buffer_.push((value >>> 0) & 0xFF); this.buffer_.push((value >>> 8) & 0xFF); }; @@ -338,9 +339,10 @@ jspb.BinaryEncoder.prototype.writeInt16 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeInt32 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && - (value < jspb.BinaryConstants.TWO_TO_31)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); this.buffer_.push((value >>> 0) & 0xFF); this.buffer_.push((value >>> 8) & 0xFF); this.buffer_.push((value >>> 16) & 0xFF); @@ -354,9 +356,10 @@ jspb.BinaryEncoder.prototype.writeInt32 = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeInt64 = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) && - (value < jspb.BinaryConstants.TWO_TO_63)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_63) && + (value < jspb.BinaryConstants.TWO_TO_63)); jspb.utils.splitInt64(value); this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High); }; @@ -368,9 +371,10 @@ jspb.BinaryEncoder.prototype.writeInt64 = function(value) { * @param {string} value The value to write. */ jspb.BinaryEncoder.prototype.writeInt64String = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((+value >= -jspb.BinaryConstants.TWO_TO_63) && - (+value < jspb.BinaryConstants.TWO_TO_63)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (+value >= -jspb.BinaryConstants.TWO_TO_63) && + (+value < jspb.BinaryConstants.TWO_TO_63)); jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value)); this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High); }; @@ -382,7 +386,7 @@ jspb.BinaryEncoder.prototype.writeInt64String = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeFloat = function(value) { - goog.asserts.assert( + jspb.asserts.assert( value === Infinity || value === -Infinity || isNaN(value) || ((value >= -jspb.BinaryConstants.FLOAT32_MAX) && (value <= jspb.BinaryConstants.FLOAT32_MAX))); @@ -397,7 +401,7 @@ jspb.BinaryEncoder.prototype.writeFloat = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeDouble = function(value) { - goog.asserts.assert( + jspb.asserts.assert( value === Infinity || value === -Infinity || isNaN(value) || ((value >= -jspb.BinaryConstants.FLOAT64_MAX) && (value <= jspb.BinaryConstants.FLOAT64_MAX))); @@ -414,7 +418,8 @@ jspb.BinaryEncoder.prototype.writeDouble = function(value) { * @param {boolean|number} value The value to write. */ jspb.BinaryEncoder.prototype.writeBool = function(value) { - goog.asserts.assert(typeof value === 'boolean' || typeof value === 'number'); + jspb.asserts.assert( + typeof value === 'boolean' || typeof value === 'number'); this.buffer_.push(value ? 1 : 0); }; @@ -424,9 +429,10 @@ jspb.BinaryEncoder.prototype.writeBool = function(value) { * @param {number} value The value to write. */ jspb.BinaryEncoder.prototype.writeEnum = function(value) { - goog.asserts.assert(value == Math.floor(value)); - goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) && - (value < jspb.BinaryConstants.TWO_TO_31)); + jspb.asserts.assert(value == Math.floor(value)); + jspb.asserts.assert( + (value >= -jspb.BinaryConstants.TWO_TO_31) && + (value < jspb.BinaryConstants.TWO_TO_31)); this.writeSignedVarint32(value); }; @@ -447,8 +453,7 @@ jspb.BinaryEncoder.prototype.writeBytes = function(bytes) { */ jspb.BinaryEncoder.prototype.writeVarintHash64 = function(hash) { jspb.utils.splitHash64(hash); - this.writeSplitVarint64(jspb.utils.split64Low, - jspb.utils.split64High); + this.writeSplitVarint64(jspb.utils.split64Low, jspb.utils.split64High); }; @@ -474,10 +479,9 @@ jspb.BinaryEncoder.prototype.writeString = function(value) { var oldLength = this.buffer_.length; // Protect against non-string values being silently ignored. - goog.asserts.assertString(value); + jspb.asserts.assertString(value); for (var i = 0; i < value.length; i++) { - var c = value.charCodeAt(i); if (c < 128) { @@ -489,18 +493,17 @@ jspb.BinaryEncoder.prototype.writeString = function(value) { // Look for surrogates if (c >= 0xD800 && c <= 0xDBFF && i + 1 < value.length) { var second = value.charCodeAt(i + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae c = (c - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; this.buffer_.push((c >> 18) | 240); - this.buffer_.push(((c >> 12) & 63 ) | 128); + this.buffer_.push(((c >> 12) & 63) | 128); this.buffer_.push(((c >> 6) & 63) | 128); this.buffer_.push((c & 63) | 128); i++; } - } - else { + } else { this.buffer_.push((c >> 12) | 224); this.buffer_.push(((c >> 6) & 63) | 128); this.buffer_.push((c & 63) | 128); diff --git a/binary/message_test.js b/binary/message_test.js index 4edc666..807a0b7 100644 --- a/binary/message_test.js +++ b/binary/message_test.js @@ -32,29 +32,27 @@ goog.setTestOnly(); -goog.require('goog.testing.asserts'); - // CommonJS-LoadFromFile: test_pb proto.jspb.test goog.require('proto.jspb.test.Deeply.Nested.Message'); // CommonJS-LoadFromFile: test2_pb proto.jspb.test goog.require('proto.jspb.test.ForeignNestedFieldMessage'); -describe('Message test suite', function() { +describe('Message test suite', () => { // Verify that we can successfully use a field referring to a nested message // from a different .proto file. - it('testForeignNestedMessage', function() { - var msg = new proto.jspb.test.ForeignNestedFieldMessage(); - var nested = new proto.jspb.test.Deeply.Nested.Message(); + it('testForeignNestedMessage', () => { + const msg = new proto.jspb.test.ForeignNestedFieldMessage(); + const nested = new proto.jspb.test.Deeply.Nested.Message(); nested.setCount(5); msg.setDeeplyNestedMessage(nested); - assertEquals(5, msg.getDeeplyNestedMessage().getCount()); + expect(msg.getDeeplyNestedMessage().getCount()).toEqual(5); // After a serialization-deserialization round trip we should get back the // same data we started with. - var serialized = msg.serializeBinary(); - var deserialized = + const serialized = msg.serializeBinary(); + const deserialized = proto.jspb.test.ForeignNestedFieldMessage.deserializeBinary(serialized); - assertEquals(5, deserialized.getDeeplyNestedMessage().getCount()); + expect(deserialized.getDeeplyNestedMessage().getCount()).toEqual(5); }); }); diff --git a/binary/proto_test.js b/binary/proto_test.js index 1ece6b3..689498c 100644 --- a/binary/proto_test.js +++ b/binary/proto_test.js @@ -31,7 +31,7 @@ // Test suite is written using Jasmine -- see http://jasmine.github.io/ goog.require('goog.crypt.base64'); -goog.require('goog.testing.asserts'); + goog.require('jspb.BinaryWriter'); goog.require('jspb.Message'); @@ -88,15 +88,16 @@ goog.require('proto.jspb.test.extendRepeatedStringList'); goog.require('proto.jspb.test.extendRepeatedUint32List'); goog.require('proto.jspb.test.extendRepeatedUint64List'); +// clang-format off // CommonJS-LoadFromFile: ../node_modules/google-protobuf/google/protobuf/any_pb proto.google.protobuf goog.require('proto.google.protobuf.Any'); -var suite = {}; +const suite = {}; -var BYTES = new Uint8Array([1, 2, 8, 9]); +const BYTES = new Uint8Array([1, 2, 8, 9]); -var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES); +const BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES); /** @@ -123,7 +124,7 @@ function fillAllFields(msg) { msg.setOptionalBytes(BYTES); msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup()); msg.getOptionalGroup().setA(100); - var submsg = new proto.jspb.test.ForeignMessage(); + let submsg = new proto.jspb.test.ForeignMessage(); submsg.setC(16); msg.setOptionalForeignMessage(submsg); msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO); @@ -165,7 +166,6 @@ function fillAllFields(msg) { msg.setPackedRepeatedFloatList([1.5]); msg.setPackedRepeatedDoubleList([-1.5]); msg.setPackedRepeatedBoolList([true]); - } @@ -182,7 +182,7 @@ function bytesCompare(arr, expected) { if (arr.length != expected.length) { return false; } - for (var i = 0; i < arr.length; i++) { + for (let i = 0; i < arr.length; i++) { if (arr[i] != expected[i]) { return false; } @@ -198,83 +198,81 @@ function bytesCompare(arr, expected) { * @param {proto.jspb.test.TestAllTypes} copy */ function checkAllFields(original, copy) { - assertEquals(copy.getOptionalInt32(), -42); - assertEquals(copy.getOptionalInt64(), -0x7fffffff00000000); - assertEquals(copy.getOptionalUint32(), 0x80000000); - assertEquals(copy.getOptionalUint64(), 0xf000000000000000); - assertEquals(copy.getOptionalSint32(), -100); - assertEquals(copy.getOptionalSint64(), -0x8000000000000000); - assertEquals(copy.getOptionalFixed32(), 1234); - assertEquals(copy.getOptionalFixed64(), 0x1234567800000000); - assertEquals(copy.getOptionalSfixed32(), -1234); - assertEquals(copy.getOptionalSfixed64(), -0x1234567800000000); - assertEquals(copy.getOptionalFloat(), 1.5); - assertEquals(copy.getOptionalDouble(), -1.5); - assertEquals(copy.getOptionalBool(), true); - assertEquals(copy.getOptionalString(), 'hello world'); - assertEquals(true, bytesCompare(copy.getOptionalBytes(), BYTES)); - assertEquals(true, bytesCompare(copy.getOptionalBytes_asU8(), BYTES)); - assertEquals( - copy.getOptionalBytes_asB64(), goog.crypt.base64.encodeByteArray(BYTES)); - - assertEquals(copy.getOptionalGroup().getA(), 100); - assertEquals(copy.getOptionalForeignMessage().getC(), 16); - assertEquals(copy.getOptionalForeignEnum(), - proto.jspb.test.ForeignEnum.FOREIGN_FOO); - - - assertEquals(copy.getOneofString(), 'oneof'); - assertEquals(copy.getOneofFieldCase(), - proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING); - - assertElementsEquals(copy.getRepeatedInt32List(), [-42]); - assertElementsEquals(copy.getRepeatedInt64List(), [-0x7fffffff00000000]); - assertElementsEquals(copy.getRepeatedUint32List(), [0x80000000]); - assertElementsEquals(copy.getRepeatedUint64List(), [0xf000000000000000]); - assertElementsEquals(copy.getRepeatedSint32List(), [-100]); - assertElementsEquals(copy.getRepeatedSint64List(), [-0x8000000000000000]); - assertElementsEquals(copy.getRepeatedFixed32List(), [1234]); - assertElementsEquals(copy.getRepeatedFixed64List(), [0x1234567800000000]); - assertElementsEquals(copy.getRepeatedSfixed32List(), [-1234]); - assertElementsEquals(copy.getRepeatedSfixed64List(), [-0x1234567800000000]); - assertElementsEquals(copy.getRepeatedFloatList(), [1.5]); - assertElementsEquals(copy.getRepeatedDoubleList(), [-1.5]); - assertElementsEquals(copy.getRepeatedBoolList(), [true]); - assertElementsEquals(copy.getRepeatedStringList(), ['hello world']); - assertEquals(copy.getRepeatedBytesList().length, 2); - assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES)); - assertEquals(true, bytesCompare(copy.getRepeatedBytesList()[0], BYTES)); - assertEquals(true, bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES)); - assertEquals(copy.getRepeatedBytesList_asB64()[0], BYTES_B64); - assertEquals(copy.getRepeatedBytesList_asB64()[1], BYTES_B64); - assertEquals(copy.getRepeatedGroupList().length, 1); - assertEquals(copy.getRepeatedGroupList()[0].getA(), 100); - assertEquals(copy.getRepeatedForeignMessageList().length, 1); - assertEquals(copy.getRepeatedForeignMessageList()[0].getC(), 1000); - assertElementsEquals(copy.getRepeatedForeignEnumList(), - [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); - - assertElementsEquals(copy.getPackedRepeatedInt32List(), [-42]); - assertElementsEquals(copy.getPackedRepeatedInt64List(), - [-0x7fffffff00000000]); - assertElementsEquals(copy.getPackedRepeatedUint32List(), [0x80000000]); - assertElementsEquals(copy.getPackedRepeatedUint64List(), - [0xf000000000000000]); - assertElementsEquals(copy.getPackedRepeatedSint32List(), [-100]); - assertElementsEquals(copy.getPackedRepeatedSint64List(), - [-0x8000000000000000]); - assertElementsEquals(copy.getPackedRepeatedFixed32List(), [1234]); - assertElementsEquals(copy.getPackedRepeatedFixed64List(), - [0x1234567800000000]); - assertElementsEquals(copy.getPackedRepeatedSfixed32List(), [-1234]); - assertElementsEquals(copy.getPackedRepeatedSfixed64List(), - [-0x1234567800000000]); - assertElementsEquals(copy.getPackedRepeatedFloatList(), [1.5]); - assertElementsEquals(copy.getPackedRepeatedDoubleList(), [-1.5]); + expect(copy.getOptionalInt32()).toEqual(-42); + expect(copy.getOptionalInt64()).toEqual(-0x7fffffff00000000); + expect(copy.getOptionalUint32()).toEqual(0x80000000); + expect(copy.getOptionalUint64()).toEqual(0xf000000000000000); + expect(copy.getOptionalSint32()).toEqual(-100); + expect(copy.getOptionalSint64()).toEqual(-0x8000000000000000); + expect(copy.getOptionalFixed32()).toEqual(1234); + expect(copy.getOptionalFixed64()).toEqual(0x1234567800000000); + expect(copy.getOptionalSfixed32()).toEqual(-1234); + expect(copy.getOptionalSfixed64()).toEqual(-0x1234567800000000); + expect(copy.getOptionalFloat()).toEqual(1.5); + expect(copy.getOptionalDouble()).toEqual(-1.5); + expect(copy.getOptionalBool()).toBeTrue(); + expect(copy.getOptionalString()).toEqual('hello world'); + expect(bytesCompare(copy.getOptionalBytes(), BYTES)).toEqual(true); + expect(true).toEqual(bytesCompare(copy.getOptionalBytes_asU8(), BYTES)); + expect(copy.getOptionalBytes_asB64()) + .toEqual(goog.crypt.base64.encodeByteArray(BYTES)); + + expect(copy.getOptionalGroup().getA()).toEqual(100); + expect(copy.getOptionalForeignMessage().getC()).toEqual(16); + expect(proto.jspb.test.ForeignEnum.FOREIGN_FOO) + .toEqual(copy.getOptionalForeignEnum()); + + + expect(copy.getOneofString()).toEqual('oneof'); + expect(proto.jspb.test.TestAllTypes.OneofFieldCase.ONEOF_STRING) + .toEqual(copy.getOneofFieldCase()); + + expect(copy.getRepeatedInt32List()).toEqual([-42]); + expect(copy.getRepeatedInt64List()).toEqual([-0x7fffffff00000000]); + expect(copy.getRepeatedUint32List()).toEqual([0x80000000]); + expect(copy.getRepeatedUint64List()).toEqual([0xf000000000000000]); + expect(copy.getRepeatedSint32List()).toEqual([-100]); + expect(copy.getRepeatedSint64List()).toEqual([-0x8000000000000000]); + expect(copy.getRepeatedFixed32List()).toEqual([1234]); + expect(copy.getRepeatedFixed64List()).toEqual([0x1234567800000000]); + expect(copy.getRepeatedSfixed32List()).toEqual([-1234]); + expect(copy.getRepeatedSfixed64List()).toEqual([-0x1234567800000000]); + expect(copy.getRepeatedFloatList()).toEqual([1.5]); + expect(copy.getRepeatedDoubleList()).toEqual([-1.5]); + expect(copy.getRepeatedBoolList()).toEqual([true]); + expect(copy.getRepeatedStringList()).toEqual(['hello world']); + expect(copy.getRepeatedBytesList().length).toEqual(2); + expect(true).toEqual( + bytesCompare(copy.getRepeatedBytesList_asU8()[0], BYTES)); + expect(true).toEqual(bytesCompare(copy.getRepeatedBytesList()[0], BYTES)); + expect(true).toEqual( + bytesCompare(copy.getRepeatedBytesList_asU8()[1], BYTES)); + expect(copy.getRepeatedBytesList_asB64()[0]).toEqual(BYTES_B64); + expect(copy.getRepeatedBytesList_asB64()[1]).toEqual(BYTES_B64); + expect(copy.getRepeatedGroupList().length).toEqual(1); + expect(copy.getRepeatedGroupList()[0].getA()).toEqual(100); + expect(copy.getRepeatedForeignMessageList().length).toEqual(1); + expect(copy.getRepeatedForeignMessageList()[0].getC()).toEqual(1000); + expect([ + proto.jspb.test.ForeignEnum.FOREIGN_FOO + ]).toEqual(copy.getRepeatedForeignEnumList()); + + expect(copy.getPackedRepeatedInt32List()).toEqual([-42]); + expect(copy.getPackedRepeatedInt64List()).toEqual([-0x7fffffff00000000]); + expect(copy.getPackedRepeatedUint32List()).toEqual([0x80000000]); + expect(copy.getPackedRepeatedUint64List()).toEqual([0xf000000000000000]); + expect(copy.getPackedRepeatedSint32List()).toEqual([-100]); + expect(copy.getPackedRepeatedSint64List()).toEqual([-0x8000000000000000]); + expect(copy.getPackedRepeatedFixed32List()).toEqual([1234]); + expect(copy.getPackedRepeatedFixed64List()).toEqual([0x1234567800000000]); + expect(copy.getPackedRepeatedSfixed32List()).toEqual([-1234]); + expect(copy.getPackedRepeatedSfixed64List()).toEqual([-0x1234567800000000]); + expect(copy.getPackedRepeatedFloatList()).toEqual([1.5]); + expect(copy.getPackedRepeatedDoubleList()).toEqual([-1.5]); // Check last so we get more granular errors first. - assertTrue(jspb.Message.equals(original, copy)); + expect(jspb.Message.equals(original, copy)).toBeTrue(); } @@ -283,217 +281,200 @@ function checkAllFields(original, copy) { * @param {!proto.jspb.test.TestExtendable} msg */ function checkExtensions(msg) { - assertEquals(0, msg.getExtension(proto.jspb.test.extendOptionalInt32)); - assertEquals(-0x7fffffff00000000, - msg.getExtension(proto.jspb.test.extendOptionalInt64)); - assertEquals(0x80000000, - msg.getExtension(proto.jspb.test.extendOptionalUint32)); - assertEquals(0xf000000000000000, - msg.getExtension(proto.jspb.test.extendOptionalUint64)); - assertEquals(-100, - msg.getExtension(proto.jspb.test.extendOptionalSint32)); - assertEquals(-0x8000000000000000, - msg.getExtension(proto.jspb.test.extendOptionalSint64)); - assertEquals(1234, - msg.getExtension(proto.jspb.test.extendOptionalFixed32)); - assertEquals(0x1234567800000000, - msg.getExtension(proto.jspb.test.extendOptionalFixed64)); - assertEquals(-1234, + expect(0).toEqual(msg.getExtension(proto.jspb.test.extendOptionalInt32)); + expect(-0x7fffffff00000000) + .toEqual(msg.getExtension(proto.jspb.test.extendOptionalInt64)); + expect(0x80000000) + .toEqual(msg.getExtension(proto.jspb.test.extendOptionalUint32)); + expect(0xf000000000000000) + .toEqual(msg.getExtension(proto.jspb.test.extendOptionalUint64)); + expect(-100).toEqual(msg.getExtension(proto.jspb.test.extendOptionalSint32)); + expect(-0x8000000000000000) + .toEqual(msg.getExtension(proto.jspb.test.extendOptionalSint64)); + expect(1234).toEqual(msg.getExtension(proto.jspb.test.extendOptionalFixed32)); + expect(0x1234567800000000) + .toEqual(msg.getExtension(proto.jspb.test.extendOptionalFixed64)); + expect(-1234).toEqual( msg.getExtension(proto.jspb.test.extendOptionalSfixed32)); - assertEquals(-0x1234567800000000, - msg.getExtension(proto.jspb.test.extendOptionalSfixed64)); - assertEquals(1.5, - msg.getExtension(proto.jspb.test.extendOptionalFloat)); - assertEquals(-1.5, - msg.getExtension(proto.jspb.test.extendOptionalDouble)); - assertEquals(true, - msg.getExtension(proto.jspb.test.extendOptionalBool)); - assertEquals('hello world', - msg.getExtension(proto.jspb.test.extendOptionalString)); - assertEquals( - true, bytesCompare( - msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES)); - assertEquals(16, - msg.getExtension( - proto.jspb.test.ExtendsWithMessage.optionalExtension).getFoo()); - - - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedInt32List), - [-42]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedInt64List), - [-0x7fffffff00000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedUint32List), - [0x80000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedUint64List), - [0xf000000000000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedSint32List), - [-100]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedSint64List), - [-0x8000000000000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedFixed32List), - [1234]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedFixed64List), - [0x1234567800000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List), - [-1234]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List), - [-0x1234567800000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedFloatList), - [1.5]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedDoubleList), - [-1.5]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedBoolList), - [true]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedStringList), - ['hello world']); - assertEquals( - true, - bytesCompare( - msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES)); - assertEquals(1000, + expect(-0x1234567800000000) + .toEqual(msg.getExtension(proto.jspb.test.extendOptionalSfixed64)); + expect(msg.getExtension(proto.jspb.test.extendOptionalFloat)).toEqual(1.5); + expect(msg.getExtension(proto.jspb.test.extendOptionalDouble)).toEqual(-1.5); + expect(msg.getExtension(proto.jspb.test.extendOptionalBool)).toEqual(true); + expect(msg.getExtension(proto.jspb.test.extendOptionalString)) + .toEqual('hello world'); + expect(bytesCompare( + msg.getExtension(proto.jspb.test.extendOptionalBytes), BYTES)) + .toEqual(true); + expect(msg.getExtension(proto.jspb.test.ExtendsWithMessage.optionalExtension) + .getFoo()) + .toEqual(16); + + + expect(msg.getExtension(proto.jspb.test.extendRepeatedInt32List)).toEqual([ + -42 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedInt64List)).toEqual([ + -0x7fffffff00000000 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedUint32List)).toEqual([ + 0x80000000 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedUint64List)).toEqual([ + 0xf000000000000000 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedSint32List)).toEqual([ + -100 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedSint64List)).toEqual([ + -0x8000000000000000 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedFixed32List)).toEqual([ + 1234 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedFixed64List)).toEqual([ + 0x1234567800000000 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedSfixed32List)).toEqual([ + -1234 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedSfixed64List)).toEqual([ + -0x1234567800000000 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedFloatList)).toEqual([ + 1.5 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedDoubleList)).toEqual([ + -1.5 + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedBoolList)).toEqual([ + true + ]); + expect(msg.getExtension(proto.jspb.test.extendRepeatedStringList)).toEqual([ + 'hello world' + ]); + expect(true).toEqual(bytesCompare( + msg.getExtension(proto.jspb.test.extendRepeatedBytesList)[0], BYTES)); + expect(1000).toEqual( msg.getExtension( - proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0] - .getFoo()); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList), - [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); - - - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List), - [-42]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List), - [-0x7fffffff00000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List), - [0x80000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List), - [0xf000000000000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List), - [-100]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List), - [-0x8000000000000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List), - [1234]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List), - [0x1234567800000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List), - [-1234]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List), - [-0x1234567800000000]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList), - [1.5]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList), - [-1.5]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList), - [true]); - assertElementsEquals( - msg.getExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList), - [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); - + proto.jspb.test.ExtendsWithMessage.repeatedExtensionList)[0] + .getFoo()); + expect([ + proto.jspb.test.ForeignEnum.FOREIGN_FOO + ]).toEqual(msg.getExtension(proto.jspb.test.extendRepeatedForeignEnumList)); + + + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedInt32List)) + .toEqual([-42]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedInt64List)) + .toEqual([-0x7fffffff00000000]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedUint32List)) + .toEqual([0x80000000]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedUint64List)) + .toEqual([0xf000000000000000]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedSint32List)) + .toEqual([-100]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedSint64List)) + .toEqual([-0x8000000000000000]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed32List)) + .toEqual([1234]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedFixed64List)) + .toEqual([0x1234567800000000]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed32List)) + .toEqual([-1234]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedSfixed64List)) + .toEqual([-0x1234567800000000]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedFloatList)) + .toEqual([1.5]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedDoubleList)) + .toEqual([-1.5]); + expect(msg.getExtension(proto.jspb.test.extendPackedRepeatedBoolList)) + .toEqual([true]); + expect([proto.jspb.test.ForeignEnum.FOREIGN_FOO]) + .toEqual(msg.getExtension( + proto.jspb.test.extendPackedRepeatedForeignEnumList)); } -describe('protoBinaryTest', function() { +describe('protoBinaryTest', () => { /** * Tests a basic serialization-deserializaton round-trip with all supported * field types (on the TestAllTypes message type). */ - it('testRoundTrip', function() { - var msg = new proto.jspb.test.TestAllTypes(); + it('testRoundTrip', () => { + const msg = new proto.jspb.test.TestAllTypes(); fillAllFields(msg); - var encoded = msg.serializeBinary(); - var decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded); + const encoded = msg.serializeBinary(); + const decoded = proto.jspb.test.TestAllTypes.deserializeBinary(encoded); checkAllFields(msg, decoded); }); /** * Test that base64 string and Uint8Array are interchangeable in bytes fields. */ - it('testBytesFieldsGettersInterop', function() { - var msg = new proto.jspb.test.TestAllTypes(); + it('testBytesFieldsGettersInterop', () => { + let msg = new proto.jspb.test.TestAllTypes(); // Set from a base64 string and check all the getters work. msg.setOptionalBytes(BYTES_B64); - assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); - assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + expect(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)).toBeTrue(); + expect(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)).toBeTrue(); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); // Test binary serialize round trip doesn't break it. msg = proto.jspb.test.TestAllTypes.deserializeBinary(msg.serializeBinary()); - assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); - assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + expect(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)).toBeTrue(); + expect(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)).toBeTrue(); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); msg = new proto.jspb.test.TestAllTypes(); // Set from a Uint8Array and check all the getters work. msg.setOptionalBytes(BYTES); - assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)); - assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); - + expect(bytesCompare(msg.getOptionalBytes_asU8(), BYTES)).toBeTrue(); + expect(bytesCompare(msg.getOptionalBytes_asB64(), BYTES)).toBeTrue(); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); }); /** * Test that bytes setters will receive result of any of the getters. */ - it('testBytesFieldsSettersInterop', function() { - var msg = new proto.jspb.test.TestAllTypes(); + it('testBytesFieldsSettersInterop', () => { + const msg = new proto.jspb.test.TestAllTypes(); msg.setOptionalBytes(BYTES); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); msg.setOptionalBytes(msg.getOptionalBytes()); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); msg.setOptionalBytes(msg.getOptionalBytes_asB64()); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); msg.setOptionalBytes(msg.getOptionalBytes_asU8()); - assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES)); + expect(bytesCompare(msg.getOptionalBytes(), BYTES)).toBeTrue(); }); /** * Test that bytes setters will receive result of any of the getters. */ - it('testRepeatedBytesGetters', function() { - var msg = new proto.jspb.test.TestAllTypes(); + it('testRepeatedBytesGetters', () => { + const msg = new proto.jspb.test.TestAllTypes(); function assertGetters() { - assertTrue(typeof msg.getRepeatedBytesList_asB64()[0] === 'string'); - assertTrue(typeof msg.getRepeatedBytesList_asB64()[1] === 'string'); - assertTrue(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array); - assertTrue(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array); - - assertTrue(bytesCompare(msg.getRepeatedBytesList()[0], BYTES)); - assertTrue(bytesCompare(msg.getRepeatedBytesList()[1], BYTES)); - assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES)); - assertTrue(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES)); - assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES)); - assertTrue(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES)); + expect(typeof msg.getRepeatedBytesList_asB64()[0]).toEqual('string'); + expect(typeof msg.getRepeatedBytesList_asB64()[1]).toEqual('string'); + expect(msg.getRepeatedBytesList_asU8()[0] instanceof Uint8Array) + .toBeTrue(); + expect(msg.getRepeatedBytesList_asU8()[1] instanceof Uint8Array) + .toBeTrue(); + + expect(bytesCompare(msg.getRepeatedBytesList()[0], BYTES)).toBeTrue(); + expect(bytesCompare(msg.getRepeatedBytesList()[1], BYTES)).toBeTrue(); + expect(bytesCompare(msg.getRepeatedBytesList_asB64()[0], BYTES)) + .toBeTrue(); + expect(bytesCompare(msg.getRepeatedBytesList_asB64()[1], BYTES)) + .toBeTrue(); + expect(bytesCompare(msg.getRepeatedBytesList_asU8()[0], BYTES)) + .toBeTrue(); + expect(bytesCompare(msg.getRepeatedBytesList_asU8()[1], BYTES)) + .toBeTrue(); } - msg.setRepeatedBytesList([BYTES, BYTES]); assertGetters(); @@ -501,9 +482,9 @@ describe('protoBinaryTest', function() { assertGetters(); msg.setRepeatedBytesList([]); - assertEquals(0, msg.getRepeatedBytesList().length); - assertEquals(0, msg.getRepeatedBytesList_asB64().length); - assertEquals(0, msg.getRepeatedBytesList_asU8().length); + expect(msg.getRepeatedBytesList().length).toEqual(0); + expect(0).toEqual(msg.getRepeatedBytesList_asB64().length); + expect(0).toEqual(msg.getRepeatedBytesList_asU8().length); }); /** @@ -512,34 +493,22 @@ describe('protoBinaryTest', function() { */ function fillExtensions(msg) { msg.setExtension(proto.jspb.test.extendOptionalInt32, 0); - msg.setExtension( - proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000); - msg.setExtension( - proto.jspb.test.extendOptionalUint32, 0x80000000); - msg.setExtension( - proto.jspb.test.extendOptionalUint64, 0xf000000000000000); - msg.setExtension( - proto.jspb.test.extendOptionalSint32, -100); - msg.setExtension( - proto.jspb.test.extendOptionalSint64, -0x8000000000000000); - msg.setExtension( - proto.jspb.test.extendOptionalFixed32, 1234); - msg.setExtension( - proto.jspb.test.extendOptionalFixed64, 0x1234567800000000); - msg.setExtension( - proto.jspb.test.extendOptionalSfixed32, -1234); + msg.setExtension(proto.jspb.test.extendOptionalInt64, -0x7fffffff00000000); + msg.setExtension(proto.jspb.test.extendOptionalUint32, 0x80000000); + msg.setExtension(proto.jspb.test.extendOptionalUint64, 0xf000000000000000); + msg.setExtension(proto.jspb.test.extendOptionalSint32, -100); + msg.setExtension(proto.jspb.test.extendOptionalSint64, -0x8000000000000000); + msg.setExtension(proto.jspb.test.extendOptionalFixed32, 1234); + msg.setExtension(proto.jspb.test.extendOptionalFixed64, 0x1234567800000000); + msg.setExtension(proto.jspb.test.extendOptionalSfixed32, -1234); msg.setExtension( proto.jspb.test.extendOptionalSfixed64, -0x1234567800000000); - msg.setExtension( - proto.jspb.test.extendOptionalFloat, 1.5); - msg.setExtension( - proto.jspb.test.extendOptionalDouble, -1.5); - msg.setExtension( - proto.jspb.test.extendOptionalBool, true); - msg.setExtension( - proto.jspb.test.extendOptionalString, 'hello world'); + msg.setExtension(proto.jspb.test.extendOptionalFloat, 1.5); + msg.setExtension(proto.jspb.test.extendOptionalDouble, -1.5); + msg.setExtension(proto.jspb.test.extendOptionalBool, true); + msg.setExtension(proto.jspb.test.extendOptionalString, 'hello world'); msg.setExtension(proto.jspb.test.extendOptionalBytes, BYTES); - var submsg = new proto.jspb.test.ExtendsWithMessage(); + let submsg = new proto.jspb.test.ExtendsWithMessage(); submsg.setFoo(16); msg.setExtension( proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg); @@ -548,118 +517,101 @@ describe('protoBinaryTest', function() { proto.jspb.test.ForeignEnum.FOREIGN_FOO); - msg.setExtension( - proto.jspb.test.extendRepeatedInt32List, [-42]); + msg.setExtension(proto.jspb.test.extendRepeatedInt32List, [-42]); msg.setExtension( proto.jspb.test.extendRepeatedInt64List, [-0x7fffffff00000000]); - msg.setExtension( - proto.jspb.test.extendRepeatedUint32List, [0x80000000]); + msg.setExtension(proto.jspb.test.extendRepeatedUint32List, [0x80000000]); msg.setExtension( proto.jspb.test.extendRepeatedUint64List, [0xf000000000000000]); - msg.setExtension( - proto.jspb.test.extendRepeatedSint32List, [-100]); + msg.setExtension(proto.jspb.test.extendRepeatedSint32List, [-100]); msg.setExtension( proto.jspb.test.extendRepeatedSint64List, [-0x8000000000000000]); - msg.setExtension( - proto.jspb.test.extendRepeatedFixed32List, [1234]); + msg.setExtension(proto.jspb.test.extendRepeatedFixed32List, [1234]); msg.setExtension( proto.jspb.test.extendRepeatedFixed64List, [0x1234567800000000]); - msg.setExtension( - proto.jspb.test.extendRepeatedSfixed32List, [-1234]); + msg.setExtension(proto.jspb.test.extendRepeatedSfixed32List, [-1234]); msg.setExtension( proto.jspb.test.extendRepeatedSfixed64List, [-0x1234567800000000]); - msg.setExtension( - proto.jspb.test.extendRepeatedFloatList, [1.5]); - msg.setExtension( - proto.jspb.test.extendRepeatedDoubleList, [-1.5]); - msg.setExtension( - proto.jspb.test.extendRepeatedBoolList, [true]); - msg.setExtension( - proto.jspb.test.extendRepeatedStringList, ['hello world']); + msg.setExtension(proto.jspb.test.extendRepeatedFloatList, [1.5]); + msg.setExtension(proto.jspb.test.extendRepeatedDoubleList, [-1.5]); + msg.setExtension(proto.jspb.test.extendRepeatedBoolList, [true]); + msg.setExtension(proto.jspb.test.extendRepeatedStringList, ['hello world']); msg.setExtension(proto.jspb.test.extendRepeatedBytesList, [BYTES]); submsg = new proto.jspb.test.ExtendsWithMessage(); submsg.setFoo(1000); msg.setExtension( proto.jspb.test.ExtendsWithMessage.repeatedExtensionList, [submsg]); - msg.setExtension(proto.jspb.test.extendRepeatedForeignEnumList, + msg.setExtension( + proto.jspb.test.extendRepeatedForeignEnumList, [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); - msg.setExtension( - proto.jspb.test.extendPackedRepeatedInt32List, [-42]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedInt32List, [-42]); msg.setExtension( proto.jspb.test.extendPackedRepeatedInt64List, [-0x7fffffff00000000]); msg.setExtension( proto.jspb.test.extendPackedRepeatedUint32List, [0x80000000]); msg.setExtension( proto.jspb.test.extendPackedRepeatedUint64List, [0xf000000000000000]); - msg.setExtension( - proto.jspb.test.extendPackedRepeatedSint32List, [-100]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedSint32List, [-100]); msg.setExtension( proto.jspb.test.extendPackedRepeatedSint64List, [-0x8000000000000000]); - msg.setExtension( - proto.jspb.test.extendPackedRepeatedFixed32List, [1234]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedFixed32List, [1234]); msg.setExtension( proto.jspb.test.extendPackedRepeatedFixed64List, [0x1234567800000000]); - msg.setExtension( - proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedSfixed32List, [-1234]); msg.setExtension( proto.jspb.test.extendPackedRepeatedSfixed64List, [-0x1234567800000000]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedFloatList, [1.5]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]); + msg.setExtension(proto.jspb.test.extendPackedRepeatedBoolList, [true]); msg.setExtension( - proto.jspb.test.extendPackedRepeatedFloatList, [1.5]); - msg.setExtension( - proto.jspb.test.extendPackedRepeatedDoubleList, [-1.5]); - msg.setExtension( - proto.jspb.test.extendPackedRepeatedBoolList, [true]); - msg.setExtension(proto.jspb.test.extendPackedRepeatedForeignEnumList, + proto.jspb.test.extendPackedRepeatedForeignEnumList, [proto.jspb.test.ForeignEnum.FOREIGN_FOO]); - } /** * Tests extension serialization and deserialization. */ - it('testExtensions', function() { - var msg = new proto.jspb.test.TestExtendable(); + it('testExtensions', () => { + const msg = new proto.jspb.test.TestExtendable(); fillExtensions(msg); - var encoded = msg.serializeBinary(); - var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); + const encoded = msg.serializeBinary(); + const decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); checkExtensions(decoded); }); /** * Tests that unknown extensions don't cause deserialization failure. */ - it('testUnknownExtension', function() { - var msg = new proto.jspb.test.TestExtendable(); + it('testUnknownExtension', () => { + const msg = new proto.jspb.test.TestExtendable(); fillExtensions(msg); - var writer = new jspb.BinaryWriter(); + const writer = new jspb.BinaryWriter(); writer.writeBool((1 << 29) - 1, true); proto.jspb.test.TestExtendable.serializeBinaryToWriter(msg, writer); - var encoded = writer.getResultBuffer(); - var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); + const encoded = writer.getResultBuffer(); + const decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded); checkExtensions(decoded); }); - it('testAnyWellKnownType', function() { - var any = new proto.google.protobuf.Any(); - var msg = new proto.jspb.test.TestAllTypes(); + it('testAnyWellKnownType', () => { + const any = new proto.google.protobuf.Any(); + const msg = new proto.jspb.test.TestAllTypes(); fillAllFields(msg); any.pack(msg.serializeBinary(), 'jspb.test.TestAllTypes'); - assertEquals('type.googleapis.com/jspb.test.TestAllTypes', - any.getTypeUrl()); + expect(any.getTypeUrl()) + .toEqual('type.googleapis.com/jspb.test.TestAllTypes'); - var msg2 = any.unpack( + const msg2 = any.unpack( proto.jspb.test.TestAllTypes.deserializeBinary, 'jspb.test.TestAllTypes'); checkAllFields(msg, msg2); - }); - }); diff --git a/binary/reader.js b/binary/reader.js index cdae1a4..f21b058 100644 --- a/binary/reader.js +++ b/binary/reader.js @@ -47,7 +47,7 @@ goog.provide('jspb.BinaryReader'); -goog.require('goog.asserts'); +goog.require('jspb.asserts'); goog.require('jspb.BinaryConstants'); goog.require('jspb.BinaryDecoder'); goog.require('jspb.utils'); @@ -121,8 +121,7 @@ jspb.BinaryReader.instanceCache_ = []; * we'll throw an assertion if we go off the end of the block. * @return {!jspb.BinaryReader} */ -jspb.BinaryReader.alloc = - function(opt_bytes, opt_start, opt_length) { +jspb.BinaryReader.alloc = function(opt_bytes, opt_start, opt_length) { if (jspb.BinaryReader.instanceCache_.length) { var newReader = jspb.BinaryReader.instanceCache_.pop(); if (opt_bytes) { @@ -286,7 +285,7 @@ jspb.BinaryReader.prototype.nextField = function() { // If we hit an error decoding the previous field, stop now before we // try to decode anything else if (this.getError()) { - goog.asserts.fail('Decoder hit an error'); + jspb.asserts.fail('Decoder hit an error'); return false; } @@ -305,7 +304,7 @@ jspb.BinaryReader.prototype.nextField = function() { nextWireType != jspb.BinaryConstants.WireType.DELIMITED && nextWireType != jspb.BinaryConstants.WireType.START_GROUP && nextWireType != jspb.BinaryConstants.WireType.END_GROUP) { - goog.asserts.fail( + jspb.asserts.fail( 'Invalid wire type: %s (at position %s)', nextWireType, this.fieldCursor_); this.error_ = true; @@ -349,7 +348,7 @@ jspb.BinaryReader.prototype.skipMatchingFields = function() { */ jspb.BinaryReader.prototype.skipVarintField = function() { if (this.nextWireType_ != jspb.BinaryConstants.WireType.VARINT) { - goog.asserts.fail('Invalid wire type for skipVarintField'); + jspb.asserts.fail('Invalid wire type for skipVarintField'); this.skipField(); return; } @@ -363,7 +362,7 @@ jspb.BinaryReader.prototype.skipVarintField = function() { */ jspb.BinaryReader.prototype.skipDelimitedField = function() { if (this.nextWireType_ != jspb.BinaryConstants.WireType.DELIMITED) { - goog.asserts.fail('Invalid wire type for skipDelimitedField'); + jspb.asserts.fail('Invalid wire type for skipDelimitedField'); this.skipField(); return; } @@ -378,7 +377,7 @@ jspb.BinaryReader.prototype.skipDelimitedField = function() { */ jspb.BinaryReader.prototype.skipFixed32Field = function() { if (this.nextWireType_ != jspb.BinaryConstants.WireType.FIXED32) { - goog.asserts.fail('Invalid wire type for skipFixed32Field'); + jspb.asserts.fail('Invalid wire type for skipFixed32Field'); this.skipField(); return; } @@ -392,7 +391,7 @@ jspb.BinaryReader.prototype.skipFixed32Field = function() { */ jspb.BinaryReader.prototype.skipFixed64Field = function() { if (this.nextWireType_ != jspb.BinaryConstants.WireType.FIXED64) { - goog.asserts.fail('Invalid wire type for skipFixed64Field'); + jspb.asserts.fail('Invalid wire type for skipFixed64Field'); this.skipField(); return; } @@ -408,15 +407,14 @@ jspb.BinaryReader.prototype.skipGroup = function() { var previousField = this.nextField_; do { if (!this.nextField()) { - goog.asserts.fail('Unmatched start-group tag: stream EOF'); + jspb.asserts.fail('Unmatched start-group tag: stream EOF'); this.error_ = true; return; } - if (this.nextWireType_ == - jspb.BinaryConstants.WireType.END_GROUP) { + if (this.nextWireType_ == jspb.BinaryConstants.WireType.END_GROUP) { // Group end: check that it matches top-of-stack. if (this.nextField_ != previousField) { - goog.asserts.fail('Unmatched end-group tag'); + jspb.asserts.fail('Unmatched end-group tag'); this.error_ = true; return; } @@ -449,7 +447,7 @@ jspb.BinaryReader.prototype.skipField = function() { this.skipGroup(); break; default: - goog.asserts.fail('Invalid wire encoding for field.'); + jspb.asserts.fail('Invalid wire encoding for field.'); } }; @@ -464,7 +462,7 @@ jspb.BinaryReader.prototype.registerReadCallback = function( if (this.readCallbacks_ === null) { this.readCallbacks_ = {}; } - goog.asserts.assert(!this.readCallbacks_[callbackName]); + jspb.asserts.assert(!this.readCallbacks_[callbackName]); this.readCallbacks_[callbackName] = callback; }; @@ -475,9 +473,9 @@ jspb.BinaryReader.prototype.registerReadCallback = function( * @return {*} The value returned by the callback. */ jspb.BinaryReader.prototype.runReadCallback = function(callbackName) { - goog.asserts.assert(this.readCallbacks_ !== null); + jspb.asserts.assert(this.readCallbacks_ !== null); var callback = this.readCallbacks_[callbackName]; - goog.asserts.assert(callback); + jspb.asserts.assert(callback); return callback(this); }; @@ -510,9 +508,9 @@ jspb.BinaryReader.prototype.readAny = function(fieldType) { case fieldTypes.STRING: return this.readString(); case fieldTypes.GROUP: - goog.asserts.fail('Group field type not supported in readAny()'); + jspb.asserts.fail('Group field type not supported in readAny()'); case fieldTypes.MESSAGE: - goog.asserts.fail('Message field type not supported in readAny()'); + jspb.asserts.fail('Message field type not supported in readAny()'); case fieldTypes.BYTES: return this.readBytes(); case fieldTypes.UINT32: @@ -532,7 +530,7 @@ jspb.BinaryReader.prototype.readAny = function(fieldType) { case fieldTypes.VHASH64: return this.readVarintHash64(); default: - goog.asserts.fail('Invalid field type in readAny()'); + jspb.asserts.fail('Invalid field type in readAny()'); } return 0; }; @@ -548,7 +546,7 @@ jspb.BinaryReader.prototype.readAny = function(fieldType) { * @export */ jspb.BinaryReader.prototype.readMessage = function(message, reader) { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED); // Save the current endpoint of the decoder and move it to the end of the @@ -577,20 +575,19 @@ jspb.BinaryReader.prototype.readMessage = function(message, reader) { * @param {function(T, !jspb.BinaryReader)} reader * @export */ -jspb.BinaryReader.prototype.readGroup = - function(field, message, reader) { +jspb.BinaryReader.prototype.readGroup = function(field, message, reader) { // Ensure that the wire type is correct. - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.START_GROUP); // Ensure that the field number is correct. - goog.asserts.assert(this.nextField_ == field); + jspb.asserts.assert(this.nextField_ == field); // Deserialize the message. The deserialization will stop at an END_GROUP tag. reader(message, this); if (!this.error_ && this.nextWireType_ != jspb.BinaryConstants.WireType.END_GROUP) { - goog.asserts.fail('Group submessage did not end with an END_GROUP tag'); + jspb.asserts.fail('Group submessage did not end with an END_GROUP tag'); this.error_ = true; } }; @@ -601,7 +598,7 @@ jspb.BinaryReader.prototype.readGroup = * @return {!jspb.BinaryDecoder} */ jspb.BinaryReader.prototype.getFieldDecoder = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED); var length = this.decoder_.readUnsignedVarint32(); @@ -623,7 +620,7 @@ jspb.BinaryReader.prototype.getFieldDecoder = function() { * @export */ jspb.BinaryReader.prototype.readInt32 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSignedVarint32(); }; @@ -639,7 +636,7 @@ jspb.BinaryReader.prototype.readInt32 = function() { * string. */ jspb.BinaryReader.prototype.readInt32String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSignedVarint32String(); }; @@ -653,7 +650,7 @@ jspb.BinaryReader.prototype.readInt32String = function() { * @export */ jspb.BinaryReader.prototype.readInt64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSignedVarint64(); }; @@ -669,7 +666,7 @@ jspb.BinaryReader.prototype.readInt64 = function() { * string. */ jspb.BinaryReader.prototype.readInt64String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSignedVarint64String(); }; @@ -683,7 +680,7 @@ jspb.BinaryReader.prototype.readInt64String = function() { * @export */ jspb.BinaryReader.prototype.readUint32 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readUnsignedVarint32(); }; @@ -699,7 +696,7 @@ jspb.BinaryReader.prototype.readUint32 = function() { * string. */ jspb.BinaryReader.prototype.readUint32String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readUnsignedVarint32String(); }; @@ -713,7 +710,7 @@ jspb.BinaryReader.prototype.readUint32String = function() { * @export */ jspb.BinaryReader.prototype.readUint64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readUnsignedVarint64(); }; @@ -729,7 +726,7 @@ jspb.BinaryReader.prototype.readUint64 = function() { * string. */ jspb.BinaryReader.prototype.readUint64String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readUnsignedVarint64String(); }; @@ -744,7 +741,7 @@ jspb.BinaryReader.prototype.readUint64String = function() { * @export */ jspb.BinaryReader.prototype.readSint32 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readZigzagVarint32(); }; @@ -759,7 +756,7 @@ jspb.BinaryReader.prototype.readSint32 = function() { * @export */ jspb.BinaryReader.prototype.readSint64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readZigzagVarint64(); }; @@ -770,10 +767,11 @@ jspb.BinaryReader.prototype.readSint64 = function() { * or throws an error if the next field in the stream is not of the correct * wire type. * - * @return {string} The value of the signed 64-bit integer field as a decimal string. + * @return {string} The value of the signed 64-bit integer field as a decimal + * string. */ jspb.BinaryReader.prototype.readSint64String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readZigzagVarint64String(); }; @@ -788,7 +786,7 @@ jspb.BinaryReader.prototype.readSint64String = function() { * @export */ jspb.BinaryReader.prototype.readFixed32 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32); return this.decoder_.readUint32(); }; @@ -803,7 +801,7 @@ jspb.BinaryReader.prototype.readFixed32 = function() { * @export */ jspb.BinaryReader.prototype.readFixed64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readUint64(); }; @@ -820,7 +818,7 @@ jspb.BinaryReader.prototype.readFixed64 = function() { * string. */ jspb.BinaryReader.prototype.readFixed64String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readUint64String(); }; @@ -835,7 +833,7 @@ jspb.BinaryReader.prototype.readFixed64String = function() { * @export */ jspb.BinaryReader.prototype.readSfixed32 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32); return this.decoder_.readInt32(); }; @@ -850,7 +848,7 @@ jspb.BinaryReader.prototype.readSfixed32 = function() { * string. */ jspb.BinaryReader.prototype.readSfixed32String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32); return this.decoder_.readInt32().toString(); }; @@ -865,7 +863,7 @@ jspb.BinaryReader.prototype.readSfixed32String = function() { * @export */ jspb.BinaryReader.prototype.readSfixed64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readInt64(); }; @@ -881,7 +879,7 @@ jspb.BinaryReader.prototype.readSfixed64 = function() { * @return {string} The value of the sfixed64 field as a decimal string. */ jspb.BinaryReader.prototype.readSfixed64String = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readInt64String(); }; @@ -895,7 +893,7 @@ jspb.BinaryReader.prototype.readSfixed64String = function() { * @export */ jspb.BinaryReader.prototype.readFloat = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED32); return this.decoder_.readFloat(); }; @@ -909,7 +907,7 @@ jspb.BinaryReader.prototype.readFloat = function() { * @export */ jspb.BinaryReader.prototype.readDouble = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readDouble(); }; @@ -923,7 +921,7 @@ jspb.BinaryReader.prototype.readDouble = function() { * @export */ jspb.BinaryReader.prototype.readBool = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return !!this.decoder_.readUnsignedVarint32(); }; @@ -937,7 +935,7 @@ jspb.BinaryReader.prototype.readBool = function() { * @export */ jspb.BinaryReader.prototype.readEnum = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSignedVarint64(); }; @@ -951,7 +949,7 @@ jspb.BinaryReader.prototype.readEnum = function() { * @export */ jspb.BinaryReader.prototype.readString = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED); var length = this.decoder_.readUnsignedVarint32(); return this.decoder_.readString(length); @@ -966,7 +964,7 @@ jspb.BinaryReader.prototype.readString = function() { * @export */ jspb.BinaryReader.prototype.readBytes = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED); var length = this.decoder_.readUnsignedVarint32(); return this.decoder_.readBytes(length); @@ -981,7 +979,7 @@ jspb.BinaryReader.prototype.readBytes = function() { * @return {string} The hash value. */ jspb.BinaryReader.prototype.readVarintHash64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readVarintHash64(); }; @@ -995,7 +993,7 @@ jspb.BinaryReader.prototype.readVarintHash64 = function() { * @return {string} The hash value. */ jspb.BinaryReader.prototype.readSintHash64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readZigzagVarintHash64(); }; @@ -1012,7 +1010,7 @@ jspb.BinaryReader.prototype.readSintHash64 = function() { * @template T */ jspb.BinaryReader.prototype.readSplitVarint64 = function(convert) { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSplitVarint64(convert); }; @@ -1029,7 +1027,7 @@ jspb.BinaryReader.prototype.readSplitVarint64 = function(convert) { * @template T */ jspb.BinaryReader.prototype.readSplitZigzagVarint64 = function(convert) { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.VARINT); return this.decoder_.readSplitVarint64(function(lowBits, highBits) { return jspb.utils.fromZigzag64(lowBits, highBits, convert); @@ -1045,7 +1043,7 @@ jspb.BinaryReader.prototype.readSplitZigzagVarint64 = function(convert) { * @return {string} The hash value. */ jspb.BinaryReader.prototype.readFixedHash64 = function() { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readFixedHash64(); }; @@ -1062,7 +1060,7 @@ jspb.BinaryReader.prototype.readFixedHash64 = function() { * @template T */ jspb.BinaryReader.prototype.readSplitFixed64 = function(convert) { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.FIXED64); return this.decoder_.readSplitFixed64(convert); }; @@ -1075,7 +1073,7 @@ jspb.BinaryReader.prototype.readSplitFixed64 = function(convert) { * @private */ jspb.BinaryReader.prototype.readPackedField_ = function(decodeMethod) { - goog.asserts.assert( + jspb.asserts.assert( this.nextWireType_ == jspb.BinaryConstants.WireType.DELIMITED); var length = this.decoder_.readUnsignedVarint32(); var end = this.decoder_.getCursor() + length; diff --git a/binary/reader_test.js b/binary/reader_test.js index 6963f77..dbbbb71 100644 --- a/binary/reader_test.js +++ b/binary/reader_test.js @@ -41,26 +41,26 @@ * @author aappleby@google.com (Austin Appleby) */ -goog.require('goog.testing.asserts'); goog.require('jspb.BinaryConstants'); goog.require('jspb.BinaryDecoder'); goog.require('jspb.BinaryReader'); goog.require('jspb.BinaryWriter'); goog.require('jspb.utils'); + goog.requireType('jspb.BinaryMessage'); -describe('binaryReaderTest', function() { +describe('binaryReaderTest', () => { /** * Tests the reader instance cache. */ - it('testInstanceCaches', /** @suppress {visibility} */ function() { - var writer = new jspb.BinaryWriter(); - var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); + it('testInstanceCaches', /** @suppress {visibility} */ () => { + const writer = new jspb.BinaryWriter(); + const dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); writer.writeMessage(1, dummyMessage, () => {}); writer.writeMessage(2, dummyMessage, () => {}); - var buffer = writer.getResultBuffer(); + const buffer = writer.getResultBuffer(); // Empty the instance caches. jspb.BinaryReader.instanceCache_ = []; @@ -68,53 +68,53 @@ describe('binaryReaderTest', function() { // Allocating and then freeing three decoders should leave us with three in // the cache. - var decoder1 = jspb.BinaryDecoder.alloc(); - var decoder2 = jspb.BinaryDecoder.alloc(); - var decoder3 = jspb.BinaryDecoder.alloc(); + const decoder1 = jspb.BinaryDecoder.alloc(); + const decoder2 = jspb.BinaryDecoder.alloc(); + const decoder3 = jspb.BinaryDecoder.alloc(); decoder1.free(); decoder2.free(); decoder3.free(); - assertEquals(3, jspb.BinaryDecoder.instanceCache_.length); - assertEquals(0, jspb.BinaryReader.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(3); + expect(jspb.BinaryReader.instanceCache_.length).toEqual(0); // Allocating and then freeing a reader should remove one decoder from its // cache, but it should stay stuck to the reader afterwards since we can't // have a reader without a decoder. jspb.BinaryReader.alloc().free(); - assertEquals(2, jspb.BinaryDecoder.instanceCache_.length); - assertEquals(1, jspb.BinaryReader.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(2); + expect(jspb.BinaryReader.instanceCache_.length).toEqual(1); // Allocating a reader should remove a reader from the cache. - var reader = jspb.BinaryReader.alloc(buffer); + const reader = jspb.BinaryReader.alloc(buffer); - assertEquals(2, jspb.BinaryDecoder.instanceCache_.length); - assertEquals(0, jspb.BinaryReader.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(2); + expect(jspb.BinaryReader.instanceCache_.length).toEqual(0); // Processing the message reuses the current reader. reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - reader.readMessage(dummyMessage, function() { - assertEquals(0, jspb.BinaryReader.instanceCache_.length); - }); + expect(reader.getFieldNumber()).toEqual(1); + reader.readMessage(dummyMessage, () => { + expect(jspb.BinaryReader.instanceCache_.length).toEqual(0); + }); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - reader.readMessage(dummyMessage, function() { - assertEquals(0, jspb.BinaryReader.instanceCache_.length); - }); + expect(reader.getFieldNumber()).toEqual(2); + reader.readMessage(dummyMessage, () => { + expect(jspb.BinaryReader.instanceCache_.length).toEqual(0); + }); - assertEquals(false, reader.nextField()); + expect(reader.nextField()).toEqual(false); - assertEquals(2, jspb.BinaryDecoder.instanceCache_.length); - assertEquals(0, jspb.BinaryReader.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(2); + expect(jspb.BinaryReader.instanceCache_.length).toEqual(0); // Freeing the reader should put it back into the cache. reader.free(); - assertEquals(2, jspb.BinaryDecoder.instanceCache_.length); - assertEquals(1, jspb.BinaryReader.instanceCache_.length); + expect(jspb.BinaryDecoder.instanceCache_.length).toEqual(2); + expect(jspb.BinaryReader.instanceCache_.length).toEqual(1); }); @@ -123,7 +123,7 @@ describe('binaryReaderTest', function() { * @return {number} */ function truncate(x) { - var temp = new Float32Array(1); + const temp = new Float32Array(1); temp[0] = x; return temp[0]; } @@ -132,105 +132,105 @@ describe('binaryReaderTest', function() { /** * Verifies that misuse of the reader class triggers assertions. */ - it('testReadErrors', /** @suppress {checkTypes|visibility} */ function() { - // Calling readMessage on a non-delimited field should trigger an - // assertion. - var reader = jspb.BinaryReader.alloc([8, 1]); - var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); - reader.nextField(); - assertThrows(function() { - reader.readMessage(dummyMessage, () => {}); - }); - - // Reading past the end of the stream should trigger an assertion. - reader = jspb.BinaryReader.alloc([9, 1]); - reader.nextField(); - assertThrows(function() { - reader.readFixed64() - }); - - // Reading past the end of a submessage should trigger an assertion. - reader = jspb.BinaryReader.alloc([10, 4, 13, 1, 1, 1]); - reader.nextField(); - reader.readMessage(dummyMessage, function() { + it('testReadErrors', /** @suppress {checkTypes|visibility} */ () => { + // Calling readMessage on a non-delimited field should trigger an + // assertion. + let reader = jspb.BinaryReader.alloc([8, 1]); + const dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); reader.nextField(); - assertThrows(function() { - reader.readFixed32() - }); - }); + expect(() => { + reader.readMessage(dummyMessage, () => { }); + }).toThrow(); - // Skipping an invalid field should trigger an assertion. - reader = jspb.BinaryReader.alloc([12, 1]); - reader.nextWireType_ = 1000; - assertThrows(function() { - reader.skipField() - }); + // Reading past the end of the stream should trigger an assertion. + reader = jspb.BinaryReader.alloc([9, 1]); + reader.nextField(); + expect(() => { + reader.readFixed64(); + }).toThrow(); - // Reading fields with the wrong wire type should assert. - reader = jspb.BinaryReader.alloc([9, 0, 0, 0, 0, 0, 0, 0, 0]); - reader.nextField(); - assertThrows(function() { - reader.readInt32() - }); - assertThrows(function() { - reader.readInt32String() - }); - assertThrows(function() { - reader.readInt64() - }); - assertThrows(function() { - reader.readInt64String() - }); - assertThrows(function() { - reader.readUint32() - }); - assertThrows(function() { - reader.readUint32String() - }); - assertThrows(function() { - reader.readUint64() - }); - assertThrows(function() { - reader.readUint64String() - }); - assertThrows(function() { - reader.readSint32() - }); - assertThrows(function() { - reader.readBool() - }); - assertThrows(function() { - reader.readEnum() - }); + // Reading past the end of a submessage should trigger an assertion. + reader = jspb.BinaryReader.alloc([10, 4, 13, 1, 1, 1]); + reader.nextField(); + reader.readMessage(dummyMessage, () => { + reader.nextField(); + expect(() => { + reader.readFixed32(); + }).toThrow(); + }); - reader = jspb.BinaryReader.alloc([8, 1]); - reader.nextField(); - assertThrows(function() { - reader.readFixed32() - }); - assertThrows(function() { - reader.readFixed64() - }); - assertThrows(function() { - reader.readSfixed32() - }); - assertThrows(function() { - reader.readSfixed64() - }); - assertThrows(function() { - reader.readFloat() - }); - assertThrows(function() { - reader.readDouble() - }); + // Skipping an invalid field should trigger an assertion. + reader = jspb.BinaryReader.alloc([12, 1]); + reader.nextWireType_ = 1000; + expect(() => { + reader.skipField(); + }).toThrow(); - assertThrows(function() { - reader.readString() - }); - assertThrows(function() { - reader.readBytes() + // Reading fields with the wrong wire type should assert. + reader = jspb.BinaryReader.alloc([9, 0, 0, 0, 0, 0, 0, 0, 0]); + reader.nextField(); + expect(() => { + reader.readInt32(); + }).toThrow(); + expect(function () { + reader.readInt32String(); + }).toThrow(); + expect(function () { + reader.readInt64(); + }).toThrow(); + expect(function () { + reader.readInt64String(); + }).toThrow(); + expect(function () { + reader.readUint32(); + }).toThrow(); + expect(function () { + reader.readUint32String(); + }).toThrow(); + expect(function () { + reader.readUint64(); + }).toThrow(); + expect(function () { + reader.readUint64String(); + }).toThrow(); + expect(function () { + reader.readSint32(); + }).toThrow(); + expect(function () { + reader.readBool(); + }).toThrow(); + expect(function () { + reader.readEnum(); + }).toThrow(); + + reader = jspb.BinaryReader.alloc([8, 1]); + reader.nextField(); + expect(function () { + reader.readFixed32(); + }).toThrow(); + expect(function () { + reader.readFixed64(); + }).toThrow(); + expect(function () { + reader.readSfixed32(); + }).toThrow(); + expect(function () { + reader.readSfixed64(); + }).toThrow(); + expect(function () { + reader.readFloat(); + }).toThrow(); + expect(function () { + reader.readDouble(); + }).toThrow(); + + expect(function () { + reader.readString(); + }).toThrow(); + expect(function () { + reader.readBytes(); + }).toThrow(); }); - }); /** @@ -243,12 +243,12 @@ describe('binaryReaderTest', function() { * @private * @suppress {missingProperties} */ - var doTestUnsignedField_ = function( + const doTestUnsignedField_ = function( readField, writeField, epsilon, upperLimit, filter) { - assertNotNull(readField); - assertNotNull(writeField); + expect(readField).not.toBeNull(); + expect(writeField).not.toBeNull(); - var writer = new jspb.BinaryWriter(); + const writer = new jspb.BinaryWriter(); // Encode zero and limits. writeField.call(writer, 1, filter(0)); @@ -256,27 +256,27 @@ describe('binaryReaderTest', function() { writeField.call(writer, 3, filter(upperLimit)); // Encode positive values. - for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { + for (let cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { writeField.call(writer, 4, filter(cursor)); } - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); // Check zero and limits. reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - assertEquals(filter(0), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(1); + expect(readField.call(reader)).toEqual(filter(0)); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - assertEquals(filter(epsilon), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(2); + expect(readField.call(reader)).toEqual(filter(epsilon)); reader.nextField(); - assertEquals(3, reader.getFieldNumber()); - assertEquals(filter(upperLimit), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(3); + expect(readField.call(reader)).toEqual(filter(upperLimit)); // Check positive values. - for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { + for (let cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { reader.nextField(); if (4 != reader.getFieldNumber()) throw 'fail!'; if (filter(cursor) != readField.call(reader)) throw 'fail!'; @@ -295,9 +295,9 @@ describe('binaryReaderTest', function() { * @private * @suppress {missingProperties} */ - var doTestSignedField_ = function( + const doTestSignedField_ = function( readField, writeField, epsilon, lowerLimit, upperLimit, filter) { - var writer = new jspb.BinaryWriter(); + const writer = new jspb.BinaryWriter(); // Encode zero and limits. writeField.call(writer, 1, filter(lowerLimit)); @@ -306,50 +306,50 @@ describe('binaryReaderTest', function() { writeField.call(writer, 4, filter(epsilon)); writeField.call(writer, 5, filter(upperLimit)); - var inputValues = []; + const inputValues = []; // Encode negative values. - for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) { - var val = filter(cursor); + for (let cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) { + const val = filter(cursor); writeField.call(writer, 6, val); inputValues.push({fieldNumber: 6, value: val}); } // Encode positive values. - for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { - var val = filter(cursor); + for (let cursor = epsilon; cursor < upperLimit; cursor *= 1.1) { + const val = filter(cursor); writeField.call(writer, 7, val); inputValues.push({fieldNumber: 7, value: val}); } - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); // Check zero and limits. reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - assertEquals(filter(lowerLimit), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(1); + expect(readField.call(reader)).toEqual(filter(lowerLimit)); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - assertEquals(filter(-epsilon), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(2); + expect(readField.call(reader)).toEqual(filter(-epsilon)); reader.nextField(); - assertEquals(3, reader.getFieldNumber()); - assertEquals(filter(0), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(3); + expect(readField.call(reader)).toEqual(filter(0)); reader.nextField(); - assertEquals(4, reader.getFieldNumber()); - assertEquals(filter(epsilon), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(4); + expect(readField.call(reader)).toEqual(filter(epsilon)); reader.nextField(); - assertEquals(5, reader.getFieldNumber()); - assertEquals(filter(upperLimit), readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(5); + expect(readField.call(reader)).toEqual(filter(upperLimit)); - for (var i = 0; i < inputValues.length; i++) { - var expected = inputValues[i]; + for (let i = 0; i < inputValues.length; i++) { + const expected = inputValues[i]; reader.nextField(); - assertEquals(expected.fieldNumber, reader.getFieldNumber()); - assertEquals(expected.value, readField.call(reader)); + expect(reader.getFieldNumber()).toEqual(expected.fieldNumber); + expect(readField.call(reader)).toEqual(expected.value); } }; @@ -357,13 +357,13 @@ describe('binaryReaderTest', function() { /** * Tests fields that use varint encoding. */ - it('testVarintFields', function() { - assertNotUndefined(jspb.BinaryReader.prototype.readUint32); - assertNotUndefined(jspb.BinaryWriter.prototype.writeUint32); - assertNotUndefined(jspb.BinaryReader.prototype.readUint64); - assertNotUndefined(jspb.BinaryWriter.prototype.writeUint64); - assertNotUndefined(jspb.BinaryReader.prototype.readBool); - assertNotUndefined(jspb.BinaryWriter.prototype.writeBool); + it('testVarintFields', () => { + expect(jspb.BinaryReader.prototype.readUint32).not.toBeUndefined(); + expect(jspb.BinaryWriter.prototype.writeUint32).not.toBeUndefined(); + expect(jspb.BinaryReader.prototype.readUint64).not.toBeUndefined(); + expect(jspb.BinaryWriter.prototype.writeUint64).not.toBeUndefined(); + expect(jspb.BinaryReader.prototype.readBool).not.toBeUndefined(); + expect(jspb.BinaryWriter.prototype.writeBool).not.toBeUndefined(); doTestUnsignedField_( jspb.BinaryReader.prototype.readUint32, jspb.BinaryWriter.prototype.writeUint32, 1, Math.pow(2, 32) - 1, @@ -404,25 +404,25 @@ describe('binaryReaderTest', function() { * @param {string} hexString */ function doTestHexStringVarint_(readField, expected, hexString) { - var bytesCount = (hexString.length + 1) / 3; - var bytes = new Uint8Array(bytesCount); - for (var i = 0; i < bytesCount; i++) { + const bytesCount = (hexString.length + 1) / 3; + const bytes = new Uint8Array(bytesCount); + for (let i = 0; i < bytesCount; i++) { bytes[i] = parseInt(hexString.substring(i * 3, i * 3 + 2), 16); } - var reader = jspb.BinaryReader.alloc(bytes); + const reader = jspb.BinaryReader.alloc(bytes); reader.nextField(); - assertEquals(expected, readField.call(reader)); + expect(readField.call(reader)).toEqual(expected); } /** * Tests non-canonical redundant varint decoding. */ - it('testRedundantVarintFields', function() { - assertNotNull(jspb.BinaryReader.prototype.readUint32); - assertNotNull(jspb.BinaryReader.prototype.readUint64); - assertNotNull(jspb.BinaryReader.prototype.readSint32); - assertNotNull(jspb.BinaryReader.prototype.readSint64); + it('testRedundantVarintFields', () => { + expect(jspb.BinaryReader.prototype.readUint32).not.toBeNull(); + expect(jspb.BinaryReader.prototype.readUint64).not.toBeNull(); + expect(jspb.BinaryReader.prototype.readSint32).not.toBeNull(); + expect(jspb.BinaryReader.prototype.readSint64).not.toBeNull(); // uint32 and sint32 take no more than 5 bytes // 08 - field prefix (type = 0 means varint) @@ -448,12 +448,12 @@ describe('binaryReaderTest', function() { /** * Tests reading 64-bit integers as split values. */ - it('handles split 64 fields', function() { - var writer = new jspb.BinaryWriter(); + it('handles split 64 fields', () => { + const writer = new jspb.BinaryWriter(); writer.writeInt64String(1, '4294967296'); writer.writeSfixed64String(2, '4294967298'); writer.writeInt64String(3, '3'); // 3 is the zig-zag encoding of -2. - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); function rejoin(lowBits, highBits) { return highBits * 2 ** 32 + (lowBits >>> 0); @@ -474,36 +474,36 @@ describe('binaryReaderTest', function() { /** * Tests 64-bit fields that are handled as strings. */ - it('testStringInt64Fields', function() { - var writer = new jspb.BinaryWriter(); + it('testStringInt64Fields', () => { + const writer = new jspb.BinaryWriter(); - var testSignedData = [ + const testSignedData = [ '2730538252207801776', '-2688470994844604560', '3398529779486536359', '3568577411627971000', '272477188847484900', '-6649058714086158188', '-7695254765712060806', '-4525541438037104029', '-4993706538836508568', '4990160321893729138' ]; - var testUnsignedData = [ + const testUnsignedData = [ '7822732630241694882', '6753602971916687352', '2399935075244442116', '8724292567325338867', '16948784802625696584', '4136275908516066934', '3575388346793700364', '5167142028379259461', '1557573948689737699', '17100725280812548567' ]; - for (var i = 0; i < testSignedData.length; i++) { + for (let i = 0; i < testSignedData.length; i++) { writer.writeInt64String(2 * i + 1, testSignedData[i]); writer.writeUint64String(2 * i + 2, testUnsignedData[i]); } - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); - for (var i = 0; i < testSignedData.length; i++) { + for (let i = 0; i < testSignedData.length; i++) { reader.nextField(); - assertEquals(2 * i + 1, reader.getFieldNumber()); - assertEquals(testSignedData[i], reader.readInt64String()); + expect(reader.getFieldNumber()).toEqual(2 * i + 1); + expect(testSignedData[i]).toEqual(reader.readInt64String()); reader.nextField(); - assertEquals(2 * i + 2, reader.getFieldNumber()); - assertEquals(testUnsignedData[i], reader.readUint64String()); + expect(reader.getFieldNumber()).toEqual(2 * i + 2); + expect(testUnsignedData[i]).toEqual(reader.readUint64String()); } }); @@ -511,7 +511,7 @@ describe('binaryReaderTest', function() { /** * Tests fields that use zigzag encoding. */ - it('testZigzagFields', function() { + it('testZigzagFields', () => { doTestSignedField_( jspb.BinaryReader.prototype.readSint32, jspb.BinaryWriter.prototype.writeSint32, 1, -Math.pow(2, 31), @@ -532,7 +532,7 @@ describe('binaryReaderTest', function() { /** * Tests fields that use fixed-length encoding. */ - it('testFixedFields', function() { + it('testFixedFields', () => { doTestUnsignedField_( jspb.BinaryReader.prototype.readFixed32, jspb.BinaryWriter.prototype.writeFixed32, 1, Math.pow(2, 32) - 1, @@ -558,7 +558,7 @@ describe('binaryReaderTest', function() { /** * Tests floating point fields. */ - it('testFloatFields', function() { + it('testFloatFields', () => { doTestSignedField_( jspb.BinaryReader.prototype.readFloat, jspb.BinaryWriter.prototype.writeFloat, @@ -579,55 +579,55 @@ describe('binaryReaderTest', function() { /** * Tests length-delimited string fields. */ - it('testStringFields', function() { - var s1 = 'The quick brown fox jumps over the lazy dog.'; - var s2 = '人人生而自由,在尊嚴和權利上一律平等。'; + it('testStringFields', () => { + const s1 = 'The quick brown fox jumps over the lazy dog.'; + const s2 = '人人生而自由,在尊嚴和權利上一律平等。'; - var writer = new jspb.BinaryWriter(); + const writer = new jspb.BinaryWriter(); writer.writeString(1, s1); writer.writeString(2, s2); - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - assertEquals(s1, reader.readString()); + expect(reader.getFieldNumber()).toEqual(1); + expect(reader.readString()).toEqual(s1); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - assertEquals(s2, reader.readString()); + expect(reader.getFieldNumber()).toEqual(2); + expect(reader.readString()).toEqual(s2); }); /** * Tests length-delimited byte fields. */ - it('testByteFields', function() { - var message = []; - var lowerLimit = 1; - var upperLimit = 256; - var scale = 1.1; + it('testByteFields', () => { + const message = []; + const lowerLimit = 1; + const upperLimit = 256; + const scale = 1.1; - var writer = new jspb.BinaryWriter(); + const writer = new jspb.BinaryWriter(); - for (var cursor = lowerLimit; cursor < upperLimit; cursor *= 1.1) { - var len = Math.round(cursor); - var bytes = []; - for (var i = 0; i < len; i++) bytes.push(i % 256); + for (let cursor = lowerLimit; cursor < upperLimit; cursor *= 1.1) { + const len = Math.round(cursor); + const bytes = []; + for (let i = 0; i < len; i++) bytes.push(i % 256); writer.writeBytes(len, bytes); } - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); - for (var cursor = lowerLimit; reader.nextField(); cursor *= 1.1) { - var len = Math.round(cursor); + for (let cursor = lowerLimit; reader.nextField(); cursor *= 1.1) { + const len = Math.round(cursor); if (len != reader.getFieldNumber()) throw 'fail!'; - var bytes = reader.readBytes(); + const bytes = reader.readBytes(); if (len != bytes.length) throw 'fail!'; - for (var i = 0; i < bytes.length; i++) { + for (let i = 0; i < bytes.length; i++) { if (i % 256 != bytes[i]) throw 'fail!'; } } @@ -637,14 +637,14 @@ describe('binaryReaderTest', function() { /** * Tests nested messages. */ - it('testNesting', function() { - var writer = new jspb.BinaryWriter(); - var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); + it('testNesting', () => { + const writer = new jspb.BinaryWriter(); + const dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); writer.writeInt32(1, 100); // Add one message with 3 int fields. - writer.writeMessage(2, dummyMessage, function() { + writer.writeMessage(2, dummyMessage, () => { writer.writeInt32(3, 300); writer.writeInt32(4, 400); writer.writeInt32(5, 500); @@ -655,56 +655,56 @@ describe('binaryReaderTest', function() { writer.writeInt32(7, 700); - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); // Validate outermost message. reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - assertEquals(100, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(1); + expect(100).toEqual(reader.readInt32()); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - reader.readMessage(dummyMessage, function() { + expect(reader.getFieldNumber()).toEqual(2); + reader.readMessage(dummyMessage, () => { // Validate embedded message 1. reader.nextField(); - assertEquals(3, reader.getFieldNumber()); - assertEquals(300, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(3); + expect(300).toEqual(reader.readInt32()); reader.nextField(); - assertEquals(4, reader.getFieldNumber()); - assertEquals(400, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(4); + expect(400).toEqual(reader.readInt32()); reader.nextField(); - assertEquals(5, reader.getFieldNumber()); - assertEquals(500, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(5); + expect(500).toEqual(reader.readInt32()); - assertEquals(false, reader.nextField()); + expect(reader.nextField()).toEqual(false); }); reader.nextField(); - assertEquals(6, reader.getFieldNumber()); - reader.readMessage(dummyMessage, function() { + expect(reader.getFieldNumber()).toEqual(6); + reader.readMessage(dummyMessage, () => { // Validate embedded message 2. - assertEquals(false, reader.nextField()); + expect(reader.nextField()).toEqual(false); }); reader.nextField(); - assertEquals(7, reader.getFieldNumber()); - assertEquals(700, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(7); + expect(700).toEqual(reader.readInt32()); - assertEquals(false, reader.nextField()); + expect(reader.nextField()).toEqual(false); }); /** * Tests skipping fields of each type by interleaving them with sentinel * values and skipping everything that's not a sentinel. */ - it('testSkipField', function() { - var writer = new jspb.BinaryWriter(); + it('testSkipField', () => { + const writer = new jspb.BinaryWriter(); - var sentinel = 123456789; + const sentinel = 123456789; // Write varint fields of different sizes. writer.writeInt32(1, sentinel); @@ -732,8 +732,8 @@ describe('binaryReaderTest', function() { // Write a group with a nested group inside. writer.writeInt32(5, sentinel); - var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); - writer.writeGroup(5, dummyMessage, function() { + const dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); + writer.writeGroup(5, dummyMessage, () => { // Previously the skipGroup implementation was wrong, which only consume // the decoder by nextField. This case is for making the previous // implementation failed in skipGroup by an early end group tag. @@ -747,7 +747,7 @@ describe('binaryReaderTest', function() { // varint. The bytes have at least 9 consecutive minus byte, which will // fail in this.nextField for previous implementation. writer.writeBytes(43, [255, 255, 255, 255, 255, 255, 255, 255, 255, 255]); - writer.writeGroup(6, dummyMessage, function() { + writer.writeGroup(6, dummyMessage, () => { writer.writeInt64(84, 42); writer.writeInt64(84, 44); writer.writeBytes( @@ -758,10 +758,10 @@ describe('binaryReaderTest', function() { // Write final sentinel. writer.writeInt32(6, sentinel); - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); function skip(field, count) { - for (var i = 0; i < count; i++) { + for (let i = 0; i < count; i++) { reader.nextField(); if (field != reader.getFieldNumber()) throw 'fail!'; reader.skipField(); @@ -769,51 +769,51 @@ describe('binaryReaderTest', function() { } reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - assertEquals(sentinel, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(1); + expect(sentinel).toEqual(reader.readInt32()); skip(1, 4); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - assertEquals(sentinel, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(2); + expect(sentinel).toEqual(reader.readInt32()); skip(2, 3); reader.nextField(); - assertEquals(3, reader.getFieldNumber()); - assertEquals(sentinel, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(3); + expect(sentinel).toEqual(reader.readInt32()); skip(3, 3); reader.nextField(); - assertEquals(4, reader.getFieldNumber()); - assertEquals(sentinel, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(4); + expect(sentinel).toEqual(reader.readInt32()); skip(4, 2); reader.nextField(); - assertEquals(5, reader.getFieldNumber()); - assertEquals(sentinel, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(5); + expect(sentinel).toEqual(reader.readInt32()); skip(5, 1); reader.nextField(); - assertEquals(6, reader.getFieldNumber()); - assertEquals(sentinel, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(6); + expect(sentinel).toEqual(reader.readInt32()); }); /** * Tests packed fields. */ - it('testPackedFields', function() { - var writer = new jspb.BinaryWriter(); + it('testPackedFields', () => { + const writer = new jspb.BinaryWriter(); - var sentinel = 123456789; + const sentinel = 123456789; - var unsignedData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - var signedData = [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]; - var floatData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10]; - var doubleData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10]; - var boolData = [true, false, true, true, false, false, true, false]; + const unsignedData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + const signedData = [-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]; + const floatData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10]; + const doubleData = [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10]; + const boolData = [true, false, true, true, false, false, true, false]; - for (var i = 0; i < floatData.length; i++) { + for (let i = 0; i < floatData.length; i++) { floatData[i] = truncate(floatData[i]); } @@ -836,55 +836,55 @@ describe('binaryReaderTest', function() { writer.writeInt32(3, sentinel); - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); reader.nextField(); - assertEquals(sentinel, reader.readInt32()); + expect(sentinel).toEqual(reader.readInt32()); reader.nextField(); - assertElementsEquals(reader.readPackedInt32(), signedData); + expect(signedData).toEqual(reader.readPackedInt32()); reader.nextField(); - assertElementsEquals(reader.readPackedInt64(), signedData); + expect(signedData).toEqual(reader.readPackedInt64()); reader.nextField(); - assertElementsEquals(reader.readPackedUint32(), unsignedData); + expect(unsignedData).toEqual(reader.readPackedUint32()); reader.nextField(); - assertElementsEquals(reader.readPackedUint64(), unsignedData); + expect(unsignedData).toEqual(reader.readPackedUint64()); reader.nextField(); - assertElementsEquals(reader.readPackedSint32(), signedData); + expect(signedData).toEqual(reader.readPackedSint32()); reader.nextField(); - assertElementsEquals(reader.readPackedSint64(), signedData); + expect(signedData).toEqual(reader.readPackedSint64()); reader.nextField(); - assertElementsEquals(reader.readPackedFixed32(), unsignedData); + expect(unsignedData).toEqual(reader.readPackedFixed32()); reader.nextField(); - assertElementsEquals(reader.readPackedFixed64(), unsignedData); + expect(unsignedData).toEqual(reader.readPackedFixed64()); reader.nextField(); - assertElementsEquals(reader.readPackedSfixed32(), signedData); + expect(signedData).toEqual(reader.readPackedSfixed32()); reader.nextField(); - assertElementsEquals(reader.readPackedSfixed64(), signedData); + expect(signedData).toEqual(reader.readPackedSfixed64()); reader.nextField(); - assertElementsEquals(reader.readPackedFloat(), floatData); + expect(floatData).toEqual(reader.readPackedFloat()); reader.nextField(); - assertElementsEquals(reader.readPackedDouble(), doubleData); + expect(doubleData).toEqual(reader.readPackedDouble()); reader.nextField(); - assertElementsEquals(reader.readPackedBool(), boolData); + expect(boolData).toEqual(reader.readPackedBool()); reader.nextField(); - assertElementsEquals(reader.readPackedEnum(), unsignedData); + expect(unsignedData).toEqual(reader.readPackedEnum()); reader.nextField(); - assertEquals(sentinel, reader.readInt32()); + expect(sentinel).toEqual(reader.readInt32()); }); @@ -893,17 +893,17 @@ describe('binaryReaderTest', function() { * relative to the start of the outermost blob, not the start of their parent * blob. */ - it('testNestedBlobs', function() { + it('testNestedBlobs', () => { // Create a proto consisting of two nested messages, with the inner one // containing a blob of bytes. - var fieldTag = (1 << 3) | jspb.BinaryConstants.WireType.DELIMITED; - var blob = [1, 2, 3, 4, 5]; - var writer = new jspb.BinaryWriter(); - var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); + const fieldTag = (1 << 3) | jspb.BinaryConstants.WireType.DELIMITED; + const blob = [1, 2, 3, 4, 5]; + const writer = new jspb.BinaryWriter(); + const dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); - writer.writeMessage(1, dummyMessage, function() { - writer.writeMessage(1, dummyMessage, function() { + writer.writeMessage(1, dummyMessage, () => { + writer.writeMessage(1, dummyMessage, () => { writer.writeBytes(1, blob); }); }); @@ -912,33 +912,34 @@ describe('binaryReaderTest', function() { // of overhead, one for the field tag and one for the length of the inner // blob. - var decoder1 = new jspb.BinaryDecoder(writer.getResultBuffer()); - assertEquals(fieldTag, decoder1.readUnsignedVarint32()); - assertEquals(blob.length + 4, decoder1.readUnsignedVarint32()); + const decoder1 = new jspb.BinaryDecoder(writer.getResultBuffer()); + expect(fieldTag).toEqual(decoder1.readUnsignedVarint32()); + expect(blob.length + 4).toEqual(decoder1.readUnsignedVarint32()); - var decoder2 = new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4)); - assertEquals(fieldTag, decoder2.readUnsignedVarint32()); - assertEquals(blob.length + 2, decoder2.readUnsignedVarint32()); + const decoder2 = + new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4)); + expect(fieldTag).toEqual(decoder2.readUnsignedVarint32()); + expect(blob.length + 2).toEqual(decoder2.readUnsignedVarint32()); - assertEquals(fieldTag, decoder2.readUnsignedVarint32()); - assertEquals(blob.length, decoder2.readUnsignedVarint32()); - var bytes = decoder2.readBytes(blob.length); + expect(fieldTag).toEqual(decoder2.readUnsignedVarint32()); + expect(blob.length).toEqual(decoder2.readUnsignedVarint32()); + const bytes = decoder2.readBytes(blob.length); - assertElementsEquals(bytes, blob); + expect(Uint8Array.from(blob)).toEqual(bytes); }); /** * Tests read callbacks. */ - it('testReadCallbacks', function() { - var writer = new jspb.BinaryWriter(); - var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); + it('testReadCallbacks', () => { + const writer = new jspb.BinaryWriter(); + const dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); // Add an int, a submessage, and another int. writer.writeInt32(1, 100); - writer.writeMessage(2, dummyMessage, function() { + writer.writeMessage(2, dummyMessage, () => { writer.writeInt32(3, 300); writer.writeInt32(4, 400); writer.writeInt32(5, 500); @@ -947,7 +948,7 @@ describe('binaryReaderTest', function() { writer.writeInt32(7, 700); // Create the reader and register a custom read callback. - var reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); + const reader = jspb.BinaryReader.alloc(writer.getResultBuffer()); /** * @param {!jspb.BinaryReader} reader @@ -955,38 +956,38 @@ describe('binaryReaderTest', function() { */ function readCallback(reader) { reader.nextField(); - assertEquals(3, reader.getFieldNumber()); - assertEquals(300, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(3); + expect(300).toEqual(reader.readInt32()); reader.nextField(); - assertEquals(4, reader.getFieldNumber()); - assertEquals(400, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(4); + expect(400).toEqual(reader.readInt32()); reader.nextField(); - assertEquals(5, reader.getFieldNumber()); - assertEquals(500, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(5); + expect(500).toEqual(reader.readInt32()); - assertEquals(false, reader.nextField()); + expect(reader.nextField()).toEqual(false); }; reader.registerReadCallback('readCallback', readCallback); // Read the container message. reader.nextField(); - assertEquals(1, reader.getFieldNumber()); - assertEquals(100, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(1); + expect(100).toEqual(reader.readInt32()); reader.nextField(); - assertEquals(2, reader.getFieldNumber()); - reader.readMessage(dummyMessage, function() { + expect(reader.getFieldNumber()).toEqual(2); + reader.readMessage(dummyMessage, () => { // Decode the embedded message using the registered callback. reader.runReadCallback('readCallback'); }); reader.nextField(); - assertEquals(7, reader.getFieldNumber()); - assertEquals(700, reader.readInt32()); + expect(reader.getFieldNumber()).toEqual(7); + expect(700).toEqual(reader.readInt32()); - assertEquals(false, reader.nextField()); + expect(reader.nextField()).toEqual(false); }); }); diff --git a/binary/utils.js b/binary/utils.js index d912305..ed60fed 100644 --- a/binary/utils.js +++ b/binary/utils.js @@ -38,10 +38,11 @@ goog.provide('jspb.utils'); -goog.require('goog.asserts'); goog.require('goog.crypt'); goog.require('goog.crypt.base64'); goog.require('goog.string'); + +goog.require('jspb.asserts'); goog.require('jspb.BinaryConstants'); @@ -76,8 +77,8 @@ jspb.utils.split64High = 0; jspb.utils.splitUint64 = function(value) { // Extract low 32 bits and high 32 bits as unsigned integers. var lowBits = value >>> 0; - var highBits = Math.floor((value - lowBits) / - jspb.BinaryConstants.TWO_TO_32) >>> 0; + var highBits = + Math.floor((value - lowBits) / jspb.BinaryConstants.TWO_TO_32) >>> 0; jspb.utils.split64Low = lowBits; jspb.utils.split64High = highBits; @@ -96,8 +97,7 @@ jspb.utils.splitInt64 = function(value) { // Extract low 32 bits and high 32 bits as unsigned integers. var lowBits = value >>> 0; - var highBits = Math.floor((value - lowBits) / - jspb.BinaryConstants.TWO_TO_32); + var highBits = Math.floor((value - lowBits) / jspb.BinaryConstants.TWO_TO_32); highBits = highBits >>> 0; // Perform two's complement conversion if the sign bit was set. @@ -434,8 +434,7 @@ jspb.utils.joinFloat32 = function(bitsLow, bitsHigh) { // Denormal. return sign * Math.pow(2, -149) * mant; } else { - return sign * Math.pow(2, exp - 150) * - (mant + Math.pow(2, 23)); + return sign * Math.pow(2, exp - 150) * (mant + Math.pow(2, 23)); } }; @@ -465,7 +464,7 @@ jspb.utils.joinFloat64 = function(bitsLow, bitsHigh) { return sign * Math.pow(2, -1074) * mant; } else { return sign * Math.pow(2, exp - 1075) * - (mant + jspb.BinaryConstants.TWO_TO_52); + (mant + jspb.BinaryConstants.TWO_TO_52); } }; @@ -494,8 +493,7 @@ jspb.utils.joinHash64 = function(bitsLow, bitsHigh) { * @const {!Array
NOTE: This string is *not* suitable for use in server requests. - * @return {string} A string representation of this proto. - * @override - * @export - */ -jspb.Message.prototype.toString = function() { - this.syncMapFields_(); - return this.array.toString(); -}; - + /** + * Creates a string representation of the internal data array of this proto. + *
NOTE: This string is *not* suitable for use in server requests.
+ * @return {string} A string representation of this proto.
+ * @override
+ * @export
+ */
+ jspb.Message.prototype.toString = function() {
+ this.syncMapFields_();
+ return this.array.toString();
+ };
}
/**
@@ -1516,11 +1520,10 @@ jspb.Message.prototype.getExtension = function(fieldInfo) {
if (fieldInfo.isRepeated) {
if (fieldInfo.isMessageType()) {
if (!this.wrappers_[fieldNumber]) {
- this.wrappers_[fieldNumber] =
- goog.array.map(this.extensionObject_[fieldNumber] || [],
- function(arr) {
- return new fieldInfo.ctor(arr);
- });
+ this.wrappers_[fieldNumber] = goog.array.map(
+ this.extensionObject_[fieldNumber] || [], function(arr) {
+ return new fieldInfo.ctor(arr);
+ });
}
return this.wrappers_[fieldNumber];
} else {
@@ -1566,8 +1569,8 @@ jspb.Message.prototype.setExtension = function(fieldInfo, value) {
self.wrappers_[fieldNumber] = value;
self.extensionObject_[fieldNumber] = goog.array.map(
/** @type {!Array} */ (value), function(msg) {
- return msg.toArray();
- });
+ return msg.toArray();
+ });
} else {
self.extensionObject_[fieldNumber] = value;
}
@@ -1637,8 +1640,9 @@ jspb.Message.difference = function(m1, m2) {
* @export
*/
jspb.Message.equals = function(m1, m2) {
- return m1 == m2 || (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
- jspb.Message.compareFields(m1.toArray(), m2.toArray()));
+ return m1 == m2 ||
+ (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
+ jspb.Message.compareFields(m1.toArray(), m2.toArray()));
};
@@ -1694,14 +1698,14 @@ jspb.Message.compareFields = function(field1, field2) {
}
// We have two objects. If they're different types, they're not equal.
- field1 = /** @type {!Object} */(field1);
- field2 = /** @type {!Object} */(field2);
+ field1 = /** @type {!Object} */ (field1);
+ field2 = /** @type {!Object} */ (field2);
if (field1.constructor != field2.constructor) return false;
// If both are Uint8Arrays, compare them element-by-element.
if (jspb.Message.SUPPORTS_UINT8ARRAY_ && field1.constructor === Uint8Array) {
- var bytes1 = /** @type {!Uint8Array} */(field1);
- var bytes2 = /** @type {!Uint8Array} */(field2);
+ var bytes1 = /** @type {!Uint8Array} */ (field1);
+ var bytes2 = /** @type {!Uint8Array} */ (field2);
if (bytes1.length != bytes2.length) return false;
for (var i = 0; i < bytes1.length; i++) {
if (bytes1[i] != bytes2[i]) return false;
@@ -1723,15 +1727,15 @@ jspb.Message.compareFields = function(field1, field2) {
var val2 = typedField2[i];
if (val1 && (val1.constructor == Object)) {
- goog.asserts.assert(extension1 === undefined);
- goog.asserts.assert(i === typedField1.length - 1);
+ jspb.asserts.assert(extension1 === undefined);
+ jspb.asserts.assert(i === typedField1.length - 1);
extension1 = val1;
val1 = undefined;
}
if (val2 && (val2.constructor == Object)) {
- goog.asserts.assert(extension2 === undefined);
- goog.asserts.assert(i === typedField2.length - 1);
+ jspb.asserts.assert(extension2 === undefined);
+ jspb.asserts.assert(i === typedField2.length - 1);
extension2 = val2;
val2 = undefined;
}
@@ -1822,11 +1826,11 @@ jspb.Message.cloneMessage = function(msg) {
* @export
*/
jspb.Message.copyInto = function(fromMessage, toMessage) {
- goog.asserts.assertInstanceof(fromMessage, jspb.Message);
- goog.asserts.assertInstanceof(toMessage, jspb.Message);
-
- if(fromMessage.constructor !== toMessage.constructor)
- throw new Error('Copy source and target message should have the same type.');
+ jspb.asserts.assertInstanceof(fromMessage, jspb.Message);
+ jspb.asserts.assertInstanceof(toMessage, jspb.Message);
+ jspb.asserts.assert(
+ fromMessage.constructor == toMessage.constructor,
+ 'Copy source and target message should have the same type.');
var copyOfFrom = jspb.Message.clone(fromMessage);
@@ -1865,7 +1869,7 @@ jspb.Message.clone_ = function(obj) {
// NOTE:redundant null check existing for NTI compatibility.
// see b/70515949
clonedArray[i] = (typeof o == 'object') ?
- jspb.Message.clone_(goog.asserts.assert(o)) :
+ jspb.Message.clone_(jspb.asserts.assert(o)) :
o;
}
}
@@ -1881,7 +1885,7 @@ jspb.Message.clone_ = function(obj) {
// NOTE:redundant null check existing for NTI compatibility.
// see b/70515949
clone[key] = (typeof o == 'object') ?
- jspb.Message.clone_(goog.asserts.assert(o)) :
+ jspb.Message.clone_(jspb.asserts.assert(o)) :
o;
}
}
@@ -1896,8 +1900,9 @@ jspb.Message.clone_ = function(obj) {
* @export
*/
jspb.Message.registerMessageType = function(id, constructor) {
- // This is needed so we can later access messageId directly on the constructor,
- // otherwise it is not available due to 'property collapsing' by the compiler.
+ // This is needed so we can later access messageId directly on the
+ // constructor, otherwise it is not available due to 'property collapsing' by
+ // the compiler.
/**
* @suppress {strictMissingProperties} messageId is not defined on Function
*/
diff --git a/message_test.js b/message_test.js
index 7e25dbc..15ab24e 100644
--- a/message_test.js
+++ b/message_test.js
@@ -33,13 +33,15 @@
goog.setTestOnly();
goog.require('goog.testing.PropertyReplacer');
-goog.require('goog.testing.asserts');
-goog.require('goog.testing.TestCase');
+
goog.require('goog.userAgent');
// CommonJS-LoadFromFile: protos/google-protobuf jspb
goog.require('jspb.Message');
+// CommonJS-LoadFromFile: protos/google-protobuf jspb.asserts
+goog.require('jspb.asserts');
+
// CommonJS-LoadFromFile: protos/test15_pb proto.jspb.filenametest.package1
goog.require('proto.jspb.filenametest.package1.b');
@@ -124,124 +126,110 @@ goog.require('proto.jspb.test.MessageWithLargeFieldNumbers');
goog.require('proto.jspb.test.simple1');
-describe('Message test suite', function() {
- var stubs = new goog.testing.PropertyReplacer();
+describe('Message test suite', () => {
+ const stubs = new goog.testing.PropertyReplacer();
- beforeEach(function() {
+ beforeEach(() => {
stubs.set(jspb.Message, 'SERIALIZE_EMPTY_TRAILING_FIELDS', false);
});
- afterEach(function() {
+ afterEach(() => {
stubs.reset();
});
- it('testEmptyProto', function() {
- var empty1 = new proto.jspb.test.Empty([]);
- var empty2 = new proto.jspb.test.Empty([]);
- assertObjectEquals({}, empty1.toObject());
- assertObjectEquals('Message should not be corrupted:', empty2, empty1);
+ it('testEmptyProto', () => {
+ const empty1 = new proto.jspb.test.Empty([]);
+ const empty2 = new proto.jspb.test.Empty([]);
+ expect(empty1.toObject()).toEqual({});
+ expect(empty1).toEqual(empty2);
});
- it('testTopLevelEnum', function() {
- var response = new proto.jspb.test.EnumContainer([]);
+ it('testTopLevelEnum', () => {
+ const response = new proto.jspb.test.EnumContainer([]);
response.setOuterEnum(proto.jspb.test.OuterEnum.FOO);
- assertEquals(proto.jspb.test.OuterEnum.FOO, response.getOuterEnum());
+ expect(response.getOuterEnum()).toEqual(proto.jspb.test.OuterEnum.FOO);
});
- it('testByteStrings', function() {
- var data = new proto.jspb.test.DefaultValues([]);
+ it('testByteStrings', () => {
+ const data = new proto.jspb.test.DefaultValues([]);
data.setBytesField('some_bytes');
- assertEquals('some_bytes', data.getBytesField());
+ expect(data.getBytesField()).toEqual('some_bytes');
});
- it('testComplexConversion', function() {
- var data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1];
- var data2 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1];
- var foo = new proto.jspb.test.Complex(data1);
- var bar = new proto.jspb.test.Complex(data2);
- var result = foo.toObject();
- assertObjectEquals(
- {
- aString: 'a',
- anOutOfOrderBool: true,
- aNestedMessage: {anInt: 11},
- aRepeatedMessageList: [{anInt: 22}, {anInt: 33}],
- aRepeatedStringList: ['s1', 's2'],
- aFloatingPointField: undefined,
- },
- result);
+ it('testComplexConversion', () => {
+ const data1 = ['a', , , [, 11], [[, 22], [, 33]], , ['s1', 's2'], , 1];
+ const foo = new proto.jspb.test.Complex(data1);
+ let result = foo.toObject();
+ expect(result).toEqual({
+ aString: 'a',
+ anOutOfOrderBool: true,
+ aNestedMessage: {anInt: 11},
+ aRepeatedMessageList: [{anInt: 22}, {anInt: 33}],
+ aRepeatedStringList: ['s1', 's2'],
+ aFloatingPointField: undefined,
+ });
// Now test with the jspb instances included.
result = foo.toObject(true /* opt_includeInstance */);
- assertObjectEquals(
- {
- aString: 'a',
- anOutOfOrderBool: true,
- aNestedMessage:
- {anInt: 11, $jspbMessageInstance: foo.getANestedMessage()},
- aRepeatedMessageList: [
- {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]},
- {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]}
- ],
- aRepeatedStringList: ['s1', 's2'],
- aFloatingPointField: undefined,
- $jspbMessageInstance: foo
- },
- result);
+ expect(result).toEqual({
+ aString: 'a',
+ anOutOfOrderBool: true,
+ aNestedMessage:
+ {anInt: 11, $jspbMessageInstance: foo.getANestedMessage()},
+ aRepeatedMessageList: [
+ {anInt: 22, $jspbMessageInstance: foo.getARepeatedMessageList()[0]},
+ {anInt: 33, $jspbMessageInstance: foo.getARepeatedMessageList()[1]}
+ ],
+ aRepeatedStringList: ['s1', 's2'],
+ aFloatingPointField: undefined,
+ $jspbMessageInstance: foo
+ });
});
- it('testMissingFields', function() {
- var foo = new proto.jspb.test.Complex([
- undefined, undefined, undefined, [], undefined, undefined, undefined,
- undefined
- ]);
- var bar = new proto.jspb.test.Complex([
+ it('testMissingFields', () => {
+ const foo = new proto.jspb.test.Complex([
undefined, undefined, undefined, [], undefined, undefined, undefined,
undefined
]);
- var result = foo.toObject();
- assertObjectEquals(
- {
- aString: undefined,
- anOutOfOrderBool: undefined,
- aNestedMessage: {anInt: undefined},
- // Note: JsPb converts undefined repeated fields to empty arrays.
- aRepeatedMessageList: [],
- aRepeatedStringList: [],
- aFloatingPointField: undefined,
- },
- result);
+ const result = foo.toObject();
+ expect(result).toEqual({
+ aString: undefined,
+ anOutOfOrderBool: undefined,
+ aNestedMessage: {anInt: undefined},
+ // Note: JsPb converts undefined repeated fields to empty arrays.
+ aRepeatedMessageList: [],
+ aRepeatedStringList: [],
+ aFloatingPointField: undefined,
+ });
});
- it('testNestedComplexMessage', function() {
+ it('testNestedComplexMessage', () => {
// Instantiate the message and set a unique field, just to ensure that we
// are not getting jspb.test.Complex instead.
- var msg = new proto.jspb.test.OuterMessage.Complex();
+ const msg = new proto.jspb.test.OuterMessage.Complex();
msg.setInnerComplexField(5);
});
- it('testSpecialCases', function() {
+ it('testSpecialCases', () => {
// Note: Some property names are reserved in JavaScript.
// These names are converted to the Js property named pb_