Remove the JavaScript implementation (#9874)

This implementation is about to be split out into a separate Git repo.
This commit is contained in:
Adam Cozzette 2022-04-28 12:08:26 -07:00 committed by GitHub
parent 1927520278
commit 860f8ad171
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
211 changed files with 10 additions and 61158 deletions

15
.gitignore vendored
View File

@ -168,21 +168,6 @@ php/ext/google/protobuf/run-tests.php
php/ext/google/protobuf/third_party/
vendor/
# JavaScript artifacts
js/commonjs_out/
js/compatibility_tests/v3.0.0/commonjs_out*
js/compatibility_tests/v3.0.0/protoc
js/compatibility_tests/v3.0.0/testproto_libs1.js
js/compatibility_tests/v3.0.0/testproto_libs1_new.js
js/compatibility_tests/v3.0.0/testproto_libs2.js
js/compatibility_tests/v3.0.0/testproto_libs2_new.js
js/deps.js
js/google-protobuf.js
js/google/
js/node_modules/
js/testproto_libs1.js
js/testproto_libs2.js
# Ignore the bazel symlinks
/bazel-*

2
BUILD
View File

@ -485,8 +485,6 @@ cc_library(
"src/google/protobuf/compiler/java/shared_code_generator.cc",
"src/google/protobuf/compiler/java/string_field.cc",
"src/google/protobuf/compiler/java/string_field_lite.cc",
"src/google/protobuf/compiler/js/js_generator.cc",
"src/google/protobuf/compiler/js/well_known_types_embed.cc",
"src/google/protobuf/compiler/objectivec/objectivec_enum.cc",
"src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc",
"src/google/protobuf/compiler/objectivec/objectivec_extension.cc",

View File

@ -1218,189 +1218,7 @@ ruby_EXTRA_DIST= \
ruby/tests/type_errors.rb \
ruby/travis-test.sh
# Note: please keep this in sync with the dist_files rule in js/BUILD.
js_EXTRA_DIST= \
js/README.md \
js/binary/arith.js \
js/binary/arith_test.js \
js/binary/constants.js \
js/binary/decoder.js \
js/binary/decoder_test.js \
js/binary/encoder.js \
js/binary/message_test.js \
js/binary/proto_test.js \
js/binary/reader.js \
js/binary/reader_test.js \
js/binary/utils.js \
js/binary/utils_test.js \
js/binary/writer.js \
js/binary/writer_test.js \
js/commonjs/export.js \
js/commonjs/export_asserts.js \
js/commonjs/export_testdeps.js \
js/commonjs/import_test.js \
js/commonjs/jasmine.json \
js/commonjs/rewrite_tests_for_commonjs.js \
js/commonjs/strict_test.js \
js/commonjs/test6/test6.proto \
js/commonjs/test7/test7.proto \
js/compatibility_tests/v3.0.0/binary/arith_test.js \
js/compatibility_tests/v3.0.0/binary/decoder_test.js \
js/compatibility_tests/v3.0.0/binary/proto_test.js \
js/compatibility_tests/v3.0.0/binary/reader_test.js \
js/compatibility_tests/v3.0.0/binary/utils_test.js \
js/compatibility_tests/v3.0.0/binary/writer_test.js \
js/compatibility_tests/v3.0.0/commonjs/export_asserts.js \
js/compatibility_tests/v3.0.0/commonjs/export_testdeps.js \
js/compatibility_tests/v3.0.0/commonjs/import_test.js \
js/compatibility_tests/v3.0.0/commonjs/jasmine.json \
js/compatibility_tests/v3.0.0/commonjs/rewrite_tests_for_commonjs.js \
js/compatibility_tests/v3.0.0/commonjs/test6/test6.proto \
js/compatibility_tests/v3.0.0/commonjs/test7/test7.proto \
js/compatibility_tests/v3.0.0/data.proto \
js/compatibility_tests/v3.0.0/debug_test.js \
js/compatibility_tests/v3.0.0/jasmine1.json \
js/compatibility_tests/v3.0.0/jasmine2.json \
js/compatibility_tests/v3.0.0/jasmine3.json \
js/compatibility_tests/v3.0.0/message_test.js \
js/compatibility_tests/v3.0.0/proto3_test.js \
js/compatibility_tests/v3.0.0/proto3_test.proto \
js/compatibility_tests/v3.0.0/test2.proto \
js/compatibility_tests/v3.0.0/test3.proto \
js/compatibility_tests/v3.0.0/test4.proto \
js/compatibility_tests/v3.0.0/test5.proto \
js/compatibility_tests/v3.0.0/testbinary.proto \
js/compatibility_tests/v3.0.0/testempty.proto \
js/compatibility_tests/v3.0.0/test.proto \
js/compatibility_tests/v3.0.0/test.sh \
js/compatibility_tests/v3.1.0/testempty.proto \
js/compatibility_tests/v3.1.0/testbinary.proto \
js/compatibility_tests/v3.1.0/test5.proto \
js/compatibility_tests/v3.1.0/test4.proto \
js/compatibility_tests/v3.1.0/test3.proto \
js/compatibility_tests/v3.1.0/test2.proto \
js/compatibility_tests/v3.1.0/test.proto \
js/compatibility_tests/v3.1.0/proto3_test.proto \
js/compatibility_tests/v3.1.0/proto3_test.js \
js/compatibility_tests/v3.1.0/message_test.js \
js/compatibility_tests/v3.1.0/maps_test.js \
js/compatibility_tests/v3.1.0/debug_test.js \
js/compatibility_tests/v3.1.0/data.proto \
js/compatibility_tests/v3.1.0/commonjs/test7/test7.proto \
js/compatibility_tests/v3.1.0/commonjs/test6/test6.proto \
js/compatibility_tests/v3.1.0/binary/writer_test.js \
js/compatibility_tests/v3.1.0/binary/utils_test.js \
js/compatibility_tests/v3.1.0/binary/reader_test.js \
js/compatibility_tests/v3.1.0/binary/proto_test.js \
js/compatibility_tests/v3.1.0/binary/decoder_test.js \
js/compatibility_tests/v3.1.0/binary/arith_test.js \
js/data.proto \
js/debug.js \
js/debug_test.js \
js/experimental/runtime/kernel/message_set.js \
js/experimental/runtime/kernel/message_set_test.js \
js/experimental/runtime/kernel/tag.js \
js/experimental/runtime/kernel/tag_test.js \
js/gulpfile.js \
js/jasmine.json \
js/map.js \
js/maps_test.js \
js/message.js \
js/message_test.js \
js/node_loader.js \
js/package.json \
js/proto3_test.js \
js/proto3_test.proto \
js/test.proto \
js/test2.proto \
js/test3.proto \
js/test4.proto \
js/test5.proto \
js/test8.proto \
js/test9.proto \
js/test10.proto \
js/test11.proto \
js/test12.proto \
js/test13.proto \
js/test14.proto \
js/test15.proto \
js/test_bootstrap.js \
js/testbinary.proto \
js/testempty.proto \
js/testlargenumbers.proto \
js/experimental/runtime/testing/jasmine_protobuf.js \
js/experimental/runtime/testing/ensure_custom_equality_test.js \
js/experimental/runtime/testing/binary/test_message.js \
js/experimental/runtime/kernel/writer_test.js \
js/experimental/runtime/kernel/writer.js \
js/experimental/runtime/kernel/wire_type.js \
js/experimental/runtime/kernel/uint8arrays_test.js \
js/experimental/runtime/kernel/uint8arrays.js \
js/experimental/runtime/kernel/uint32_test_pairs.js \
js/experimental/runtime/kernel/typed_arrays_test.js \
js/experimental/runtime/kernel/typed_arrays.js \
js/experimental/runtime/kernel/textencoding_test.js \
js/experimental/runtime/kernel/textencoding.js \
js/experimental/runtime/kernel/storage.js \
js/experimental/runtime/kernel/sint64_test_pairs.js \
js/experimental/runtime/kernel/sint32_test_pairs.js \
js/experimental/runtime/kernel/sfixed64_test_pairs.js \
js/experimental/runtime/kernel/sfixed32_test_pairs.js \
js/experimental/runtime/kernel/reader_test.js \
js/experimental/runtime/kernel/reader.js \
js/experimental/runtime/kernel/packed_uint32_test_pairs.js \
js/experimental/runtime/kernel/packed_sint64_test_pairs.js \
js/experimental/runtime/kernel/packed_sint32_test_pairs.js \
js/experimental/runtime/kernel/packed_sfixed64_test_pairs.js \
js/experimental/runtime/kernel/packed_sfixed32_test_pairs.js \
js/experimental/runtime/kernel/packed_int64_test_pairs.js \
js/experimental/runtime/kernel/packed_int32_test_pairs.js \
js/experimental/runtime/kernel/packed_float_test_pairs.js \
js/experimental/runtime/kernel/packed_fixed32_test_pairs.js \
js/experimental/runtime/kernel/packed_double_test_pairs.js \
js/experimental/runtime/kernel/packed_bool_test_pairs.js \
js/experimental/runtime/kernel/kernel_test.js \
js/experimental/runtime/kernel/kernel_repeated_test.js \
js/experimental/runtime/kernel/kernel_compatibility_test.js \
js/experimental/runtime/kernel/kernel.js \
js/experimental/runtime/kernel/internal_message.js \
js/experimental/runtime/kernel/int64_test_pairs.js \
js/experimental/runtime/kernel/int32_test_pairs.js \
js/experimental/runtime/kernel/indexer_test.js \
js/experimental/runtime/kernel/indexer.js \
js/experimental/runtime/kernel/float_test_pairs.js \
js/experimental/runtime/kernel/fixed32_test_pairs.js \
js/experimental/runtime/kernel/field.js \
js/experimental/runtime/kernel/double_test_pairs.js \
js/experimental/runtime/kernel/conformance/wire_format.js \
js/experimental/runtime/kernel/conformance/test_all_types_proto3.js \
js/experimental/runtime/kernel/conformance/test_all_types_proto2.js \
js/experimental/runtime/kernel/conformance/conformance_testee_runner_node.js \
js/experimental/runtime/kernel/conformance/conformance_testee.js \
js/experimental/runtime/kernel/conformance/conformance_response.js \
js/experimental/runtime/kernel/conformance/conformance_request.js \
js/experimental/runtime/kernel/buffer_decoder_test.js \
js/experimental/runtime/kernel/buffer_decoder_helper.js \
js/experimental/runtime/kernel/buffer_decoder.js \
js/experimental/runtime/kernel/bool_test_pairs.js \
js/experimental/runtime/kernel/binary_storage_test.js \
js/experimental/runtime/kernel/binary_storage.js \
js/experimental/runtime/internal/checks_test.js \
js/experimental/runtime/internal/checks.js \
js/experimental/runtime/int64_test.js \
js/experimental/runtime/int64.js \
js/experimental/runtime/bytestring_test.js \
js/experimental/runtime/bytestring_internal.js \
js/experimental/runtime/bytestring.js \
js/experimental/benchmarks/code_size/kernel/popular_types.js \
js/experimental/benchmarks/code_size/kernel/all_types.js \
js/experimental/benchmarks/code_size/code_size_base.js \
js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto3.js \
js/experimental/benchmarks/code_size/apps_jspb/popular_types_proto2.js \
js/experimental/benchmarks/code_size/apps_jspb/all_types_proto3.js \
js/experimental/benchmarks/code_size/apps_jspb/all_types_proto2.js
all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST)
all_EXTRA_DIST=$(csharp_EXTRA_DIST) $(java_EXTRA_DIST) $(objectivec_EXTRA_DIST) $(php_EXTRA_DIST) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST)
# Note: please keep this in sync with the common_dist_files rule in BUILD.
EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
@ -1462,7 +1280,6 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
examples/list_people.py \
examples/pubspec.yaml \
internal.bzl \
js/BUILD \
maven_install.json \
php/BUILD \
protobuf.bzl \

View File

@ -59,7 +59,6 @@ how to install protobuf runtime for that specific language:
| Python | [python](python) |
| Objective-C | [objectivec](objectivec) |
| C# | [csharp](csharp) |
| JavaScript | [js](js) |
| Ruby | [ruby](ruby) |
| Go | [protocolbuffers/protobuf-go](https://github.com/protocolbuffers/protobuf-go)|
| PHP | [php](php) |

View File

@ -5,7 +5,6 @@ mkdir include\google\protobuf\compiler
mkdir include\google\protobuf\compiler\cpp
mkdir include\google\protobuf\compiler\csharp
mkdir include\google\protobuf\compiler\java
mkdir include\google\protobuf\compiler\js
mkdir include\google\protobuf\compiler\objectivec
mkdir include\google\protobuf\compiler\php
mkdir include\google\protobuf\compiler\python
@ -34,7 +33,6 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h"
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\generator.h" include\google\protobuf\compiler\java\generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\kotlin_generator.h" include\google\protobuf\compiler\java\kotlin_generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\names.h" include\google\protobuf\compiler\java\names.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generator.h" include\google\protobuf\compiler\js\js_generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h" include\google\protobuf\compiler\objectivec\objectivec_generator.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_helpers.h" include\google\protobuf\compiler\objectivec\objectivec_helpers.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\parser.h" include\google\protobuf\compiler\parser.h

View File

@ -61,8 +61,6 @@ set(libprotoc_files
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/shared_code_generator.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/string_field.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/string_field_lite.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/js/js_generator.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/js/well_known_types_embed.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
@ -100,7 +98,6 @@ set(libprotoc_headers
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/generator.h
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/kotlin_generator.h
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/names.h
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/js/js_generator.h
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_generator.h
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/php/php_generator.h

View File

@ -31,7 +31,7 @@ AC_CONFIG_MACRO_DIR([m4])
AC_ARG_VAR(DIST_LANG, [language to include in the distribution package (i.e., make dist)])
case "$DIST_LANG" in
"") DIST_LANG=all ;;
all | cpp | csharp | java | python | javanano | objectivec | ruby | js | php) ;;
all | cpp | csharp | java | python | javanano | objectivec | ruby | php) ;;
*) AC_MSG_FAILURE([unknown language: $DIST_LANG]) ;;
esac
AC_SUBST(DIST_LANG)

View File

@ -260,9 +260,9 @@ if USE_EXTERNAL_PROTOC
# Some implementations include pre-generated versions of well-known types.
protoc_middleman: $(conformance_protoc_inputs) $(conformance_proto2_protoc_inputs) $(well_known_type_protoc_inputs) google-protobuf
$(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --objc_out=. --python_out=. --php_out=. --js_out=import_style=commonjs,binary:. $(conformance_protoc_inputs)
$(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --objc_out=. --python_out=. --js_out=import_style=commonjs,binary:. $(conformance_proto2_protoc_inputs)
$(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --python_out=. --js_out=import_style=commonjs,binary:google-protobuf $(well_known_type_protoc_inputs)
$(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --objc_out=. --python_out=. --php_out=. $(conformance_protoc_inputs)
$(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --objc_out=. --python_out=. $(conformance_proto2_protoc_inputs)
$(PROTOC) -I$(srcdir) -I$(top_srcdir) --cpp_out=. --java_out=. --ruby_out=. --python_out=. $(well_known_type_protoc_inputs)
## $(PROTOC) -I$(srcdir) -I$(top_srcdir) --java_out=lite:lite $(conformance_protoc_inputs) $(well_known_type_protoc_inputs)
touch protoc_middleman
@ -272,9 +272,9 @@ else
# relative to srcdir, which may not be the same as the current directory when
# building out-of-tree.
protoc_middleman: $(top_srcdir)/src/protoc$(EXEEXT) $(conformance_protoc_inputs) $(conformance_proto2_protoc_inputs) $(well_known_type_protoc_inputs) google-protobuf
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --objc_out=$$oldpwd --python_out=$$oldpwd --php_out=$$oldpwd --js_out=import_style=commonjs,binary:$$oldpwd $(conformance_protoc_inputs) )
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --objc_out=$$oldpwd --python_out=$$oldpwd --js_out=import_style=commonjs,binary:$$oldpwd $(conformance_proto2_protoc_inputs) )
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --python_out=$$oldpwd --js_out=import_style=commonjs,binary:$$oldpwd/google-protobuf $(well_known_type_protoc_inputs) )
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --objc_out=$$oldpwd --python_out=$$oldpwd --php_out=$$oldpwd $(conformance_protoc_inputs) )
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --objc_out=$$oldpwd --python_out=$$oldpwd $(conformance_proto2_protoc_inputs) )
oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --cpp_out=$$oldpwd --java_out=$$oldpwd --ruby_out=$$oldpwd --python_out=$$oldpwd $(well_known_type_protoc_inputs) )
## @mkdir -p lite
## oldpwd=`pwd` && ( cd $(srcdir) && $$oldpwd/../src/protoc$(EXEEXT) -I. -I$(top_srcdir)/src --java_out=lite:$$oldpwd/lite $(conformance_protoc_inputs) $(well_known_type_protoc_inputs) )
touch protoc_middleman
@ -364,9 +364,6 @@ test_python: protoc_middleman conformance-test-runner
test_python_cpp: protoc_middleman conformance-test-runner
./conformance-test-runner --enforce_recommended --failure_list failure_list_python_cpp.txt --text_format_failure_list text_format_failure_list_python_cpp.txt ./conformance_python.py
test_nodejs: protoc_middleman conformance-test-runner $(other_language_protoc_outputs)
NODE_PATH=../js:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_js.txt ./conformance_nodejs.js
if OBJC_CONFORMANCE_TEST
test_objc: protoc_middleman conformance-test-runner conformance-objc

View File

@ -26,10 +26,6 @@ languages = [
"python",
"src/google/protobuf/compiler/python",
]),
Language("JavaScript", [
"js",
"src/google/protobuf/compiler/js",
]),
Language("PHP", [
"php",
"src/google/protobuf/compiler/php",

View File

@ -1,29 +0,0 @@
# Protobuf JS runtime
#
# See also code generation logic under /src/google/protobuf/compiler/js.
load("@rules_pkg//:mappings.bzl", "pkg_files", "strip_prefix")
pkg_files(
name = "dist_files",
srcs = glob([
"*.js",
"*.json",
"*.proto",
"binary/*.js",
"commonjs/*.js*", # js, json
"commonjs/**/*.proto",
"compatibility_tests/v3.0.0/**/*.js*",
"compatibility_tests/v3.0.0/**/*.proto",
"compatibility_tests/v3.0.0/**/*.sh",
"compatibility_tests/v3.1.0/**/*.js*",
"compatibility_tests/v3.1.0/**/*.proto",
"experimental/benchmarks/**/*.js",
"experimental/runtime/**/*.js",
]) + [
"BUILD",
"README.md",
],
strip_prefix = strip_prefix.from_root(""),
visibility = ["//pkg:__pkg__"],
)

View File

@ -1,161 +0,0 @@
Protocol Buffers - Google's data interchange format
===================================================
Copyright 2008 Google Inc.
This directory contains the JavaScript Protocol Buffers runtime library.
The library is currently compatible with:
1. CommonJS-style imports (eg. `var protos = require('my-protos');`)
2. Closure-style imports (eg. `goog.require('my.package.MyProto');`)
Support for ES6-style imports is not implemented yet. Browsers can
be supported by using Browserify, webpack, Closure Compiler, etc. to
resolve imports at compile time.
To use Protocol Buffers with JavaScript, you need two main components:
1. The protobuf runtime library. You can install this with
`npm install google-protobuf`, or use the files in this directory.
If npm is not being used, as of 3.3.0, the files needed are located in binary subdirectory;
arith.js, constants.js, decoder.js, encoder.js, map.js, message.js, reader.js, utils.js, writer.js
2. The Protocol Compiler `protoc`. This translates `.proto` files
into `.js` files. The compiler is not currently available via
npm, but you can download a pre-built binary
[on GitHub](https://github.com/protocolbuffers/protobuf/releases)
(look for the `protoc-*.zip` files under **Downloads**).
Setup
=====
First, obtain the Protocol Compiler. The easiest way is to download
a pre-built binary from [https://github.com/protocolbuffers/protobuf/releases](https://github.com/protocolbuffers/protobuf/releases).
If you want, you can compile `protoc` from source instead. To do this
follow the instructions in [the top-level
README](https://github.com/protocolbuffers/protobuf/blob/main/src/README.md).
Once you have `protoc` compiled, you can run the tests provided along with our project to examine whether it can run successfully. In order to do this, you should download the Protocol Buffer source code from the release page with the link above. Then extract the source code and navigate to the folder named `js` containing a `package.json` file and a series of test files. In this folder, you can run the commands below to run the tests automatically.
$ npm install
$ npm test
# If your protoc is somewhere else than ../src/protoc, instead do this.
# But make sure your protoc is the same version as this (or compatible)!
$ PROTOC=/usr/local/bin/protoc npm test
This will run two separate copies of the tests: one that uses
Closure Compiler style imports and one that uses CommonJS imports.
You can see all the CommonJS files in `commonjs_out/`.
If all of these tests pass, you know you have a working setup.
Using Protocol Buffers in your own project
==========================================
To use Protocol Buffers in your own project, you need to integrate
the Protocol Compiler into your build system. The details are a
little different depending on whether you are using Closure imports
or CommonJS imports:
Closure Imports
---------------
If you want to use Closure imports, your build should run a command
like this:
$ protoc --js_out=library=myproto_libs,binary:. messages.proto base.proto
For Closure imports, `protoc` will generate a single output file
(`myproto_libs.js` in this example). The generated file will `goog.provide()`
all of the types defined in your .proto files. For example, for the unit
tests the generated files contain many `goog.provide` statements like:
goog.provide('proto.google.protobuf.DescriptorProto');
goog.provide('proto.google.protobuf.DescriptorProto.ExtensionRange');
goog.provide('proto.google.protobuf.DescriptorProto.ReservedRange');
goog.provide('proto.google.protobuf.EnumDescriptorProto');
goog.provide('proto.google.protobuf.EnumOptions');
The generated code will also `goog.require()` many types in the core library,
and they will require many types in the Google Closure library. So make sure
that your `goog.provide()` / `goog.require()` setup can find all of your
generated code, the core library `.js` files in this directory, and the
Google Closure library itself.
Once you've done this, you should be able to import your types with
statements like:
goog.require('proto.my.package.MyMessage');
var message = proto.my.package.MyMessage();
If unfamiliar with Closure or its compiler, consider reviewing
[Closure documentation](https://developers.google.com/closure/library).
CommonJS imports
----------------
If you want to use CommonJS imports, your build should run a command
like this:
$ protoc --js_out=import_style=commonjs,binary:. messages.proto base.proto
For CommonJS imports, `protoc` will spit out one file per input file
(so `messages_pb.js` and `base_pb.js` in this example). The generated
code will depend on the core runtime, which should be in a file called
`google-protobuf.js`. If you are installing from `npm`, this file should
already be built and available. If you are running from GitHub, you need
to build it first by running:
$ gulp dist
Once you've done this, you should be able to import your types with
statements like:
var messages = require('./messages_pb');
var message = new messages.MyMessage();
The `--js_out` flag
-------------------
The syntax of the `--js_out` flag is:
--js_out=[OPTIONS:]output_dir
Where `OPTIONS` are separated by commas. Options are either `opt=val` or
just `opt` (for options that don't take a value). The available options
are specified and documented in the `GeneratorOptions` struct in
[src/google/protobuf/compiler/js/js_generator.h](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/compiler/js/js_generator.h#L53).
Some examples:
- `--js_out=library=myprotos_lib.js,binary:.`: this contains the options
`library=myprotos.lib.js` and `binary` and outputs to the current directory.
The `import_style` option is left to the default, which is `closure`.
- `--js_out=import_style=commonjs,binary:protos`: this contains the options
`import_style=commonjs` and `binary` and outputs to the directory `protos`.
`import_style=commonjs_strict` doesn't expose the output on the global scope.
API
===
The API is not well-documented yet. Here is a quick example to give you an
idea of how the library generally works:
var message = new MyMessage();
message.setName("John Doe");
message.setAge(25);
message.setPhoneNumbers(["800-555-1212", "800-555-0000"]);
// Serializes to a UInt8Array.
var bytes = message.serializeBinary();
var message2 = MyMessage.deserializeBinary(bytes);
For more examples, see the tests. You can also look at the generated code
to see what methods are defined for your generated messages.

View File

@ -1,413 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview This file contains helper code used by jspb.utils to
* handle 64-bit integer conversion to/from strings.
*
* @author cfallin@google.com (Chris Fallin)
*
* TODO(haberman): move this to javascript/closure/math?
*/
goog.provide('jspb.arith.Int64');
goog.provide('jspb.arith.UInt64');
/**
* UInt64 implements some 64-bit arithmetic routines necessary for properly
* handling 64-bit integer fields. It implements lossless integer arithmetic on
* top of JavaScript's number type, which has only 53 bits of precision, by
* representing 64-bit integers as two 32-bit halves.
*
* @param {number} lo The low 32 bits.
* @param {number} hi The high 32 bits.
* @constructor
*/
jspb.arith.UInt64 = function(lo, hi) {
/**
* The low 32 bits.
* @public {number}
*/
this.lo = lo;
/**
* The high 32 bits.
* @public {number}
*/
this.hi = hi;
};
/**
* Compare two 64-bit numbers. Returns -1 if the first is
* less, +1 if the first is greater, or 0 if both are equal.
* @param {!jspb.arith.UInt64} other
* @return {number}
*/
jspb.arith.UInt64.prototype.cmp = function(other) {
if (this.hi < other.hi || (this.hi == other.hi && this.lo < other.lo)) {
return -1;
} else if (this.hi == other.hi && this.lo == other.lo) {
return 0;
} else {
return 1;
}
};
/**
* Right-shift this number by one bit.
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.prototype.rightShift = function() {
var hi = this.hi >>> 1;
var lo = (this.lo >>> 1) | ((this.hi & 1) << 31);
return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
};
/**
* Left-shift this number by one bit.
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.prototype.leftShift = function() {
var lo = this.lo << 1;
var hi = (this.hi << 1) | (this.lo >>> 31);
return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
};
/**
* Test the MSB.
* @return {boolean}
*/
jspb.arith.UInt64.prototype.msb = function() {
return !!(this.hi & 0x80000000);
};
/**
* Test the LSB.
* @return {boolean}
*/
jspb.arith.UInt64.prototype.lsb = function() {
return !!(this.lo & 1);
};
/**
* Test whether this number is zero.
* @return {boolean}
*/
jspb.arith.UInt64.prototype.zero = function() {
return this.lo == 0 && this.hi == 0;
};
/**
* Add two 64-bit numbers to produce a 64-bit number.
* @param {!jspb.arith.UInt64} other
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.prototype.add = function(other) {
var lo = ((this.lo + other.lo) & 0xffffffff) >>> 0;
var hi =
(((this.hi + other.hi) & 0xffffffff) >>> 0) +
(((this.lo + other.lo) >= 0x100000000) ? 1 : 0);
return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
};
/**
* Subtract two 64-bit numbers to produce a 64-bit number.
* @param {!jspb.arith.UInt64} other
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.prototype.sub = function(other) {
var lo = ((this.lo - other.lo) & 0xffffffff) >>> 0;
var hi =
(((this.hi - other.hi) & 0xffffffff) >>> 0) -
(((this.lo - other.lo) < 0) ? 1 : 0);
return new jspb.arith.UInt64(lo >>> 0, hi >>> 0);
};
/**
* Multiply two 32-bit numbers to produce a 64-bit number.
* @param {number} a The first integer: must be in [0, 2^32-1).
* @param {number} b The second integer: must be in [0, 2^32-1).
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.mul32x32 = function(a, b) {
// Directly multiplying two 32-bit numbers may produce up to 64 bits of
// precision, thus losing precision because of the 53-bit mantissa of
// JavaScript numbers. So we multiply with 16-bit digits (radix 65536)
// instead.
var aLow = (a & 0xffff);
var aHigh = (a >>> 16);
var bLow = (b & 0xffff);
var bHigh = (b >>> 16);
var productLow =
// 32-bit result, result bits 0-31, take all 32 bits
(aLow * bLow) +
// 32-bit result, result bits 16-47, take bottom 16 as our top 16
((aLow * bHigh) & 0xffff) * 0x10000 +
// 32-bit result, result bits 16-47, take bottom 16 as our top 16
((aHigh * bLow) & 0xffff) * 0x10000;
var productHigh =
// 32-bit result, result bits 32-63, take all 32 bits
(aHigh * bHigh) +
// 32-bit result, result bits 16-47, take top 16 as our bottom 16
((aLow * bHigh) >>> 16) +
// 32-bit result, result bits 16-47, take top 16 as our bottom 16
((aHigh * bLow) >>> 16);
// Carry. Note that we actually have up to *two* carries due to addition of
// three terms.
while (productLow >= 0x100000000) {
productLow -= 0x100000000;
productHigh += 1;
}
return new jspb.arith.UInt64(productLow >>> 0, productHigh >>> 0);
};
/**
* Multiply this number by a 32-bit number, producing a 96-bit number, then
* truncate the top 32 bits.
* @param {number} a The multiplier.
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.prototype.mul = function(a) {
// Produce two parts: at bits 0-63, and 32-95.
var lo = jspb.arith.UInt64.mul32x32(this.lo, a);
var hi = jspb.arith.UInt64.mul32x32(this.hi, a);
// Left-shift hi by 32 bits, truncating its top bits. The parts will then be
// aligned for addition.
hi.hi = hi.lo;
hi.lo = 0;
return lo.add(hi);
};
/**
* Divide a 64-bit number by a 32-bit number to produce a
* 64-bit quotient and a 32-bit remainder.
* @param {number} _divisor
* @return {Array<jspb.arith.UInt64>} array of [quotient, remainder],
* unless divisor is 0, in which case an empty array is returned.
*/
jspb.arith.UInt64.prototype.div = function(_divisor) {
if (_divisor == 0) {
return [];
}
// We perform long division using a radix-2 algorithm, for simplicity (i.e.,
// one bit at a time). TODO: optimize to a radix-2^32 algorithm, taking care
// to get the variable shifts right.
var quotient = new jspb.arith.UInt64(0, 0);
var remainder = new jspb.arith.UInt64(this.lo, this.hi);
var divisor = new jspb.arith.UInt64(_divisor, 0);
var unit = new jspb.arith.UInt64(1, 0);
// Left-shift the divisor and unit until the high bit of divisor is set.
while (!divisor.msb()) {
divisor = divisor.leftShift();
unit = unit.leftShift();
}
// Perform long division one bit at a time.
while (!unit.zero()) {
// If divisor < remainder, add unit to quotient and subtract divisor from
// remainder.
if (divisor.cmp(remainder) <= 0) {
quotient = quotient.add(unit);
remainder = remainder.sub(divisor);
}
// Right-shift the divisor and unit.
divisor = divisor.rightShift();
unit = unit.rightShift();
}
return [quotient, remainder];
};
/**
* Convert a 64-bit number to a string.
* @return {string}
* @override
*/
jspb.arith.UInt64.prototype.toString = function() {
var result = '';
var num = this;
while (!num.zero()) {
var divResult = num.div(10);
var quotient = divResult[0], remainder = divResult[1];
result = remainder.lo + result;
num = quotient;
}
if (result == '') {
result = '0';
}
return result;
};
/**
* Parse a string into a 64-bit number. Returns `null` on a parse error.
* @param {string} s
* @return {?jspb.arith.UInt64}
*/
jspb.arith.UInt64.fromString = function(s) {
var result = new jspb.arith.UInt64(0, 0);
// optimization: reuse this instance for each digit.
var digit64 = new jspb.arith.UInt64(0, 0);
for (var i = 0; i < s.length; i++) {
if (s[i] < '0' || s[i] > '9') {
return null;
}
var digit = parseInt(s[i], 10);
digit64.lo = digit;
result = result.mul(10).add(digit64);
}
return result;
};
/**
* Make a copy of the uint64.
* @return {!jspb.arith.UInt64}
*/
jspb.arith.UInt64.prototype.clone = function() {
return new jspb.arith.UInt64(this.lo, this.hi);
};
/**
* Int64 is like UInt64, but modifies string conversions to interpret the stored
* 64-bit value as a twos-complement-signed integer. It does *not* support the
* full range of operations that UInt64 does: only add, subtract, and string
* conversions.
*
* N.B. that multiply and divide routines are *NOT* supported. They will throw
* exceptions. (They are not necessary to implement string conversions, which
* are the only operations we really need in jspb.)
*
* @param {number} lo The low 32 bits.
* @param {number} hi The high 32 bits.
* @constructor
*/
jspb.arith.Int64 = function(lo, hi) {
/**
* The low 32 bits.
* @public {number}
*/
this.lo = lo;
/**
* The high 32 bits.
* @public {number}
*/
this.hi = hi;
};
/**
* Add two 64-bit numbers to produce a 64-bit number.
* @param {!jspb.arith.Int64} other
* @return {!jspb.arith.Int64}
*/
jspb.arith.Int64.prototype.add = function(other) {
var lo = ((this.lo + other.lo) & 0xffffffff) >>> 0;
var hi =
(((this.hi + other.hi) & 0xffffffff) >>> 0) +
(((this.lo + other.lo) >= 0x100000000) ? 1 : 0);
return new jspb.arith.Int64(lo >>> 0, hi >>> 0);
};
/**
* Subtract two 64-bit numbers to produce a 64-bit number.
* @param {!jspb.arith.Int64} other
* @return {!jspb.arith.Int64}
*/
jspb.arith.Int64.prototype.sub = function(other) {
var lo = ((this.lo - other.lo) & 0xffffffff) >>> 0;
var hi =
(((this.hi - other.hi) & 0xffffffff) >>> 0) -
(((this.lo - other.lo) < 0) ? 1 : 0);
return new jspb.arith.Int64(lo >>> 0, hi >>> 0);
};
/**
* Make a copy of the int64.
* @return {!jspb.arith.Int64}
*/
jspb.arith.Int64.prototype.clone = function() {
return new jspb.arith.Int64(this.lo, this.hi);
};
/**
* Convert a 64-bit number to a string.
* @return {string}
* @override
*/
jspb.arith.Int64.prototype.toString = function() {
// If the number is negative, find its twos-complement inverse.
var sign = (this.hi & 0x80000000) != 0;
var num = new jspb.arith.UInt64(this.lo, this.hi);
if (sign) {
num = new jspb.arith.UInt64(0, 0).sub(num);
}
return (sign ? '-' : '') + num.toString();
};
/**
* Parse a string into a 64-bit number. Returns `null` on a parse error.
* @param {string} s
* @return {?jspb.arith.Int64}
*/
jspb.arith.Int64.fromString = function(s) {
var hasNegative = (s.length > 0 && s[0] == '-');
if (hasNegative) {
s = s.substring(1);
}
var num = jspb.arith.UInt64.fromString(s);
if (num === null) {
return null;
}
if (hasNegative) {
num = new jspb.arith.UInt64(0, 0).sub(num);
}
return new jspb.arith.Int64(num.lo, num.hi);
};

View File

@ -1,354 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for Int64-manipulation functions.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author cfallin@google.com (Chris Fallin)
*/
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
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);
expect(a.cmp(b)).toEqual(0);
expect(b.cmp(a)).toEqual(0);
b.lo -= 1;
expect(a.cmp(b)).toEqual(1);
expect(b.cmp(a)).toEqual(-1);
b.lo += 2;
expect(a.cmp(b)).toEqual(-1);
expect(b.cmp(a)).toEqual(1);
b.lo = a.lo;
b.hi = a.hi - 1;
expect(a.cmp(b)).toEqual(1);
expect(b.cmp(a)).toEqual(-1);
expect(a.zero()).toEqual(false);
expect(a.msb()).toEqual(false);
expect(a.lsb()).toEqual(false);
a.hi = 0;
a.lo = 0;
expect(a.zero()).toEqual(true);
a.hi = 0x80000000;
expect(a.zero()).toEqual(false);
expect(a.msb()).toEqual(true);
a.lo = 0x00000001;
expect(a.lsb()).toEqual(true);
});
/**
* Tests shifts.
*/
it('testShifts', function() {
var a = new jspb.arith.UInt64(1, 0);
expect(a.lo).toEqual(1);
expect(a.hi).toEqual(0);
var orig = a;
a = a.leftShift();
expect(orig.lo).toEqual(1); // original unmodified.
expect(orig.hi).toEqual(0);
expect(a.lo).toEqual(2);
expect(a.hi).toEqual(0);
a = a.leftShift();
expect(a.lo).toEqual(4);
expect(a.hi).toEqual(0);
for (var i = 0; i < 29; i++) {
a = a.leftShift();
}
expect(a.lo).toEqual(0x80000000);
expect(a.hi).toEqual(0);
a = a.leftShift();
expect(a.lo).toEqual(0);
expect(a.hi).toEqual(1);
a = a.leftShift();
expect(a.lo).toEqual(0);
expect(a.hi).toEqual(2);
a = a.rightShift();
a = a.rightShift();
expect(a.lo).toEqual(0x80000000);
expect(a.hi).toEqual(0);
a = a.rightShift();
expect(a.lo).toEqual(0x40000000);
expect(a.hi).toEqual(0);
});
/**
* 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);
// Addition with carry.
var c = a.add(b);
expect(a.lo).toEqual(0x89abcdef); // originals unmodified.
expect(a.hi).toEqual(0x01234567);
expect(b.lo).toEqual(0xff52ab91);
expect(b.hi).toEqual(0x92fa2123);
expect(c.lo).toEqual(0x88fe7980);
expect(c.hi).toEqual(0x941d668b);
// Simple addition without carry.
a.lo = 2;
a.hi = 0;
b.lo = 3;
b.hi = 0;
c = a.add(b);
expect(c.lo).toEqual(5);
expect(c.hi).toEqual(0);
});
/**
* 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);
expect(c.hi).toEqual(a.hi);
expect(c.lo).toEqual(a.lo);
}
}
});
/**
* Tests 32-by-32 multiplication.
*/
it('testMul32x32', function() {
var testData = [
// a b low(a*b) high(a*b)
[0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8],
[0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc],
[0xfe4efe70, 0x80b48c37, 0xbcddea10, 0x7fdada0c],
[0xe222fd4a, 0xe43d524a, 0xd5e0eb64, 0xc99d549c],
[0xd171f469, 0xb94ebd01, 0x4be17969, 0x979bc4fa],
[0x829cc1df, 0xe2598b38, 0xf4157dc8, 0x737c12ad],
[0xf10c3767, 0x8382881e, 0x942b3612, 0x7bd428b8],
[0xb0f6dd24, 0x232597e1, 0x079c98a4, 0x184bbce7],
[0xfcdb05a7, 0x902f55bc, 0x636199a4, 0x8e69f412],
[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);
expect(c.lo).toEqual(cLow);
expect(c.hi).toEqual(cHigh);
}
});
/**
* Tests 64-by-32 multiplication.
*/
it('testMul', 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 = [
// low(a) high(a) low(a*b) high(a*b)
[0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f],
[0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b],
[0xf42d4fb4, 0xae366403, 0xa65a1000, 0x92434000, 0x1ff978df],
[0x17e2f56b, 0x25487693, 0xf13f98c7, 0x73794e2d, 0xa96b0c6a],
[0x492f241f, 0x76c0eb67, 0x7377ac44, 0xd4336c3c, 0xfc4b1ebe],
[0xd6b92321, 0xe184fa48, 0xd6e76904, 0x93141584, 0xcbf44da1],
[0x4bf007ea, 0x968c0a9e, 0xf5e4026a, 0x4fdb1ae4, 0x61b9fb7d],
[0x10a83be7, 0x2d685ba6, 0xc9e5fb7f, 0x2ad43499, 0x3742473d],
[0x2f261829, 0x1aca681a, 0x3d3494e3, 0x8213205b, 0x283719f8],
[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]);
expect(prod.lo).toEqual(testData[i][3]);
expect(prod.hi).toEqual(testData[i][4]);
}
});
/**
* Tests 64-div-by-32 division.
*/
it('testDiv', function() {
// Compute a/b, yielding quot = a/b and rem = a%b.
var 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],
[0x11912915, 0xb2699eb5, 0x30467cbe, 0xb21b4be4, 0x00000003, 0x283465dd],
[0x0d917982, 0x201f2a6e, 0x3f35bf03, 0x8217c8e4, 0x00000000, 0x153402d6],
[0xa072c108, 0x74020c96, 0xc60568fd, 0x95f9613e, 0x00000000, 0x3f4676c2],
[0xd845d5d8, 0xcdd235c4, 0x20426475, 0x6154e78b, 0x00000006, 0x202fb751],
[0xa4dbf71f, 0x9e90465e, 0xf08e022f, 0xa8be947f, 0x00000000, 0xbe43b5ce],
[0x3dbe627f, 0xa791f4b9, 0x28a5bd89, 0x1f5dfe93, 0x00000004, 0x02bf9ed4],
[0x5c1c53ee, 0xccf5102e, 0x198576e7, 0x07e3ae31, 0x00000008, 0x02ea8fb7],
[0xfef1e581, 0x04714067, 0xca6540c1, 0x059e73ec, 0x00000000, 0x31658095],
[0x1e2dd90c, 0x13dd6667, 0x8b2184c3, 0x248d1a42, 0x00000000, 0x4ca6d0c6],
// --- divisors in (0, 2^16-1) to test larger quotient high-words
// low(a) high(a) b low(quot) high(quot) rem
[0x86722b47, 0x2cd57c9a, 0x00003123, 0x2ae41b7a, 0x0000e995, 0x00000f99],
[0x1dd7884c, 0xf5e839bc, 0x00009eeb, 0x5c886242, 0x00018c21, 0x000099b6],
[0x5c53d625, 0x899fc7e5, 0x000087d7, 0xd625007a, 0x0001035c, 0x000019af],
[0x6932d932, 0x9d0a5488, 0x000051fb, 0x9d976143, 0x0001ea63, 0x00004981],
[0x4d18bb85, 0x0c92fb31, 0x00001d9f, 0x03265ab4, 0x00006cac, 0x000001b9],
[0xbe756768, 0xdea67ccb, 0x00008a03, 0x58add442, 0x00019cff, 0x000056a2],
[0xe2466f9a, 0x2521f114, 0x0000c350, 0xa0c0860d, 0x000030ab, 0x0000a48a],
[0xf00ddad1, 0xe2f5446a, 0x00002cfc, 0x762697a6, 0x00050b96, 0x00000b69],
[0xa879152a, 0x0a70e0a5, 0x00007cdf, 0xb44151b3, 0x00001567, 0x0000363d],
[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];
expect(quotient.lo).toEqual(testData[i][3]);
expect(quotient.hi).toEqual(testData[i][4]);
expect(remainder.lo).toEqual(testData[i][5]);
}
});
/**
* 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']
];
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());
expect(roundtrip.lo).toEqual(a.lo);
expect(roundtrip.hi).toEqual(a.hi);
expect(a.toString()).toEqual(testData[i][2]);
}
});
/**
* Tests signed Int64s. These are built on UInt64s, so we only need to test
* 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'
];
for (var i = 0; i < testStrings.length; i++) {
var roundtrip =
jspb.arith.Int64.fromString(testStrings[i]).toString();
expect(roundtrip).toEqual(testStrings[i]);
}
});
});

View File

@ -1,377 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview This file contains constants and typedefs used by
* jspb.BinaryReader and BinaryWriter.
* @suppress {missingRequire} TODO(b/152540451): this shouldn't be needed
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.provide('jspb.AnyFieldType');
goog.provide('jspb.BinaryConstants');
goog.provide('jspb.BinaryMessage');
goog.provide('jspb.BuilderFunction');
goog.provide('jspb.ByteSource');
goog.provide('jspb.ClonerFunction');
goog.provide('jspb.ComparerFunction');
goog.provide('jspb.ConstBinaryMessage');
goog.provide('jspb.PrunerFunction');
goog.provide('jspb.ReaderFunction');
goog.provide('jspb.RecyclerFunction');
goog.provide('jspb.RepeatedFieldType');
goog.provide('jspb.ScalarFieldType');
goog.provide('jspb.WriterFunction');
goog.forwardDeclare('jspb.BinaryMessage');
goog.forwardDeclare('jspb.BinaryReader');
goog.forwardDeclare('jspb.BinaryWriter');
goog.forwardDeclare('jspb.Message');
goog.forwardDeclare('jsprotolib.BinaryExtension');
/**
* Base interface class for all const messages.
* @interface
*/
jspb.ConstBinaryMessage = function() {};
/**
* Generate a debug string for this proto that is in proto2 text format.
* @return {string} The debug string.
*/
jspb.ConstBinaryMessage.prototype.toDebugString;
/**
* Helper to generate a debug string for this proto at some indent level. The
* first line is not indented.
* @param {number} indentLevel The number of spaces by which to indent lines.
* @return {string} The debug string.
* @protected
*/
jspb.ConstBinaryMessage.prototype.toDebugStringInternal;
/**
* Base interface class for all messages. Does __not__ define any methods, as
* doing so on a widely-used interface defeats dead-code elimination.
* @interface
* @extends {jspb.ConstBinaryMessage}
*/
jspb.BinaryMessage = function() {};
/**
* The types convertible to Uint8Arrays. Strings are assumed to be
* base64-encoded.
* @typedef {ArrayBuffer|Uint8Array|Array<number>|string}
*/
jspb.ByteSource;
/**
* A scalar field in jspb can be a boolean, number, or string.
* @typedef {boolean|number|string}
*/
jspb.ScalarFieldType;
/**
* A repeated field in jspb is an array of scalars, blobs, or messages.
* @typedef {!Array<jspb.ScalarFieldType>|
!Array<!Uint8Array>|
!Array<!jspb.ConstBinaryMessage>|
!Array<!jspb.BinaryMessage>}
*/
jspb.RepeatedFieldType;
/**
* A field in jspb can be a scalar, a block of bytes, another proto, or an
* array of any of the above.
* @typedef {jspb.ScalarFieldType|
jspb.RepeatedFieldType|
!Uint8Array|
!jspb.ConstBinaryMessage|
!jspb.BinaryMessage|
!jsprotolib.BinaryExtension}
*/
jspb.AnyFieldType;
/**
* A builder function creates an instance of a message object.
* @typedef {function():!jspb.BinaryMessage}
*/
jspb.BuilderFunction;
/**
* A cloner function creates a deep copy of a message object.
* @typedef {function(jspb.ConstBinaryMessage):jspb.BinaryMessage}
*/
jspb.ClonerFunction;
/**
* A recycler function destroys an instance of a message object.
* @typedef {function(!jspb.BinaryMessage):void}
*/
jspb.RecyclerFunction;
/**
* A reader function initializes a message using data from a BinaryReader.
* @typedef {function(!jspb.BinaryMessage, !jspb.BinaryReader):void}
*/
jspb.ReaderFunction;
/**
* A writer function serializes a message to a BinaryWriter.
* @typedef {function((!jspb.Message|!jspb.ConstBinaryMessage),
* !jspb.BinaryWriter):void}
*/
jspb.WriterFunction;
/**
* A pruner function removes default-valued fields and empty submessages from a
* message and returns either the pruned message or null if the entire message
* was pruned away.
* @typedef {function(?jspb.BinaryMessage):?jspb.BinaryMessage}
*/
jspb.PrunerFunction;
/**
* A comparer function returns true if two protos are equal.
* @typedef {function(?jspb.ConstBinaryMessage,
* ?jspb.ConstBinaryMessage):boolean}
*/
jspb.ComparerFunction;
/**
* Field type codes, taken from proto2/public/wire_format_lite.h.
* @enum {number}
*/
jspb.BinaryConstants.FieldType = {
INVALID: -1,
DOUBLE: 1,
FLOAT: 2,
INT64: 3,
UINT64: 4,
INT32: 5,
FIXED64: 6,
FIXED32: 7,
BOOL: 8,
STRING: 9,
GROUP: 10,
MESSAGE: 11,
BYTES: 12,
UINT32: 13,
ENUM: 14,
SFIXED32: 15,
SFIXED64: 16,
SINT32: 17,
SINT64: 18,
// Extended types for Javascript
FHASH64: 30, // 64-bit hash string, fixed-length encoding.
VHASH64: 31 // 64-bit hash string, varint encoding.
};
/**
* Wire-format type codes, taken from proto2/public/wire_format_lite.h.
* @enum {number}
*/
jspb.BinaryConstants.WireType = {
INVALID: -1,
VARINT: 0,
FIXED64: 1,
DELIMITED: 2,
START_GROUP: 3,
END_GROUP: 4,
FIXED32: 5
};
/**
* Translates field type to wire type.
* @param {jspb.BinaryConstants.FieldType} fieldType
* @return {jspb.BinaryConstants.WireType}
*/
jspb.BinaryConstants.FieldTypeToWireType = function(fieldType) {
var fieldTypes = jspb.BinaryConstants.FieldType;
var wireTypes = jspb.BinaryConstants.WireType;
switch (fieldType) {
case fieldTypes.INT32:
case fieldTypes.INT64:
case fieldTypes.UINT32:
case fieldTypes.UINT64:
case fieldTypes.SINT32:
case fieldTypes.SINT64:
case fieldTypes.BOOL:
case fieldTypes.ENUM:
case fieldTypes.VHASH64:
return wireTypes.VARINT;
case fieldTypes.DOUBLE:
case fieldTypes.FIXED64:
case fieldTypes.SFIXED64:
case fieldTypes.FHASH64:
return wireTypes.FIXED64;
case fieldTypes.STRING:
case fieldTypes.MESSAGE:
case fieldTypes.BYTES:
return wireTypes.DELIMITED;
case fieldTypes.FLOAT:
case fieldTypes.FIXED32:
case fieldTypes.SFIXED32:
return wireTypes.FIXED32;
case fieldTypes.INVALID:
case fieldTypes.GROUP:
default:
return wireTypes.INVALID;
}
};
/**
* Flag to indicate a missing field.
* @const {number}
*/
jspb.BinaryConstants.INVALID_FIELD_NUMBER = -1;
/**
* The smallest denormal float32 value.
* @const {number}
*/
jspb.BinaryConstants.FLOAT32_EPS = 1.401298464324817e-45;
/**
* The smallest normal float64 value.
* @const {number}
*/
jspb.BinaryConstants.FLOAT32_MIN = 1.1754943508222875e-38;
/**
* The largest finite float32 value.
* @const {number}
*/
jspb.BinaryConstants.FLOAT32_MAX = 3.4028234663852886e+38;
/**
* The smallest denormal float64 value.
* @const {number}
*/
jspb.BinaryConstants.FLOAT64_EPS = 5e-324;
/**
* The smallest normal float64 value.
* @const {number}
*/
jspb.BinaryConstants.FLOAT64_MIN = 2.2250738585072014e-308;
/**
* The largest finite float64 value.
* @const {number}
*/
jspb.BinaryConstants.FLOAT64_MAX = 1.7976931348623157e+308;
/**
* Convenience constant equal to 2^20.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_20 = 1048576;
/**
* Convenience constant equal to 2^23.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_23 = 8388608;
/**
* Convenience constant equal to 2^31.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_31 = 2147483648;
/**
* Convenience constant equal to 2^32.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_32 = 4294967296;
/**
* Convenience constant equal to 2^52.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_52 = 4503599627370496;
/**
* Convenience constant equal to 2^63.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_63 = 9223372036854775808;
/**
* Convenience constant equal to 2^64.
* @const {number}
*/
jspb.BinaryConstants.TWO_TO_64 = 18446744073709551616;
/**
* Eight-character string of zeros, used as the default 64-bit hash value.
* @const {string}
*/
jspb.BinaryConstants.ZERO_HASH = '\0\0\0\0\0\0\0\0';

View File

@ -1,951 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview This file contains utilities for decoding primitive values
* (signed and unsigned integers, varints, booleans, enums, hashes, strings,
* and raw bytes) embedded in Uint8Arrays into their corresponding Javascript
* types.
*
* Major caveat - Javascript is unable to accurately represent integers larger
* than 2^53 due to its use of a double-precision floating point format or all
* numbers. If you need to guarantee that 64-bit values survive with all bits
* intact, you _must_ read them using one of the Hash64 methods, which return
* an 8-character string.
*
* @suppress {missingRequire} TODO(b/152540451): this shouldn't be needed
* @author aappleby@google.com (Austin Appleby)
*/
goog.provide('jspb.BinaryDecoder');
goog.require('goog.asserts');
goog.require('goog.crypt');
goog.require('jspb.utils');
/**
* BinaryDecoder implements the decoders for all the wire types specified in
* https://developers.google.com/protocol-buffers/docs/encoding.
*
* @param {jspb.ByteSource=} opt_bytes The bytes we're reading from.
* @param {number=} opt_start The optional offset to start reading at.
* @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.
* @constructor
* @struct
*/
jspb.BinaryDecoder = function(opt_bytes, opt_start, opt_length) {
/**
* Typed byte-wise view of the source buffer.
* @private {?Uint8Array}
*/
this.bytes_ = null;
/**
* Start point of the block to read.
* @private {number}
*/
this.start_ = 0;
/**
* End point of the block to read.
* @private {number}
*/
this.end_ = 0;
/**
* Current read location in bytes_.
* @private {number}
*/
this.cursor_ = 0;
/**
* Set to true if this decoder encountered an error due to corrupt data.
* @private {boolean}
*/
this.error_ = false;
if (opt_bytes) {
this.setBlock(opt_bytes, opt_start, opt_length);
}
};
/**
* Global pool of BinaryDecoder instances.
* @private {!Array<!jspb.BinaryDecoder>}
*/
jspb.BinaryDecoder.instanceCache_ = [];
/**
* Pops an instance off the instance cache, or creates one if the cache is
* empty.
* @param {jspb.ByteSource=} opt_bytes The bytes we're reading from.
* @param {number=} opt_start The optional offset to start reading at.
* @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.
* @return {!jspb.BinaryDecoder}
*/
jspb.BinaryDecoder.alloc = function(opt_bytes, opt_start, opt_length) {
if (jspb.BinaryDecoder.instanceCache_.length) {
var newDecoder = jspb.BinaryDecoder.instanceCache_.pop();
if (opt_bytes) {
newDecoder.setBlock(opt_bytes, opt_start, opt_length);
}
return newDecoder;
} else {
return new jspb.BinaryDecoder(opt_bytes, opt_start, opt_length);
}
};
/**
* Puts this instance back in the instance cache.
*/
jspb.BinaryDecoder.prototype.free = function() {
this.clear();
if (jspb.BinaryDecoder.instanceCache_.length < 100) {
jspb.BinaryDecoder.instanceCache_.push(this);
}
};
/**
* Makes a copy of this decoder.
* @return {!jspb.BinaryDecoder}
*/
jspb.BinaryDecoder.prototype.clone = function() {
return jspb.BinaryDecoder.alloc(this.bytes_,
this.start_, this.end_ - this.start_);
};
/**
* Clears the decoder.
*/
jspb.BinaryDecoder.prototype.clear = function() {
this.bytes_ = null;
this.start_ = 0;
this.end_ = 0;
this.cursor_ = 0;
this.error_ = false;
};
/**
* Returns the raw buffer.
* @return {?Uint8Array} The raw buffer.
*/
jspb.BinaryDecoder.prototype.getBuffer = function() {
return this.bytes_;
};
/**
* Changes the block of bytes we're decoding.
* @param {!jspb.ByteSource} data The bytes we're reading from.
* @param {number=} opt_start The optional offset to start reading at.
* @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) {
this.bytes_ = jspb.utils.byteSourceToUint8Array(data);
this.start_ = (opt_start !== undefined) ? opt_start : 0;
this.end_ = (opt_length !== undefined) ? this.start_ + opt_length :
this.bytes_.length;
this.cursor_ = this.start_;
};
/**
* @return {number}
*/
jspb.BinaryDecoder.prototype.getEnd = function() {
return this.end_;
};
/**
* @param {number} end
*/
jspb.BinaryDecoder.prototype.setEnd = function(end) {
this.end_ = end;
};
/**
* Moves the read cursor back to the start of the block.
*/
jspb.BinaryDecoder.prototype.reset = function() {
this.cursor_ = this.start_;
};
/**
* Returns the internal read cursor.
* @return {number} The internal read cursor.
*/
jspb.BinaryDecoder.prototype.getCursor = function() {
return this.cursor_;
};
/**
* Returns the internal read cursor.
* @param {number} cursor The new cursor.
*/
jspb.BinaryDecoder.prototype.setCursor = function(cursor) {
this.cursor_ = cursor;
};
/**
* Advances the stream cursor by the given number of bytes.
* @param {number} count The number of bytes to advance by.
*/
jspb.BinaryDecoder.prototype.advance = function(count) {
this.cursor_ += count;
goog.asserts.assert(this.cursor_ <= this.end_);
};
/**
* Returns true if this decoder is at the end of the block.
* @return {boolean}
*/
jspb.BinaryDecoder.prototype.atEnd = function() {
return this.cursor_ == this.end_;
};
/**
* Returns true if this decoder is at the end of the block.
* @return {boolean}
*/
jspb.BinaryDecoder.prototype.pastEnd = function() {
return this.cursor_ > this.end_;
};
/**
* Returns true if this decoder encountered an error due to corrupt data.
* @return {boolean}
*/
jspb.BinaryDecoder.prototype.getError = function() {
return this.error_ ||
(this.cursor_ < 0) ||
(this.cursor_ > this.end_);
};
/**
* Reads an unsigned varint from the binary stream and invokes the conversion
* function with the value in two signed 32 bit integers to produce the result.
* Since this does not convert the value to a number, no precision is lost.
*
* It's possible for an unsigned varint to be incorrectly encoded - more than
* 64 bits' worth of data could be present. If this happens, this method will
* throw an error.
*
* Decoding varints requires doing some funny base-128 math - for more
* details on the format, see
* https://developers.google.com/protocol-buffers/docs/encoding
*
* @param {function(number, number): T} convert Conversion function to produce
* the result value, takes parameters (lowBits, highBits).
* @return {T}
* @template T
*/
jspb.BinaryDecoder.prototype.readSplitVarint64 = function(convert) {
var temp = 128;
var lowBits = 0;
var highBits = 0;
// Read the first four bytes of the varint, stopping at the terminator if we
// see it.
for (var i = 0; i < 4 && temp >= 128; i++) {
temp = this.bytes_[this.cursor_++];
lowBits |= (temp & 0x7F) << (i * 7);
}
if (temp >= 128) {
// Read the fifth byte, which straddles the low and high dwords.
temp = this.bytes_[this.cursor_++];
lowBits |= (temp & 0x7F) << 28;
highBits |= (temp & 0x7F) >> 4;
}
if (temp >= 128) {
// Read the sixth through tenth byte.
for (var i = 0; i < 5 && temp >= 128; i++) {
temp = this.bytes_[this.cursor_++];
highBits |= (temp & 0x7F) << (i * 7 + 3);
}
}
if (temp < 128) {
return convert(lowBits >>> 0, highBits >>> 0);
}
// If we did not see the terminator, the encoding was invalid.
goog.asserts.fail('Failed to read varint, encoding is invalid.');
this.error_ = true;
};
/**
* Reads a signed zigzag encoded varint from the binary stream and invokes
* the conversion function with the value in two signed 32 bit integers to
* produce the result. Since this does not convert the value to a number, no
* precision is lost.
*
* It's possible for an unsigned varint to be incorrectly encoded - more than
* 64 bits' worth of data could be present. If this happens, this method will
* throw an error.
*
* Zigzag encoding is a modification of varint encoding that reduces the
* storage overhead for small negative integers - for more details on the
* format, see https://developers.google.com/protocol-buffers/docs/encoding
*
* @param {function(number, number): T} convert Conversion function to produce
* the result value, takes parameters (lowBits, highBits).
* @return {T}
* @template T
*/
jspb.BinaryDecoder.prototype.readSplitZigzagVarint64 = function(convert) {
return this.readSplitVarint64(function(low, high) {
return jspb.utils.fromZigzag64(low, high, convert);
});
};
/**
* Reads a 64-bit fixed-width value from the stream and invokes the conversion
* function with the value in two signed 32 bit integers to produce the result.
* Since this does not convert the value to a number, no precision is lost.
*
* @param {function(number, number): T} convert Conversion function to produce
* the result value, takes parameters (lowBits, highBits).
* @return {T}
* @template T
*/
jspb.BinaryDecoder.prototype.readSplitFixed64 = function(convert) {
var bytes = this.bytes_;
var cursor = this.cursor_;
this.cursor_ += 8;
var lowBits = 0;
var highBits = 0;
for (var i = cursor + 7; i >= cursor; i--) {
lowBits = (lowBits << 8) | bytes[i];
highBits = (highBits << 8) | bytes[i + 4];
}
return convert(lowBits, highBits);
};
/**
* Skips over a varint in the block without decoding it.
*/
jspb.BinaryDecoder.prototype.skipVarint = function() {
while (this.bytes_[this.cursor_] & 0x80) {
this.cursor_++;
}
this.cursor_++;
};
/**
* Skips backwards over a varint in the block - to do this correctly, we have
* to know the value we're skipping backwards over or things are ambiguous.
* @param {number} value The varint value to unskip.
*/
jspb.BinaryDecoder.prototype.unskipVarint = function(value) {
while (value > 128) {
this.cursor_--;
value = value >>> 7;
}
this.cursor_--;
};
/**
* Reads a 32-bit varint from the binary stream. Due to a quirk of the encoding
* format and Javascript's handling of bitwise math, this actually works
* correctly for both signed and unsigned 32-bit varints.
*
* This function is called vastly more frequently than any other in
* BinaryDecoder, so it has been unrolled and tweaked for performance.
*
* If there are more than 32 bits of data in the varint, it _must_ be due to
* sign-extension. If we're in debug mode and the high 32 bits don't match the
* expected sign extension, this method will throw an error.
*
* Decoding varints requires doing some funny base-128 math - for more
* details on the format, see
* https://developers.google.com/protocol-buffers/docs/encoding
*
* @return {number} The decoded unsigned 32-bit varint.
*/
jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() {
var temp;
var bytes = this.bytes_;
temp = bytes[this.cursor_ + 0];
var x = (temp & 0x7F);
if (temp < 128) {
this.cursor_ += 1;
goog.asserts.assert(this.cursor_ <= this.end_);
return x;
}
temp = bytes[this.cursor_ + 1];
x |= (temp & 0x7F) << 7;
if (temp < 128) {
this.cursor_ += 2;
goog.asserts.assert(this.cursor_ <= this.end_);
return x;
}
temp = bytes[this.cursor_ + 2];
x |= (temp & 0x7F) << 14;
if (temp < 128) {
this.cursor_ += 3;
goog.asserts.assert(this.cursor_ <= this.end_);
return x;
}
temp = bytes[this.cursor_ + 3];
x |= (temp & 0x7F) << 21;
if (temp < 128) {
this.cursor_ += 4;
goog.asserts.assert(this.cursor_ <= this.end_);
return x;
}
temp = bytes[this.cursor_ + 4];
x |= (temp & 0x0F) << 28;
if (temp < 128) {
// 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_);
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 &&
bytes[this.cursor_++] >= 128) {
// If we get here, the varint is too long.
goog.asserts.assert(false);
}
goog.asserts.assert(this.cursor_ <= this.end_);
return x;
};
/**
* The readUnsignedVarint32 above deals with signed 32-bit varints correctly,
* so this is just an alias.
*
* @return {number} The decoded signed 32-bit varint.
*/
jspb.BinaryDecoder.prototype.readSignedVarint32 =
jspb.BinaryDecoder.prototype.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() {
// 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.
var value = this.readUnsignedVarint32();
return value.toString();
};
/**
* Reads a 32-bit signed variant and returns its value as a string.
*
* @return {string} The decoded signed 32-bit varint as a string.
*/
jspb.BinaryDecoder.prototype.readSignedVarint32String = 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.
var value = this.readSignedVarint32();
return value.toString();
};
/**
* Reads a signed, zigzag-encoded 32-bit varint from the binary stream.
*
* Zigzag encoding is a modification of varint encoding that reduces the
* storage overhead for small negative integers - for more details on the
* format, see https://developers.google.com/protocol-buffers/docs/encoding
*
* @return {number} The decoded signed, zigzag-encoded 32-bit varint.
*/
jspb.BinaryDecoder.prototype.readZigzagVarint32 = function() {
var result = this.readUnsignedVarint32();
return (result >>> 1) ^ - (result & 1);
};
/**
* Reads an unsigned 64-bit varint from the binary stream. Note that since
* Javascript represents all numbers as double-precision floats, there will be
* precision lost if the absolute value of the varint is larger than 2^53.
*
* @return {number} The decoded unsigned varint. Precision will be lost if the
* integer exceeds 2^53.
*/
jspb.BinaryDecoder.prototype.readUnsignedVarint64 = function() {
return this.readSplitVarint64(jspb.utils.joinUint64);
};
/**
* Reads an unsigned 64-bit varint from the binary stream and returns the value
* as a decimal string.
*
* @return {string} The decoded unsigned varint as a decimal string.
*/
jspb.BinaryDecoder.prototype.readUnsignedVarint64String = function() {
return this.readSplitVarint64(jspb.utils.joinUnsignedDecimalString);
};
/**
* Reads a signed 64-bit varint from the binary stream. Note that since
* Javascript represents all numbers as double-precision floats, there will be
* precision lost if the absolute value of the varint is larger than 2^53.
*
* @return {number} The decoded signed varint. Precision will be lost if the
* integer exceeds 2^53.
*/
jspb.BinaryDecoder.prototype.readSignedVarint64 = function() {
return this.readSplitVarint64(jspb.utils.joinInt64);
};
/**
* Reads an signed 64-bit varint from the binary stream and returns the value
* as a decimal string.
*
* @return {string} The decoded signed varint as a decimal string.
*/
jspb.BinaryDecoder.prototype.readSignedVarint64String = function() {
return this.readSplitVarint64(jspb.utils.joinSignedDecimalString);
};
/**
* Reads a signed, zigzag-encoded 64-bit varint from the binary stream. Note
* that since Javascript represents all numbers as double-precision floats,
* there will be precision lost if the absolute value of the varint is larger
* than 2^53.
*
* Zigzag encoding is a modification of varint encoding that reduces the
* storage overhead for small negative integers - for more details on the
* format, see https://developers.google.com/protocol-buffers/docs/encoding
*
* @return {number} The decoded zigzag varint. Precision will be lost if the
* integer exceeds 2^53.
*/
jspb.BinaryDecoder.prototype.readZigzagVarint64 = function() {
return this.readSplitVarint64(jspb.utils.joinZigzag64);
};
/**
* Reads a signed, zigzag-encoded 64-bit varint from the binary stream
* losslessly and returns it as an 8-character Unicode string for use as a hash
* table key.
*
* Zigzag encoding is a modification of varint encoding that reduces the
* storage overhead for small negative integers - for more details on the
* format, see https://developers.google.com/protocol-buffers/docs/encoding
*
* @return {string} The decoded zigzag varint in hash64 format.
*/
jspb.BinaryDecoder.prototype.readZigzagVarintHash64 = function() {
return this.readSplitZigzagVarint64(jspb.utils.joinHash64);
};
/**
* Reads a signed, zigzag-encoded 64-bit varint from the binary stream and
* returns its value as a string.
*
* Zigzag encoding is a modification of varint encoding that reduces the
* storage overhead for small negative integers - for more details on the
* format, see https://developers.google.com/protocol-buffers/docs/encoding
*
* @return {string} The decoded signed, zigzag-encoded 64-bit varint as a
* string.
*/
jspb.BinaryDecoder.prototype.readZigzagVarint64String = function() {
return this.readSplitZigzagVarint64(jspb.utils.joinSignedDecimalString);
};
/**
* Reads a raw unsigned 8-bit integer from the binary stream.
*
* @return {number} The unsigned 8-bit integer read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readUint8 = function() {
var a = this.bytes_[this.cursor_ + 0];
this.cursor_ += 1;
goog.asserts.assert(this.cursor_ <= this.end_);
return a;
};
/**
* Reads a raw unsigned 16-bit integer from the binary stream.
*
* @return {number} The unsigned 16-bit integer read from the binary stream.
*/
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_);
return (a << 0) | (b << 8);
};
/**
* Reads a raw unsigned 32-bit integer from the binary stream.
*
* @return {number} The unsigned 32-bit integer read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readUint32 = function() {
var a = this.bytes_[this.cursor_ + 0];
var b = this.bytes_[this.cursor_ + 1];
var c = this.bytes_[this.cursor_ + 2];
var d = this.bytes_[this.cursor_ + 3];
this.cursor_ += 4;
goog.asserts.assert(this.cursor_ <= this.end_);
return ((a << 0) | (b << 8) | (c << 16) | (d << 24)) >>> 0;
};
/**
* Reads a raw unsigned 64-bit integer from the binary stream. Note that since
* Javascript represents all numbers as double-precision floats, there will be
* precision lost if the absolute value of the integer is larger than 2^53.
*
* @return {number} The unsigned 64-bit integer read from the binary stream.
* Precision will be lost if the integer exceeds 2^53.
*/
jspb.BinaryDecoder.prototype.readUint64 = function() {
var bitsLow = this.readUint32();
var bitsHigh = this.readUint32();
return jspb.utils.joinUint64(bitsLow, bitsHigh);
};
/**
* Reads a raw unsigned 64-bit integer from the binary stream. Note that since
* Javascript represents all numbers as double-precision floats, there will be
* precision lost if the absolute value of the integer is larger than 2^53.
*
* @return {string} The unsigned 64-bit integer read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readUint64String = function() {
var bitsLow = this.readUint32();
var bitsHigh = this.readUint32();
return jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
};
/**
* Reads a raw signed 8-bit integer from the binary stream.
*
* @return {number} The signed 8-bit integer read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readInt8 = function() {
var a = this.bytes_[this.cursor_ + 0];
this.cursor_ += 1;
goog.asserts.assert(this.cursor_ <= this.end_);
return (a << 24) >> 24;
};
/**
* Reads a raw signed 16-bit integer from the binary stream.
*
* @return {number} The signed 16-bit integer read from the binary stream.
*/
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_);
return (((a << 0) | (b << 8)) << 16) >> 16;
};
/**
* Reads a raw signed 32-bit integer from the binary stream.
*
* @return {number} The signed 32-bit integer read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readInt32 = function() {
var a = this.bytes_[this.cursor_ + 0];
var b = this.bytes_[this.cursor_ + 1];
var c = this.bytes_[this.cursor_ + 2];
var d = this.bytes_[this.cursor_ + 3];
this.cursor_ += 4;
goog.asserts.assert(this.cursor_ <= this.end_);
return (a << 0) | (b << 8) | (c << 16) | (d << 24);
};
/**
* Reads a raw signed 64-bit integer from the binary stream. Note that since
* Javascript represents all numbers as double-precision floats, there will be
* precision lost if the absolute value of the integer is larger than 2^53.
*
* @return {number} The signed 64-bit integer read from the binary stream.
* Precision will be lost if the integer exceeds 2^53.
*/
jspb.BinaryDecoder.prototype.readInt64 = function() {
var bitsLow = this.readUint32();
var bitsHigh = this.readUint32();
return jspb.utils.joinInt64(bitsLow, bitsHigh);
};
/**
* Reads a raw signed 64-bit integer from the binary stream and returns it as a
* string.
*
* @return {string} The signed 64-bit integer read from the binary stream.
* Precision will be lost if the integer exceeds 2^53.
*/
jspb.BinaryDecoder.prototype.readInt64String = function() {
var bitsLow = this.readUint32();
var bitsHigh = this.readUint32();
return jspb.utils.joinSignedDecimalString(bitsLow, bitsHigh);
};
/**
* Reads a 32-bit floating-point number from the binary stream, using the
* temporary buffer to realign the data.
*
* @return {number} The float read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readFloat = function() {
var bitsLow = this.readUint32();
var bitsHigh = 0;
return jspb.utils.joinFloat32(bitsLow, bitsHigh);
};
/**
* Reads a 64-bit floating-point number from the binary stream, using the
* temporary buffer to realign the data.
*
* @return {number} The double read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readDouble = function() {
var bitsLow = this.readUint32();
var bitsHigh = this.readUint32();
return jspb.utils.joinFloat64(bitsLow, bitsHigh);
};
/**
* Reads a boolean value from the binary stream.
* @return {boolean} The boolean read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readBool = function() {
return !!this.bytes_[this.cursor_++];
};
/**
* Reads an enum value from the binary stream, which are always encoded as
* signed varints.
* @return {number} The enum value read from the binary stream.
*/
jspb.BinaryDecoder.prototype.readEnum = function() {
return this.readSignedVarint32();
};
/**
* Reads and parses a UTF-8 encoded unicode string from the stream.
* The code is inspired by maps.vectortown.parse.StreamedDataViewReader.
* Supports codepoints from U+0000 up to U+10FFFF.
* (http://en.wikipedia.org/wiki/UTF-8).
* @param {number} length The length of the string to read.
* @return {string} The decoded string.
*/
jspb.BinaryDecoder.prototype.readString = function(length) {
var bytes = this.bytes_;
var cursor = this.cursor_;
var end = cursor + length;
var codeUnits = [];
var result = '';
while (cursor < end) {
var c = bytes[cursor++];
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.
var c2 = bytes[cursor++];
codeUnits.push(((c & 31) << 6) | (c2 & 63));
} 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.
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);
// Surrogates formula from wikipedia.
// 1. Subtract 0x10000 from codepoint
codepoint -= 0x10000;
// 2. Split this into the high 10-bit value and the low 10-bit value
// 3. Add 0xD800 to the high value to form the high surrogate
// 4. Add 0xDC00 to the low value to form the low surrogate:
var low = (codepoint & 1023) + 0xDC00;
var high = ((codepoint >> 10) & 1023) + 0xD800;
codeUnits.push(high, low);
}
// Avoid exceeding the maximum stack size when calling `apply`.
if (codeUnits.length >= 8192) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
result += goog.crypt.byteArrayToString(codeUnits);
this.cursor_ = cursor;
return result;
};
/**
* Reads and parses a UTF-8 encoded unicode string (with length prefix) from
* the stream.
* @return {string} The decoded string.
*/
jspb.BinaryDecoder.prototype.readStringWithLength = function() {
var length = this.readUnsignedVarint32();
return this.readString(length);
};
/**
* Reads a block of raw bytes from the binary stream.
*
* @param {number} length The number of bytes to read.
* @return {!Uint8Array} The decoded block of bytes, or an empty block if the
* length was invalid.
*/
jspb.BinaryDecoder.prototype.readBytes = function(length) {
if (length < 0 ||
this.cursor_ + length > this.bytes_.length) {
this.error_ = true;
goog.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_);
return result;
};
/**
* Reads a 64-bit varint from the stream and returns it as an 8-character
* Unicode string for use as a hash table key.
*
* @return {string} The hash value.
*/
jspb.BinaryDecoder.prototype.readVarintHash64 = function() {
return this.readSplitVarint64(jspb.utils.joinHash64);
};
/**
* Reads a 64-bit fixed-width value from the stream and returns it as an
* 8-character Unicode string for use as a hash table key.
*
* @return {string} The hash value.
*/
jspb.BinaryDecoder.prototype.readFixedHash64 = function() {
var bytes = this.bytes_;
var cursor = this.cursor_;
var a = bytes[cursor + 0];
var b = bytes[cursor + 1];
var c = bytes[cursor + 2];
var d = bytes[cursor + 3];
var e = bytes[cursor + 4];
var f = bytes[cursor + 5];
var g = bytes[cursor + 6];
var h = bytes[cursor + 7];
this.cursor_ += 8;
return String.fromCharCode(a, b, c, d, e, f, g, h);
};

View File

@ -1,481 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer decoder.
*
* There are two particular magic numbers that need to be pointed out -
* 2^64-1025 is the largest number representable as both a double and an
* unsigned 64-bit integer, and 2^63-513 is the largest number representable as
* both a double and a signed 64-bit integer.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @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');
/**
* Tests encoding and decoding of unsigned types.
* @param {Function} readValue
* @param {Function} writeValue
* @param {number} epsilon
* @param {number} upperLimit
* @param {Function} filter
* @suppress {missingProperties|visibility}
*/
function doTestUnsignedValue(readValue,
writeValue, epsilon, upperLimit, filter) {
var encoder = new jspb.BinaryEncoder();
// Encode zero and limits.
writeValue.call(encoder, filter(0));
writeValue.call(encoder, filter(epsilon));
writeValue.call(encoder, filter(upperLimit));
// Encode positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
writeValue.call(encoder, filter(cursor));
}
var 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));
// Check positive values.
for (var 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);});
}
/**
* Tests encoding and decoding of signed types.
* @param {Function} readValue
* @param {Function} writeValue
* @param {number} epsilon
* @param {number} lowerLimit
* @param {number} upperLimit
* @param {Function} filter
* @suppress {missingProperties}
*/
function doTestSignedValue(readValue,
writeValue, epsilon, lowerLimit, upperLimit, filter) {
var encoder = new jspb.BinaryEncoder();
// Encode zero and limits.
writeValue.call(encoder, filter(lowerLimit));
writeValue.call(encoder, filter(-epsilon));
writeValue.call(encoder, filter(0));
writeValue.call(encoder, filter(epsilon));
writeValue.call(encoder, filter(upperLimit));
var inputValues = [];
// Encode negative values.
for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
var 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);
writeValue.call(encoder, val);
inputValues.push(val);
}
var 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));
// Verify decoded values.
for (var i = 0; i < inputValues.length; i++) {
assertEquals(inputValues[i], readValue.call(decoder));
}
// Encoding values outside the valid range should assert.
var pastLowerLimit = lowerLimit * 1.1;
var pastUpperLimit = upperLimit * 1.1;
if (pastLowerLimit !== -Infinity) {
expect(() => void writeValue.call(encoder, pastLowerLimit)).toThrow();
}
if (pastUpperLimit !== Infinity) {
expect(() => void writeValue.call(encoder, pastUpperLimit)).toThrow();
}
}
describe('binaryDecoderTest', function() {
/**
* Tests the decoder instance cache.
*/
it('testInstanceCache', /** @suppress {visibility} */ function() {
// Empty the instance caches.
jspb.BinaryDecoder.instanceCache_ = [];
// Allocating and then freeing a decoder should put it in the instance
// cache.
jspb.BinaryDecoder.alloc().free();
assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
// 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();
decoder1.free();
decoder2.free();
decoder3.free();
assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
});
describe('varint64', function() {
var /** !jspb.BinaryEncoder */ encoder;
var /** !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() {
encoder = new jspb.BinaryEncoder();
encoder.writeVarintHash64(hashA);
encoder.writeVarintHash64(hashB);
encoder.writeVarintHash64(hashC);
encoder.writeVarintHash64(hashD);
encoder.writeFixedHash64(hashA);
encoder.writeFixedHash64(hashB);
encoder.writeFixedHash64(hashC);
encoder.writeFixedHash64(hashD);
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());
assertEquals(hashA, decoder.readFixedHash64());
assertEquals(hashB, decoder.readFixedHash64());
assertEquals(hashC, decoder.readFixedHash64());
assertEquals(hashD, decoder.readFixedHash64());
});
it('reads split 64 bit integers', function() {
function hexJoin(bitsLow, bitsHigh) {
return `0x${(bitsHigh >>> 0).toString(16)}:0x${
(bitsLow >>> 0).toString(16)}`;
}
function hexJoinHash(hash64) {
jspb.utils.splitHash64(hash64);
return hexJoin(jspb.utils.split64Low, jspb.utils.split64High);
}
expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashA));
expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashB));
expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashC));
expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashD));
expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashA));
expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashB));
expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashC));
expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashD));
});
});
describe('sint64', function() {
var /** !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() {
var encoder = new jspb.BinaryEncoder();
encoder.writeZigzagVarintHash64(hashA);
encoder.writeZigzagVarintHash64(hashB);
encoder.writeZigzagVarintHash64(hashC);
encoder.writeZigzagVarintHash64(hashD);
decoder = jspb.BinaryDecoder.alloc(encoder.end());
});
it('reads 64-bit integers as decimal strings', function() {
const signed = true;
expect(decoder.readZigzagVarint64String())
.toEqual(jspb.utils.hash64ToDecimalString(hashA, signed));
expect(decoder.readZigzagVarint64String())
.toEqual(jspb.utils.hash64ToDecimalString(hashB, signed));
expect(decoder.readZigzagVarint64String())
.toEqual(jspb.utils.hash64ToDecimalString(hashC, signed));
expect(decoder.readZigzagVarint64String())
.toEqual(jspb.utils.hash64ToDecimalString(hashD, signed));
});
it('reads 64-bit integers as hash strings', function() {
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() {
function hexJoin(bitsLow, bitsHigh) {
return `0x${(bitsHigh >>> 0).toString(16)}:0x${
(bitsLow >>> 0).toString(16)}`;
}
function hexJoinHash(hash64) {
jspb.utils.splitHash64(hash64);
return hexJoin(jspb.utils.split64Low, jspb.utils.split64High);
}
expect(decoder.readSplitZigzagVarint64(hexJoin))
.toEqual(hexJoinHash(hashA));
expect(decoder.readSplitZigzagVarint64(hexJoin))
.toEqual(hexJoinHash(hashB));
expect(decoder.readSplitZigzagVarint64(hexJoin))
.toEqual(hexJoinHash(hashC));
expect(decoder.readSplitZigzagVarint64(hexJoin))
.toEqual(hexJoinHash(hashD));
});
it('does zigzag encoding properly', function() {
// Test cases directly from the protobuf dev guide.
// https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
var testCases = [
{original: '0', zigzag: '0'},
{original: '-1', zigzag: '1'},
{original: '1', zigzag: '2'},
{original: '-2', zigzag: '3'},
{original: '2147483647', zigzag: '4294967294'},
{original: '-2147483648', zigzag: '4294967295'},
// 64-bit extremes, not in dev guide.
{original: '9223372036854775807', zigzag: '18446744073709551614'},
{original: '-9223372036854775808', zigzag: '18446744073709551615'},
// None of the above catch: bitsLow < 0 && bitsHigh > 0 && bitsHigh <
// 0x1FFFFF. The following used to be broken.
{original: '72000000000', zigzag: '144000000000'},
];
var 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);
testCases.forEach(function(c) {
expect(zigzagDecoder.readZigzagVarint64String()).toEqual(c.original);
expect(varintDecoder.readUnsignedVarint64String()).toEqual(c.zigzag);
});
});
});
/**
* Tests reading and writing large strings
*/
it('testLargeStrings', function() {
var encoder = new jspb.BinaryEncoder();
var len = 150000;
var long_string = '';
for (var i = 0; i < len; i++) {
long_string += 'a';
}
encoder.writeString(long_string);
var decoder = jspb.BinaryDecoder.alloc(encoder.end());
assertEquals(long_string, decoder.readString(len));
});
/**
* Test encoding and decoding utf-8.
*/
it('testUtf8', function() {
var 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 = "😁";
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());
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));
});
/**
* Verifies that misuse of the decoder class triggers assertions.
*/
it('testDecodeErrors', function() {
// 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()});
// Overlong varints should trigger assertions.
decoder.setBlock([255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0]);
assertThrows(function() {decoder.readUnsignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readSignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readZigzagVarint64()});
decoder.reset();
assertThrows(function() {decoder.readUnsignedVarint32()});
});
/**
* Tests encoding and decoding of unsigned integers.
*/
it('testUnsignedIntegers', function() {
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint8,
jspb.BinaryEncoder.prototype.writeUint8,
1, 0xFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint16,
jspb.BinaryEncoder.prototype.writeUint16,
1, 0xFFFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint32,
jspb.BinaryEncoder.prototype.writeUint32,
1, 0xFFFFFFFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint64,
jspb.BinaryEncoder.prototype.writeUint64,
1, Math.pow(2, 64) - 1025, Math.round);
});
/**
* Tests encoding and decoding of signed integers.
*/
it('testSignedIntegers', function() {
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt8,
jspb.BinaryEncoder.prototype.writeInt8,
1, -0x80, 0x7F, Math.round);
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt16,
jspb.BinaryEncoder.prototype.writeInt16,
1, -0x8000, 0x7FFF, Math.round);
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt32,
jspb.BinaryEncoder.prototype.writeInt32,
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);
});
/**
* Tests encoding and decoding of floats.
*/
it('testFloats', function() {
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var 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);
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; });
});
});

View File

@ -1,510 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview BinaryEncode defines methods for encoding Javascript values
* into arrays of bytes compatible with the Protocol Buffer wire format.
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.provide('jspb.BinaryEncoder');
goog.require('goog.asserts');
goog.require('jspb.BinaryConstants');
goog.require('jspb.utils');
/**
* BinaryEncoder implements encoders for all the wire types specified in
* https://developers.google.com/protocol-buffers/docs/encoding.
*
* @constructor
* @struct
*/
jspb.BinaryEncoder = function() {
/** @private {!Array<number>} */
this.buffer_ = [];
};
/**
* @return {number}
*/
jspb.BinaryEncoder.prototype.length = function() {
return this.buffer_.length;
};
/**
* @return {!Array<number>}
*/
jspb.BinaryEncoder.prototype.end = function() {
var buffer = this.buffer_;
this.buffer_ = [];
return buffer;
};
/**
* Encodes a 64-bit integer in 32:32 split representation into its wire-format
* varint representation and stores it in the buffer.
* @param {number} lowBits The low 32 bits of the int.
* @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));
// 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.
while (highBits > 0 || lowBits > 127) {
this.buffer_.push((lowBits & 0x7f) | 0x80);
lowBits = ((lowBits >>> 7) | (highBits << 25)) >>> 0;
highBits = highBits >>> 7;
}
this.buffer_.push(lowBits);
};
/**
* Encodes a 64-bit integer in 32:32 split representation into its wire-format
* fixed representation and stores it in the buffer.
* @param {number} lowBits The low 32 bits of the int.
* @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));
this.writeUint32(lowBits);
this.writeUint32(highBits);
};
/**
* Encodes a 32-bit unsigned integer into its wire-format varint representation
* and stores it in the buffer.
* @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));
while (value > 127) {
this.buffer_.push((value & 0x7f) | 0x80);
value = value >>> 7;
}
this.buffer_.push(value);
};
/**
* Encodes a 32-bit signed integer into its wire-format varint representation
* and stores it in the buffer.
* @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));
// Use the unsigned version if the value is not negative.
if (value >= 0) {
this.writeUnsignedVarint32(value);
return;
}
// Write nine bytes with a _signed_ right shift so we preserve the sign bit.
for (var i = 0; i < 9; i++) {
this.buffer_.push((value & 0x7f) | 0x80);
value = value >> 7;
}
// The above loop writes out 63 bits, so the last byte is always the sign bit
// which is always set for negative numbers.
this.buffer_.push(1);
};
/**
* Encodes a 64-bit unsigned integer into its wire-format varint representation
* and stores it in the buffer. Integers that are not representable in 64 bits
* will be truncated.
* @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.utils.splitInt64(value);
this.writeSplitVarint64(jspb.utils.split64Low,
jspb.utils.split64High);
};
/**
* Encodes a 64-bit signed integer into its wire-format varint representation
* and stores it in the buffer. Integers that are not representable in 64 bits
* will be truncated.
* @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.utils.splitInt64(value);
this.writeSplitVarint64(jspb.utils.split64Low,
jspb.utils.split64High);
};
/**
* Encodes a JavaScript integer into its wire-format, zigzag-encoded varint
* representation and stores it in the buffer.
* @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));
this.writeUnsignedVarint32(((value << 1) ^ (value >> 31)) >>> 0);
};
/**
* Encodes a JavaScript integer into its wire-format, zigzag-encoded varint
* representation and stores it in the buffer. Integers not representable in 64
* bits will be truncated.
* @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.utils.splitZigzag64(value);
this.writeSplitVarint64(jspb.utils.split64Low,
jspb.utils.split64High);
};
/**
* Encodes a JavaScript decimal string into its wire-format, zigzag-encoded
* varint representation and stores it in the buffer. Integers not representable
* in 64 bits will be truncated.
* @param {string} value The integer to convert.
*/
jspb.BinaryEncoder.prototype.writeZigzagVarint64String = function(value) {
this.writeZigzagVarintHash64(jspb.utils.decimalStringToHash64(value));
};
/**
* Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
* buffer as a zigzag varint.
* @param {string} hash The hash to write.
*/
jspb.BinaryEncoder.prototype.writeZigzagVarintHash64 = function(hash) {
var self = this;
jspb.utils.splitHash64(hash);
jspb.utils.toZigzag64(
jspb.utils.split64Low, jspb.utils.split64High, function(lo, hi) {
self.writeSplitVarint64(lo >>> 0, hi >>> 0);
});
};
/**
* Writes an 8-bit unsigned integer to the buffer. Numbers outside the range
* [0,2^8) will be truncated.
* @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));
this.buffer_.push((value >>> 0) & 0xFF);
};
/**
* Writes a 16-bit unsigned integer to the buffer. Numbers outside the
* range [0,2^16) will be truncated.
* @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));
this.buffer_.push((value >>> 0) & 0xFF);
this.buffer_.push((value >>> 8) & 0xFF);
};
/**
* Writes a 32-bit unsigned integer to the buffer. Numbers outside the
* range [0,2^32) will be truncated.
* @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));
this.buffer_.push((value >>> 0) & 0xFF);
this.buffer_.push((value >>> 8) & 0xFF);
this.buffer_.push((value >>> 16) & 0xFF);
this.buffer_.push((value >>> 24) & 0xFF);
};
/**
* Writes a 64-bit unsigned integer to the buffer. Numbers outside the
* range [0,2^64) will be truncated.
* @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.utils.splitUint64(value);
this.writeUint32(jspb.utils.split64Low);
this.writeUint32(jspb.utils.split64High);
};
/**
* Writes an 8-bit integer to the buffer. Numbers outside the range
* [-2^7,2^7) will be truncated.
* @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));
this.buffer_.push((value >>> 0) & 0xFF);
};
/**
* Writes a 16-bit integer to the buffer. Numbers outside the range
* [-2^15,2^15) will be truncated.
* @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));
this.buffer_.push((value >>> 0) & 0xFF);
this.buffer_.push((value >>> 8) & 0xFF);
};
/**
* Writes a 32-bit integer to the buffer. Numbers outside the range
* [-2^31,2^31) will be truncated.
* @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));
this.buffer_.push((value >>> 0) & 0xFF);
this.buffer_.push((value >>> 8) & 0xFF);
this.buffer_.push((value >>> 16) & 0xFF);
this.buffer_.push((value >>> 24) & 0xFF);
};
/**
* Writes a 64-bit integer to the buffer. Numbers outside the range
* [-2^63,2^63) will be truncated.
* @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.utils.splitInt64(value);
this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
};
/**
* Writes a 64-bit integer decimal strings to the buffer. Numbers outside the
* range [-2^63,2^63) will be truncated.
* @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.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
};
/**
* Writes a single-precision floating point value to the buffer. Numbers
* requiring more than 32 bits of precision will be truncated.
* @param {number} value The value to write.
*/
jspb.BinaryEncoder.prototype.writeFloat = function(value) {
goog.asserts.assert(
value === Infinity || value === -Infinity || isNaN(value) ||
((value >= -jspb.BinaryConstants.FLOAT32_MAX) &&
(value <= jspb.BinaryConstants.FLOAT32_MAX)));
jspb.utils.splitFloat32(value);
this.writeUint32(jspb.utils.split64Low);
};
/**
* Writes a double-precision floating point value to the buffer. As this is
* the native format used by JavaScript, no precision will be lost.
* @param {number} value The value to write.
*/
jspb.BinaryEncoder.prototype.writeDouble = function(value) {
goog.asserts.assert(
value === Infinity || value === -Infinity || isNaN(value) ||
((value >= -jspb.BinaryConstants.FLOAT64_MAX) &&
(value <= jspb.BinaryConstants.FLOAT64_MAX)));
jspb.utils.splitFloat64(value);
this.writeUint32(jspb.utils.split64Low);
this.writeUint32(jspb.utils.split64High);
};
/**
* Writes a boolean value to the buffer as a varint. We allow numbers as input
* because the JSPB code generator uses 0/1 instead of true/false to save space
* in the string representation of the proto.
* @param {boolean|number} value The value to write.
*/
jspb.BinaryEncoder.prototype.writeBool = function(value) {
goog.asserts.assert(typeof value === 'boolean' || typeof value === 'number');
this.buffer_.push(value ? 1 : 0);
};
/**
* Writes an enum value to the buffer as a varint.
* @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));
this.writeSignedVarint32(value);
};
/**
* Writes an arbitrary byte array to the buffer.
* @param {!Uint8Array} bytes The array of bytes to write.
*/
jspb.BinaryEncoder.prototype.writeBytes = function(bytes) {
this.buffer_.push.apply(this.buffer_, bytes);
};
/**
* Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
* buffer as a varint.
* @param {string} hash The hash to write.
*/
jspb.BinaryEncoder.prototype.writeVarintHash64 = function(hash) {
jspb.utils.splitHash64(hash);
this.writeSplitVarint64(jspb.utils.split64Low,
jspb.utils.split64High);
};
/**
* Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
* buffer as a fixed64.
* @param {string} hash The hash to write.
*/
jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) {
jspb.utils.splitHash64(hash);
this.writeUint32(jspb.utils.split64Low);
this.writeUint32(jspb.utils.split64High);
};
/**
* Writes a UTF16 Javascript string to the buffer encoded as UTF8.
* TODO(aappleby): Add support for surrogate pairs, reject unpaired surrogates.
* @param {string} value The string to write.
* @return {number} The number of bytes used to encode the string.
*/
jspb.BinaryEncoder.prototype.writeString = function(value) {
var oldLength = this.buffer_.length;
for (var i = 0; i < value.length; i++) {
var c = value.charCodeAt(i);
if (c < 128) {
this.buffer_.push(c);
} else if (c < 2048) {
this.buffer_.push((c >> 6) | 192);
this.buffer_.push((c & 63) | 128);
} else if (c < 65536) {
// 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
// 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 >> 6) & 63) | 128);
this.buffer_.push((c & 63) | 128);
i++;
}
}
else {
this.buffer_.push((c >> 12) | 224);
this.buffer_.push(((c >> 6) & 63) | 128);
this.buffer_.push((c & 63) | 128);
}
}
}
var length = this.buffer_.length - oldLength;
return length;
};

View File

@ -1,60 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test suite is written using Jasmine -- see http://jasmine.github.io/
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() {
// 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();
nested.setCount(5);
msg.setDeeplyNestedMessage(nested);
assertEquals(5, msg.getDeeplyNestedMessage().getCount());
// After a serialization-deserialization round trip we should get back the
// same data we started with.
var serialized = msg.serializeBinary();
var deserialized =
proto.jspb.test.ForeignNestedFieldMessage.deserializeBinary(serialized);
assertEquals(5, deserialized.getDeeplyNestedMessage().getCount());
});
});

View File

@ -1,665 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// 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');
// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test
goog.require('proto.jspb.test.ExtendsWithMessage');
goog.require('proto.jspb.test.ForeignEnum');
goog.require('proto.jspb.test.ForeignMessage');
goog.require('proto.jspb.test.TestAllTypes');
goog.require('proto.jspb.test.TestExtendable');
goog.require('proto.jspb.test.extendOptionalBool');
goog.require('proto.jspb.test.extendOptionalBytes');
goog.require('proto.jspb.test.extendOptionalDouble');
goog.require('proto.jspb.test.extendOptionalFixed32');
goog.require('proto.jspb.test.extendOptionalFixed64');
goog.require('proto.jspb.test.extendOptionalFloat');
goog.require('proto.jspb.test.extendOptionalForeignEnum');
goog.require('proto.jspb.test.extendOptionalInt32');
goog.require('proto.jspb.test.extendOptionalInt64');
goog.require('proto.jspb.test.extendOptionalSfixed32');
goog.require('proto.jspb.test.extendOptionalSfixed64');
goog.require('proto.jspb.test.extendOptionalSint32');
goog.require('proto.jspb.test.extendOptionalSint64');
goog.require('proto.jspb.test.extendOptionalString');
goog.require('proto.jspb.test.extendOptionalUint32');
goog.require('proto.jspb.test.extendOptionalUint64');
goog.require('proto.jspb.test.extendPackedRepeatedBoolList');
goog.require('proto.jspb.test.extendPackedRepeatedDoubleList');
goog.require('proto.jspb.test.extendPackedRepeatedFixed32List');
goog.require('proto.jspb.test.extendPackedRepeatedFixed64List');
goog.require('proto.jspb.test.extendPackedRepeatedFloatList');
goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList');
goog.require('proto.jspb.test.extendPackedRepeatedInt32List');
goog.require('proto.jspb.test.extendPackedRepeatedInt64List');
goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List');
goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List');
goog.require('proto.jspb.test.extendPackedRepeatedSint32List');
goog.require('proto.jspb.test.extendPackedRepeatedSint64List');
goog.require('proto.jspb.test.extendPackedRepeatedUint32List');
goog.require('proto.jspb.test.extendPackedRepeatedUint64List');
goog.require('proto.jspb.test.extendRepeatedBoolList');
goog.require('proto.jspb.test.extendRepeatedBytesList');
goog.require('proto.jspb.test.extendRepeatedDoubleList');
goog.require('proto.jspb.test.extendRepeatedFixed32List');
goog.require('proto.jspb.test.extendRepeatedFixed64List');
goog.require('proto.jspb.test.extendRepeatedFloatList');
goog.require('proto.jspb.test.extendRepeatedForeignEnumList');
goog.require('proto.jspb.test.extendRepeatedInt32List');
goog.require('proto.jspb.test.extendRepeatedInt64List');
goog.require('proto.jspb.test.extendRepeatedSfixed32List');
goog.require('proto.jspb.test.extendRepeatedSfixed64List');
goog.require('proto.jspb.test.extendRepeatedSint32List');
goog.require('proto.jspb.test.extendRepeatedSint64List');
goog.require('proto.jspb.test.extendRepeatedStringList');
goog.require('proto.jspb.test.extendRepeatedUint32List');
goog.require('proto.jspb.test.extendRepeatedUint64List');
// CommonJS-LoadFromFile: ../node_modules/google-protobuf/google/protobuf/any_pb proto.google.protobuf
goog.require('proto.google.protobuf.Any');
var suite = {};
var BYTES = new Uint8Array([1, 2, 8, 9]);
var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
/**
* Helper: fill all fields on a TestAllTypes message.
* @param {proto.jspb.test.TestAllTypes} msg
*/
function fillAllFields(msg) {
msg.setOptionalInt32(-42);
// can be exactly represented by JS number (64-bit double, i.e., 52-bit
// mantissa).
msg.setOptionalInt64(-0x7fffffff00000000);
msg.setOptionalUint32(0x80000000);
msg.setOptionalUint64(0xf000000000000000);
msg.setOptionalSint32(-100);
msg.setOptionalSint64(-0x8000000000000000);
msg.setOptionalFixed32(1234);
msg.setOptionalFixed64(0x1234567800000000);
msg.setOptionalSfixed32(-1234);
msg.setOptionalSfixed64(-0x1234567800000000);
msg.setOptionalFloat(1.5);
msg.setOptionalDouble(-1.5);
msg.setOptionalBool(true);
msg.setOptionalString('hello world');
msg.setOptionalBytes(BYTES);
msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup());
msg.getOptionalGroup().setA(100);
var submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(16);
msg.setOptionalForeignMessage(submsg);
msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO);
msg.setOneofString('oneof');
msg.setRepeatedInt32List([-42]);
msg.setRepeatedInt64List([-0x7fffffff00000000]);
msg.setRepeatedUint32List([0x80000000]);
msg.setRepeatedUint64List([0xf000000000000000]);
msg.setRepeatedSint32List([-100]);
msg.setRepeatedSint64List([-0x8000000000000000]);
msg.setRepeatedFixed32List([1234]);
msg.setRepeatedFixed64List([0x1234567800000000]);
msg.setRepeatedSfixed32List([-1234]);
msg.setRepeatedSfixed64List([-0x1234567800000000]);
msg.setRepeatedFloatList([1.5]);
msg.setRepeatedDoubleList([-1.5]);
msg.setRepeatedBoolList([true]);
msg.setRepeatedStringList(['hello world']);
msg.setRepeatedBytesList([BYTES, BYTES]);
msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]);
msg.getRepeatedGroupList()[0].setA(100);
submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(1000);
msg.setRepeatedForeignMessageList([submsg]);
msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
msg.setPackedRepeatedInt32List([-42]);
msg.setPackedRepeatedInt64List([-0x7fffffff00000000]);
msg.setPackedRepeatedUint32List([0x80000000]);
msg.setPackedRepeatedUint64List([0xf000000000000000]);
msg.setPackedRepeatedSint32List([-100]);
msg.setPackedRepeatedSint64List([-0x8000000000000000]);
msg.setPackedRepeatedFixed32List([1234]);
msg.setPackedRepeatedFixed64List([0x1234567800000000]);
msg.setPackedRepeatedSfixed32List([-1234]);
msg.setPackedRepeatedSfixed64List([-0x1234567800000000]);
msg.setPackedRepeatedFloatList([1.5]);
msg.setPackedRepeatedDoubleList([-1.5]);
msg.setPackedRepeatedBoolList([true]);
}
/**
* Helper: compare a bytes field to an expected value
* @param {Uint8Array|string} arr
* @param {Uint8Array} expected
* @return {boolean}
*/
function bytesCompare(arr, expected) {
if (typeof arr === 'string') {
arr = goog.crypt.base64.decodeStringToUint8Array(arr);
}
if (arr.length != expected.length) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] != expected[i]) {
return false;
}
}
return true;
}
/**
* Helper: verify contents of given TestAllTypes message as set by
* fillAllFields().
* @param {proto.jspb.test.TestAllTypes} original
* @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]);
// Check last so we get more granular errors first.
assertTrue(jspb.Message.equals(original, copy));
}
/**
* Helper: verify that all expected extensions are present.
* @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,
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,
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]);
}
describe('protoBinaryTest', function() {
/**
* 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();
fillAllFields(msg);
var encoded = msg.serializeBinary();
var 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();
// 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));
// 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));
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));
});
/**
* Test that bytes setters will receive result of any of the getters.
*/
it('testBytesFieldsSettersInterop', function() {
var msg = new proto.jspb.test.TestAllTypes();
msg.setOptionalBytes(BYTES);
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes_asB64());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes_asU8());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
});
/**
* Test that bytes setters will receive result of any of the getters.
*/
it('testRepeatedBytesGetters', function() {
var 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));
}
msg.setRepeatedBytesList([BYTES, BYTES]);
assertGetters();
msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
assertGetters();
msg.setRepeatedBytesList([]);
assertEquals(0, msg.getRepeatedBytesList().length);
assertEquals(0, msg.getRepeatedBytesList_asB64().length);
assertEquals(0, msg.getRepeatedBytesList_asU8().length);
});
/**
* Helper: fill all extension values.
* @param {proto.jspb.test.TestExtendable} msg
*/
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.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.extendOptionalBytes, BYTES);
var submsg = new proto.jspb.test.ExtendsWithMessage();
submsg.setFoo(16);
msg.setExtension(
proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg);
msg.setExtension(
proto.jspb.test.extendOptionalForeignEnum,
proto.jspb.test.ForeignEnum.FOREIGN_FOO);
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.extendRepeatedUint64List, [0xf000000000000000]);
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.extendRepeatedFixed64List, [0x1234567800000000]);
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.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,
[proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
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.extendPackedRepeatedSint64List, [-0x8000000000000000]);
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.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.extendPackedRepeatedForeignEnumList,
[proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
}
/**
* Tests extension serialization and deserialization.
*/
it('testExtensions', function() {
var msg = new proto.jspb.test.TestExtendable();
fillExtensions(msg);
var encoded = msg.serializeBinary();
var 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();
fillExtensions(msg);
var 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);
checkExtensions(decoded);
});
it('testAnyWellKnownType', function() {
var any = new proto.google.protobuf.Any();
var msg = new proto.jspb.test.TestAllTypes();
fillAllFields(msg);
any.pack(msg.serializeBinary(), 'jspb.test.TestAllTypes');
assertEquals('type.googleapis.com/jspb.test.TestAllTypes',
any.getTypeUrl());
var msg2 = any.unpack(
proto.jspb.test.TestAllTypes.deserializeBinary,
'jspb.test.TestAllTypes');
checkAllFields(msg, msg2);
});
});

File diff suppressed because it is too large Load Diff

View File

@ -1,992 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer reader.
*
* There are two particular magic numbers that need to be pointed out -
* 2^64-1025 is the largest number representable as both a double and an
* unsigned 64-bit integer, and 2^63-513 is the largest number representable as
* both a double and a signed 64-bit integer.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @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() {
/**
* Tests the reader instance cache.
*/
it('testInstanceCaches', /** @suppress {visibility} */ function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
writer.writeMessage(1, dummyMessage, () => {});
writer.writeMessage(2, dummyMessage, () => {});
var buffer = writer.getResultBuffer();
// Empty the instance caches.
jspb.BinaryReader.instanceCache_ = [];
// 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();
decoder1.free();
decoder2.free();
decoder3.free();
assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// 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);
// Allocating a reader should remove a reader from the cache.
var reader = jspb.BinaryReader.alloc(buffer);
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// Processing the message reuses the current reader.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
});
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
});
assertEquals(false, reader.nextField());
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// Freeing the reader should put it back into the cache.
reader.free();
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(1, jspb.BinaryReader.instanceCache_.length);
});
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var temp = new Float32Array(1);
temp[0] = x;
return temp[0];
}
/**
* 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() {
reader.nextField();
assertThrows(function() {
reader.readFixed32()
});
});
// Skipping an invalid field should trigger an assertion.
reader = jspb.BinaryReader.alloc([12, 1]);
reader.nextWireType_ = 1000;
assertThrows(function() {
reader.skipField()
});
// 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()
});
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()
});
assertThrows(function() {
reader.readString()
});
assertThrows(function() {
reader.readBytes()
});
});
/**
* Tests encoding and decoding of unsigned field types.
* @param {Function} readField
* @param {Function} writeField
* @param {number} epsilon
* @param {number} upperLimit
* @param {Function} filter
* @private
* @suppress {missingProperties}
*/
var doTestUnsignedField_ = function(
readField, writeField, epsilon, upperLimit, filter) {
assertNotNull(readField);
assertNotNull(writeField);
var writer = new jspb.BinaryWriter();
// Encode zero and limits.
writeField.call(writer, 1, filter(0));
writeField.call(writer, 2, filter(epsilon));
writeField.call(writer, 3, filter(upperLimit));
// Encode positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
writeField.call(writer, 4, filter(cursor));
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Check zero and limits.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(filter(0), readField.call(reader));
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(filter(epsilon), readField.call(reader));
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(filter(upperLimit), readField.call(reader));
// Check positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
reader.nextField();
if (4 != reader.getFieldNumber()) throw 'fail!';
if (filter(cursor) != readField.call(reader)) throw 'fail!';
}
};
/**
* Tests encoding and decoding of signed field types.
* @param {Function} readField
* @param {Function} writeField
* @param {number} epsilon
* @param {number} lowerLimit
* @param {number} upperLimit
* @param {Function} filter
* @private
* @suppress {missingProperties}
*/
var doTestSignedField_ = function(
readField, writeField, epsilon, lowerLimit, upperLimit, filter) {
var writer = new jspb.BinaryWriter();
// Encode zero and limits.
writeField.call(writer, 1, filter(lowerLimit));
writeField.call(writer, 2, filter(-epsilon));
writeField.call(writer, 3, filter(0));
writeField.call(writer, 4, filter(epsilon));
writeField.call(writer, 5, filter(upperLimit));
var inputValues = [];
// Encode negative values.
for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
var 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);
writeField.call(writer, 7, val);
inputValues.push({fieldNumber: 7, value: val});
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Check zero and limits.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(filter(lowerLimit), readField.call(reader));
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(filter(-epsilon), readField.call(reader));
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(filter(0), readField.call(reader));
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(filter(epsilon), readField.call(reader));
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(filter(upperLimit), readField.call(reader));
for (var i = 0; i < inputValues.length; i++) {
var expected = inputValues[i];
reader.nextField();
assertEquals(expected.fieldNumber, reader.getFieldNumber());
assertEquals(expected.value, readField.call(reader));
}
};
/**
* 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);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readUint32,
jspb.BinaryWriter.prototype.writeUint32, 1, Math.pow(2, 32) - 1,
Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readUint64,
jspb.BinaryWriter.prototype.writeUint64, 1, Math.pow(2, 64) - 1025,
Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readInt32,
jspb.BinaryWriter.prototype.writeInt32, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readInt64,
jspb.BinaryWriter.prototype.writeInt64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readEnum,
jspb.BinaryWriter.prototype.writeEnum, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readBool,
jspb.BinaryWriter.prototype.writeBool, 1, 1, function(x) {
return !!x;
});
});
/**
* Tests reading a field from hexadecimal string (format: '08 BE EF').
* @param {Function} readField
* @param {number} expected
* @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++) {
bytes[i] = parseInt(hexString.substring(i * 3, i * 3 + 2), 16);
}
var reader = jspb.BinaryReader.alloc(bytes);
reader.nextField();
assertEquals(expected, readField.call(reader));
}
/**
* 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);
// uint32 and sint32 take no more than 5 bytes
// 08 - field prefix (type = 0 means varint)
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readUint32, 12, '08 8C 80 80 80 00');
// 11 stands for -6 in zigzag encoding
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readSint32, -6, '08 8B 80 80 80 00');
// uint64 and sint64 take no more than 10 bytes
// 08 - field prefix (type = 0 means varint)
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readUint64, 12,
'08 8C 80 80 80 80 80 80 80 80 00');
// 11 stands for -6 in zigzag encoding
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readSint64, -6,
'08 8B 80 80 80 80 80 80 80 80 00');
});
/**
* Tests reading 64-bit integers as split values.
*/
it('handles split 64 fields', function() {
var 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());
function rejoin(lowBits, highBits) {
return highBits * 2 ** 32 + (lowBits >>> 0);
}
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
expect(reader.readSplitVarint64(rejoin)).toEqual(0x100000000);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(2);
expect(reader.readSplitFixed64(rejoin)).toEqual(0x100000002);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(3);
expect(reader.readSplitZigzagVarint64(rejoin)).toEqual(-2);
});
/**
* Tests 64-bit fields that are handled as strings.
*/
it('testStringInt64Fields', function() {
var writer = new jspb.BinaryWriter();
var testSignedData = [
'2730538252207801776', '-2688470994844604560', '3398529779486536359',
'3568577411627971000', '272477188847484900', '-6649058714086158188',
'-7695254765712060806', '-4525541438037104029', '-4993706538836508568',
'4990160321893729138'
];
var testUnsignedData = [
'7822732630241694882', '6753602971916687352', '2399935075244442116',
'8724292567325338867', '16948784802625696584', '4136275908516066934',
'3575388346793700364', '5167142028379259461', '1557573948689737699',
'17100725280812548567'
];
for (var 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());
for (var i = 0; i < testSignedData.length; i++) {
reader.nextField();
assertEquals(2 * i + 1, reader.getFieldNumber());
assertEquals(testSignedData[i], reader.readInt64String());
reader.nextField();
assertEquals(2 * i + 2, reader.getFieldNumber());
assertEquals(testUnsignedData[i], reader.readUint64String());
}
});
/**
* Tests fields that use zigzag encoding.
*/
it('testZigzagFields', function() {
doTestSignedField_(
jspb.BinaryReader.prototype.readSint32,
jspb.BinaryWriter.prototype.writeSint32, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSint64,
jspb.BinaryWriter.prototype.writeSint64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSintHash64,
jspb.BinaryWriter.prototype.writeSintHash64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, jspb.utils.numberToHash64);
});
/**
* Tests fields that use fixed-length encoding.
*/
it('testFixedFields', function() {
doTestUnsignedField_(
jspb.BinaryReader.prototype.readFixed32,
jspb.BinaryWriter.prototype.writeFixed32, 1, Math.pow(2, 32) - 1,
Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readFixed64,
jspb.BinaryWriter.prototype.writeFixed64, 1, Math.pow(2, 64) - 1025,
Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSfixed32,
jspb.BinaryWriter.prototype.writeSfixed32, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSfixed64,
jspb.BinaryWriter.prototype.writeSfixed64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, Math.round);
});
/**
* Tests floating point fields.
*/
it('testFloatFields', function() {
doTestSignedField_(
jspb.BinaryReader.prototype.readFloat,
jspb.BinaryWriter.prototype.writeFloat,
jspb.BinaryConstants.FLOAT32_MIN, -jspb.BinaryConstants.FLOAT32_MAX,
jspb.BinaryConstants.FLOAT32_MAX, truncate);
doTestSignedField_(
jspb.BinaryReader.prototype.readDouble,
jspb.BinaryWriter.prototype.writeDouble,
jspb.BinaryConstants.FLOAT64_EPS * 10,
-jspb.BinaryConstants.FLOAT64_MIN, jspb.BinaryConstants.FLOAT64_MIN,
function(x) {
return x;
});
});
/**
* Tests length-delimited string fields.
*/
it('testStringFields', function() {
var s1 = 'The quick brown fox jumps over the lazy dog.';
var s2 = '人人生而自由,在尊嚴和權利上一律平等。';
var writer = new jspb.BinaryWriter();
writer.writeString(1, s1);
writer.writeString(2, s2);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(s1, reader.readString());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(s2, reader.readString());
});
/**
* Tests length-delimited byte fields.
*/
it('testByteFields', function() {
var message = [];
var lowerLimit = 1;
var upperLimit = 256;
var scale = 1.1;
var 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);
writer.writeBytes(len, bytes);
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
for (var cursor = lowerLimit; reader.nextField(); cursor *= 1.1) {
var len = Math.round(cursor);
if (len != reader.getFieldNumber()) throw 'fail!';
var bytes = reader.readBytes();
if (len != bytes.length) throw 'fail!';
for (var i = 0; i < bytes.length; i++) {
if (i % 256 != bytes[i]) throw 'fail!';
}
}
});
/**
* Tests nested messages.
*/
it('testNesting', function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
writer.writeInt32(1, 100);
// Add one message with 3 int fields.
writer.writeMessage(2, dummyMessage, function() {
writer.writeInt32(3, 300);
writer.writeInt32(4, 400);
writer.writeInt32(5, 500);
});
// Add one empty message.
writer.writeMessage(6, dummyMessage, () => {});
writer.writeInt32(7, 700);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Validate outermost message.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(100, reader.readInt32());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Validate embedded message 1.
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(300, reader.readInt32());
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(400, reader.readInt32());
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(500, reader.readInt32());
assertEquals(false, reader.nextField());
});
reader.nextField();
assertEquals(6, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Validate embedded message 2.
assertEquals(false, reader.nextField());
});
reader.nextField();
assertEquals(7, reader.getFieldNumber());
assertEquals(700, reader.readInt32());
assertEquals(false, reader.nextField());
});
/**
* 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();
var sentinel = 123456789;
// Write varint fields of different sizes.
writer.writeInt32(1, sentinel);
writer.writeInt32(1, 1);
writer.writeInt32(1, 1000);
writer.writeInt32(1, 1000000);
writer.writeInt32(1, 1000000000);
// Write fixed 64-bit encoded fields.
writer.writeInt32(2, sentinel);
writer.writeDouble(2, 1);
writer.writeFixed64(2, 1);
writer.writeSfixed64(2, 1);
// Write fixed 32-bit encoded fields.
writer.writeInt32(3, sentinel);
writer.writeFloat(3, 1);
writer.writeFixed32(3, 1);
writer.writeSfixed32(3, 1);
// Write delimited fields.
writer.writeInt32(4, sentinel);
writer.writeBytes(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
writer.writeString(4, 'The quick brown fox jumps over the lazy dog');
// Write a group with a nested group inside.
writer.writeInt32(5, sentinel);
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
writer.writeGroup(5, dummyMessage, function() {
// 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.
// The reason is 44 = 5 * 8 + 4, this will be translated in to a field
// with number 5 and with type 4 (end group)
writer.writeInt64(44, 44);
// This will make previous implementation failed by invalid tag (7).
writer.writeInt64(42, 47);
writer.writeInt64(42, 42);
// This is for making the previous implementation failed by an invalid
// 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.writeInt64(84, 42);
writer.writeInt64(84, 44);
writer.writeBytes(
43, [255, 255, 255, 255, 255, 255, 255, 255, 255, 255]);
});
});
// Write final sentinel.
writer.writeInt32(6, sentinel);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
function skip(field, count) {
for (var i = 0; i < count; i++) {
reader.nextField();
if (field != reader.getFieldNumber()) throw 'fail!';
reader.skipField();
}
}
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(1, 4);
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(2, 3);
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(3, 3);
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(4, 2);
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(5, 1);
reader.nextField();
assertEquals(6, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
});
/**
* Tests packed fields.
*/
it('testPackedFields', function() {
var writer = new jspb.BinaryWriter();
var 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];
for (var i = 0; i < floatData.length; i++) {
floatData[i] = truncate(floatData[i]);
}
writer.writeInt32(1, sentinel);
writer.writePackedInt32(2, signedData);
writer.writePackedInt64(2, signedData);
writer.writePackedUint32(2, unsignedData);
writer.writePackedUint64(2, unsignedData);
writer.writePackedSint32(2, signedData);
writer.writePackedSint64(2, signedData);
writer.writePackedFixed32(2, unsignedData);
writer.writePackedFixed64(2, unsignedData);
writer.writePackedSfixed32(2, signedData);
writer.writePackedSfixed64(2, signedData);
writer.writePackedFloat(2, floatData);
writer.writePackedDouble(2, doubleData);
writer.writePackedBool(2, boolData);
writer.writePackedEnum(2, unsignedData);
writer.writeInt32(3, sentinel);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
assertEquals(sentinel, reader.readInt32());
reader.nextField();
assertElementsEquals(reader.readPackedInt32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedInt64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedUint32(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedUint64(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedSint32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedSint64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedFixed32(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedFixed64(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedSfixed32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedSfixed64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedFloat(), floatData);
reader.nextField();
assertElementsEquals(reader.readPackedDouble(), doubleData);
reader.nextField();
assertElementsEquals(reader.readPackedBool(), boolData);
reader.nextField();
assertElementsEquals(reader.readPackedEnum(), unsignedData);
reader.nextField();
assertEquals(sentinel, reader.readInt32());
});
/**
* Byte blobs inside nested messages should always have their byte offset set
* relative to the start of the outermost blob, not the start of their parent
* blob.
*/
it('testNestedBlobs', function() {
// 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} */ ({});
writer.writeMessage(1, dummyMessage, function() {
writer.writeMessage(1, dummyMessage, function() {
writer.writeBytes(1, blob);
});
});
// Peel off the outer two message layers. Each layer should have two bytes
// 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());
var decoder2 = new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4));
assertEquals(fieldTag, decoder2.readUnsignedVarint32());
assertEquals(blob.length + 2, decoder2.readUnsignedVarint32());
assertEquals(fieldTag, decoder2.readUnsignedVarint32());
assertEquals(blob.length, decoder2.readUnsignedVarint32());
var bytes = decoder2.readBytes(blob.length);
assertElementsEquals(bytes, blob);
});
/**
* Tests read callbacks.
*/
it('testReadCallbacks', function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
// Add an int, a submessage, and another int.
writer.writeInt32(1, 100);
writer.writeMessage(2, dummyMessage, function() {
writer.writeInt32(3, 300);
writer.writeInt32(4, 400);
writer.writeInt32(5, 500);
});
writer.writeInt32(7, 700);
// Create the reader and register a custom read callback.
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
/**
* @param {!jspb.BinaryReader} reader
* @return {*}
*/
function readCallback(reader) {
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(300, reader.readInt32());
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(400, reader.readInt32());
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(500, reader.readInt32());
assertEquals(false, reader.nextField());
};
reader.registerReadCallback('readCallback', readCallback);
// Read the container message.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(100, reader.readInt32());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Decode the embedded message using the registered callback.
reader.runReadCallback('readCallback');
});
reader.nextField();
assertEquals(7, reader.getFieldNumber());
assertEquals(700, reader.readInt32());
assertEquals(false, reader.nextField());
});
});

File diff suppressed because it is too large Load Diff

View File

@ -1,744 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's helper functions.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.crypt');
goog.require('goog.crypt.base64');
goog.require('jspb.BinaryConstants');
goog.require('jspb.BinaryWriter');
goog.require('jspb.utils');
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var temp = new Float32Array(1);
temp[0] = x;
return temp[0];
}
/**
* Converts an 64-bit integer in split representation to a 64-bit hash string
* (8 bits encoded per character).
* @param {number} bitsLow The low 32 bits of the split 64-bit integer.
* @param {number} bitsHigh The high 32 bits of the split 64-bit integer.
* @return {string} The encoded hash string, 8 bits per character.
*/
function toHashString(bitsLow, bitsHigh) {
return String.fromCharCode((bitsLow >>> 0) & 0xFF,
(bitsLow >>> 8) & 0xFF,
(bitsLow >>> 16) & 0xFF,
(bitsLow >>> 24) & 0xFF,
(bitsHigh >>> 0) & 0xFF,
(bitsHigh >>> 8) & 0xFF,
(bitsHigh >>> 16) & 0xFF,
(bitsHigh >>> 24) & 0xFF);
}
describe('binaryUtilsTest', function() {
/**
* Tests lossless binary-to-decimal conversion.
*/
it('testDecimalConversion', function() {
// Check some magic numbers.
var result =
jspb.utils.joinUnsignedDecimalString(0x89e80001, 0x8ac72304);
expect(result).toEqual('10000000000000000001');
result = jspb.utils.joinUnsignedDecimalString(0xacd05f15, 0x1b69b4b);
expect(result).toEqual('123456789123456789');
result = jspb.utils.joinUnsignedDecimalString(0xeb1f0ad2, 0xab54a98c);
expect(result).toEqual('12345678901234567890');
result = jspb.utils.joinUnsignedDecimalString(0xe3b70cb1, 0x891087b8);
expect(result).toEqual('9876543210987654321');
// Check limits.
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00000000);
expect(result).toEqual('0');
result = jspb.utils.joinUnsignedDecimalString(0xFFFFFFFF, 0xFFFFFFFF);
expect(result).toEqual('18446744073709551615');
// Check each bit of the low dword.
for (var i = 0; i < 32; i++) {
var low = (1 << i) >>> 0;
result = jspb.utils.joinUnsignedDecimalString(low, 0);
expect(result).toEqual('' + Math.pow(2, i));
}
// Check the first 20 bits of the high dword.
for (var i = 0; i < 20; i++) {
var high = (1 << i) >>> 0;
result = jspb.utils.joinUnsignedDecimalString(0, high);
expect(result).toEqual('' + Math.pow(2, 32 + i));
}
// V8's internal double-to-string conversion is inaccurate for values above
// 2^52, even if they're representable integers - check the rest of the bits
// manually against the correct string representations of 2^N.
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00100000);
expect(result).toEqual('4503599627370496');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00200000);
expect(result).toEqual('9007199254740992');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00400000);
expect(result).toEqual('18014398509481984');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00800000);
expect(result).toEqual('36028797018963968');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x01000000);
expect(result).toEqual('72057594037927936');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x02000000);
expect(result).toEqual('144115188075855872');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x04000000);
expect(result).toEqual('288230376151711744');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x08000000);
expect(result).toEqual('576460752303423488');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x10000000);
expect(result).toEqual('1152921504606846976');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x20000000);
expect(result).toEqual('2305843009213693952');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x40000000);
expect(result).toEqual('4611686018427387904');
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x80000000);
expect(result).toEqual('9223372036854775808');
});
/**
* Going from hash strings to decimal strings should also be lossless.
*/
it('testHashToDecimalConversion', function() {
var result;
var convert = jspb.utils.hash64ToDecimalString;
result = convert(toHashString(0x00000000, 0x00000000), false);
expect(result).toEqual('0');
result = convert(toHashString(0x00000000, 0x00000000), true);
expect(result).toEqual('0');
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), false);
expect(result).toEqual('18446744073709551615');
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), true);
expect(result).toEqual('-1');
result = convert(toHashString(0x00000000, 0x80000000), false);
expect(result).toEqual('9223372036854775808');
result = convert(toHashString(0x00000000, 0x80000000), true);
expect(result).toEqual('-9223372036854775808');
result = convert(toHashString(0xacd05f15, 0x01b69b4b), false);
expect(result).toEqual('123456789123456789');
result = convert(toHashString(~0xacd05f15 + 1, ~0x01b69b4b), true);
expect(result).toEqual('-123456789123456789');
// And converting arrays of hashes should work the same way.
result = jspb.utils.hash64ArrayToDecimalStrings([
toHashString(0xFFFFFFFF, 0xFFFFFFFF),
toHashString(0x00000000, 0x80000000),
toHashString(0xacd05f15, 0x01b69b4b)], false);
expect(result.length).toEqual(3);
expect(result[0]).toEqual('18446744073709551615');
expect(result[1]).toEqual('9223372036854775808');
expect(result[2]).toEqual('123456789123456789');
});
/*
* Going from decimal strings to hash strings should be lossless.
*/
it('testDecimalToHashConversion', function() {
var result;
var convert = jspb.utils.decimalStringToHash64;
result = convert('0');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
result = convert('-1');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]));
result = convert('18446744073709551615');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]));
result = convert('9223372036854775808');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]));
result = convert('-9223372036854775808');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]));
result = convert('123456789123456789');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]));
result = convert('-123456789123456789');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]));
});
/**
* Going from hash strings to hex strings should be lossless.
*/
it('testHashToHexConversion', function() {
var result;
var convert = jspb.utils.hash64ToHexString;
result = convert(toHashString(0x00000000, 0x00000000));
expect(result).toEqual('0x0000000000000000');
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF));
expect(result).toEqual('0xffffffffffffffff');
result = convert(toHashString(0x12345678, 0x9ABCDEF0));
expect(result).toEqual('0x9abcdef012345678');
});
/**
* Going from hex strings to hash strings should be lossless.
*/
it('testHexToHashConversion', function() {
var result;
var convert = jspb.utils.hexStringToHash64;
result = convert('0x0000000000000000');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
result = convert('0xffffffffffffffff');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]));
// Hex string is big-endian, hash string is little-endian.
result = convert('0x123456789ABCDEF0');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]));
// Capitalization should not matter.
result = convert('0x0000abcdefABCDEF');
expect(result).toEqual(goog.crypt.byteArrayToString(
[0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]));
});
/**
* Going from numbers to hash strings should be lossless for up to 53 bits of
* precision.
*/
it('testNumberToHashConversion', function() {
var result;
var convert = jspb.utils.numberToHash64;
result = convert(0x0000000000000);
expect(jspb.utils.hash64ToHexString(result)).toEqual('0x0000000000000000');
result = convert(0xFFFFFFFFFFFFF);
expect(jspb.utils.hash64ToHexString(result)).toEqual('0x000fffffffffffff');
result = convert(0x123456789ABCD);
expect(jspb.utils.hash64ToHexString(result)).toEqual('0x000123456789abcd');
result = convert(0xDCBA987654321);
expect(jspb.utils.hash64ToHexString(result)).toEqual('0x000dcba987654321');
// 53 bits of precision should not be truncated.
result = convert(0x10000000000001);
expect(jspb.utils.hash64ToHexString(result)).toEqual('0x0010000000000001');
// 54 bits of precision should be truncated.
result = convert(0x20000000000001);
expect(jspb.utils.hash64ToHexString(result))
.not.toEqual('0x0020000000000001');
});
/**
* Sanity check the behavior of Javascript's strings when doing funny things
* with unicode characters.
*/
it('sanityCheckUnicodeStrings', function() {
var strings = new Array(65536);
// All possible unsigned 16-bit values should be storable in a string, they
// shouldn't do weird things with the length of the string, and they should
// come back out of the string unchanged.
for (var i = 0; i < 65536; i++) {
strings[i] = 'a' + String.fromCharCode(i) + 'a';
expect(strings[i].length).toEqual(3);
expect(strings[i].charCodeAt(1)).toEqual(i);
}
// Each unicode character should compare equal to itself and not equal to a
// different unicode character.
for (var i = 0; i < 65536; i++) {
expect(strings[i] == strings[i]).toEqual(true);
expect(strings[i] == strings[(i + 1) % 65536]).toEqual(false);
}
});
/**
* Tests conversion from 32-bit floating point numbers to split64 numbers.
*/
it('testFloat32ToSplit64', function() {
var f32_eps = jspb.BinaryConstants.FLOAT32_EPS;
var f32_min = jspb.BinaryConstants.FLOAT32_MIN;
var f32_max = jspb.BinaryConstants.FLOAT32_MAX;
var f32_max_safe_int = jspb.utils.joinFloat32(0x4b7fffff, 0);
var f32_pi = Math.fround(Math.PI);
// NaN.
jspb.utils.splitFloat32(NaN);
expect(isNaN(jspb.utils.joinFloat32(
jspb.utils.split64Low, jspb.utils.split64High)))
.toEqual(true);
/**
* @param {number} x
* @param {number=} opt_bits
*/
function test(x, opt_bits) {
jspb.utils.splitFloat32(x);
if (opt_bits !== undefined) {
if (opt_bits != jspb.utils.split64Low) throw 'fail!';
}
expect(truncate(x))
.toEqual(jspb.utils.joinFloat32(
jspb.utils.split64Low, jspb.utils.split64High));
}
// Positive and negative infinity.
test(Infinity, 0x7f800000);
test(-Infinity, 0xff800000);
// Positive and negative zero.
test(0, 0x00000000);
test(-0, 0x80000000);
// Positive and negative epsilon.
test(f32_eps, 0x00000001);
test(-f32_eps, 0x80000001);
// Positive and negative min.
test(f32_min, 0x00800000);
test(-f32_min, 0x80800000);
// Positive and negative max.
test(f32_max, 0x7F7FFFFF);
test(-f32_max, 0xFF7FFFFF);
// Positive and negative max_safe_int.
test(f32_max_safe_int, 0x4B7FFFFF);
test(-f32_max_safe_int, 0xCB7FFFFF);
// Pi.
test(f32_pi, 0x40490fdb);
// corner cases
test(0.9999999762949594, 0x3f800000);
test(7.99999999999999, 0x41000000);
test(Math.sin(30 * Math.PI / 180), 0x3f000000); // sin(30 degrees)
// Various positive values.
var cursor = f32_eps * 10;
while (cursor != Infinity) {
test(cursor);
cursor *= 1.1;
}
// Various negative values.
cursor = -f32_eps * 10;
while (cursor != -Infinity) {
test(cursor);
cursor *= 1.1;
}
});
/**
* Tests conversion from 64-bit floating point numbers to split64 numbers.
*/
it('testFloat64ToSplit64', function() {
var f64_eps = jspb.BinaryConstants.FLOAT64_EPS;
var f64_min = jspb.BinaryConstants.FLOAT64_MIN;
var f64_max = jspb.BinaryConstants.FLOAT64_MAX;
// NaN.
jspb.utils.splitFloat64(NaN);
expect(isNaN(jspb.utils.joinFloat64(
jspb.utils.split64Low, jspb.utils.split64High)))
.toEqual(true);
/**
* @param {number} x
* @param {number=} opt_highBits
* @param {number=} opt_lowBits
*/
function test(x, opt_highBits, opt_lowBits) {
jspb.utils.splitFloat64(x);
if (opt_highBits !== undefined) {
var split64High = jspb.utils.split64High;
expect(opt_highBits.toString(16)).toEqual(split64High.toString(16));
}
if (opt_lowBits !== undefined) {
var split64Low = jspb.utils.split64Low;
expect(opt_lowBits.toString(16)).toEqual(split64Low.toString(16));
}
expect(
jspb.utils.joinFloat64(jspb.utils.split64Low, jspb.utils.split64High))
.toEqual(x);
}
// Positive and negative infinity.
test(Infinity, 0x7ff00000, 0x00000000);
test(-Infinity, 0xfff00000, 0x00000000);
// Positive and negative zero.
test(0, 0x00000000, 0x00000000);
test(-0, 0x80000000, 0x00000000);
test(1, 0x3FF00000, 0x00000000);
test(2, 0x40000000, 0x00000000);
// Positive and negative epsilon.
test(f64_eps, 0x00000000, 0x00000001);
test(-f64_eps, 0x80000000, 0x00000001);
// Positive and negative min.
test(f64_min, 0x00100000, 0x00000000);
test(-f64_min, 0x80100000, 0x00000000);
// Positive and negative max.
test(f64_max, 0x7FEFFFFF, 0xFFFFFFFF);
test(-f64_max, 0xFFEFFFFF, 0xFFFFFFFF);
test(Number.MAX_SAFE_INTEGER, 0x433FFFFF, 0xFFFFFFFF);
test(Number.MIN_SAFE_INTEGER, 0xC33FFFFF, 0xFFFFFFFF);
// Test various edge cases with mantissa of all 1, all 0, or just the
// highest or lowest significant bit.
test(4503599627370497, 0x43300000, 0x00000001);
test(6755399441055744, 0x43380000, 0x00000000);
test(1.348269851146737e+308, 0x7FE80000, 0x00000000);
test(1.9999999999999998, 0x3FFFFFFF, 0xFFFFFFFF);
test(2.225073858507201e-308, 0x000FFFFF, 0xFFFFFFFF);
test(Math.PI, 0x400921fb, 0x54442d18);
test(jspb.BinaryConstants.FLOAT32_MIN, 0x38100000, 0x00000000);
// Various positive values.
var cursor = f64_eps * 10;
while (cursor != Infinity) {
test(cursor);
cursor *= 1.1;
}
// Various negative values.
cursor = -f64_eps * 10;
while (cursor != -Infinity) {
test(cursor);
cursor *= 1.1;
}
});
/**
* Tests zigzag conversions.
*/
it('can encode and decode zigzag 64', function() {
function stringToHiLoPair(str) {
jspb.utils.splitDecimalString(str);
return {
lo: jspb.utils.split64Low >>> 0,
hi: jspb.utils.split64High >>> 0
};
}
function makeHiLoPair(lo, hi) {
return {lo: lo >>> 0, hi: hi >>> 0};
}
// Test cases directly from the protobuf dev guide.
// https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
var testCases = [
{original: stringToHiLoPair('0'), zigzag: stringToHiLoPair('0')},
{original: stringToHiLoPair('-1'), zigzag: stringToHiLoPair('1')},
{original: stringToHiLoPair('1'), zigzag: stringToHiLoPair('2')},
{original: stringToHiLoPair('-2'), zigzag: stringToHiLoPair('3')},
{
original: stringToHiLoPair('2147483647'),
zigzag: stringToHiLoPair('4294967294')
},
{
original: stringToHiLoPair('-2147483648'),
zigzag: stringToHiLoPair('4294967295')
},
// 64-bit extremes
{
original: stringToHiLoPair('9223372036854775807'),
zigzag: stringToHiLoPair('18446744073709551614')
},
{
original: stringToHiLoPair('-9223372036854775808'),
zigzag: stringToHiLoPair('18446744073709551615')
},
];
for (const c of testCases) {
expect(jspb.utils.toZigzag64(c.original.lo, c.original.hi, makeHiLoPair))
.toEqual(c.zigzag);
expect(jspb.utils.fromZigzag64(c.zigzag.lo, c.zigzag.hi, makeHiLoPair))
.toEqual(c.original);
}
});
/**
* Tests counting packed varints.
*/
it('testCountVarints', function() {
var values = [];
for (var i = 1; i < 1000000000; i *= 1.1) {
values.push(Math.floor(i));
}
var writer = new jspb.BinaryWriter();
writer.writePackedUint64(1, values);
var buffer = new Uint8Array(writer.getResultBuffer());
// We should have two more varints than we started with - one for the field
// tag, one for the packed length.
expect(jspb.utils.countVarints(buffer, 0, buffer.length))
.toEqual(values.length + 2);
});
/**
* Tests counting matching varint fields.
*/
it('testCountVarintFields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeUint64(1, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countVarintFields(buffer, 0, buffer.length, 1))
.toEqual(count);
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeUint64(123456789, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countVarintFields(buffer, 0, buffer.length, 123456789))
.toEqual(count);
});
/**
* Tests counting matching fixed32 fields.
*/
it('testCountFixed32Fields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeFixed32(1, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 1))
.toEqual(count);
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeFixed32(123456789, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 123456789))
.toEqual(count);
});
/**
* Tests counting matching fixed64 fields.
*/
it('testCountFixed64Fields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeDouble(1, i);
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 1))
.toEqual(count);
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeDouble(123456789, i);
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 123456789))
.toEqual(count);
});
/**
* Tests counting matching delimited fields.
*/
it('testCountDelimitedFields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000; i *= 1.1) {
writer.writeBytes(1, [Math.floor(i)]);
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 1))
.toEqual(count);
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000; i *= 1.1) {
writer.writeBytes(123456789, [Math.floor(i)]);
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
expect(jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 123456789))
.toEqual(count);
});
/**
* Tests byte format for debug strings.
*/
it('testDebugBytesToTextFormat', function() {
expect(jspb.utils.debugBytesToTextFormat(null)).toEqual('""');
expect(jspb.utils.debugBytesToTextFormat([
0, 16, 255
])).toEqual('"\\x00\\x10\\xff"');
});
/**
* Tests converting byte blob sources into byte blobs.
*/
it('testByteSourceToUint8Array', function() {
var convert = jspb.utils.byteSourceToUint8Array;
var sourceData = [];
for (var i = 0; i < 256; i++) {
sourceData.push(i);
}
var sourceBytes = new Uint8Array(sourceData);
var sourceBuffer = sourceBytes.buffer;
var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
var sourceString = goog.crypt.byteArrayToString(sourceData);
function check(result) {
expect(result.constructor).toEqual(Uint8Array);
expect(result.length).toEqual(sourceData.length);
for (var i = 0; i < result.length; i++) {
expect(result[i]).toEqual(sourceData[i]);
}
}
// Converting Uint8Arrays into Uint8Arrays should be a no-op.
expect(convert(sourceBytes)).toEqual(sourceBytes);
// Converting Array<numbers> into Uint8Arrays should work.
check(convert(sourceData));
// Converting ArrayBuffers into Uint8Arrays should work.
check(convert(sourceBuffer));
// Converting base64-encoded strings into Uint8Arrays should work.
check(convert(sourceBase64));
});
});

File diff suppressed because it is too large Load Diff

View File

@ -1,412 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer writer. In
* practice BinaryWriter is used to drive the Decoder and Reader test cases,
* so only writer-specific tests are here.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.crypt');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryConstants');
goog.require('jspb.BinaryReader');
goog.require('jspb.BinaryWriter');
goog.require('jspb.utils');
goog.require('goog.crypt.base64');
goog.requireType('jspb.BinaryMessage');
/**
* @param {function()} func This function should throw an error when run.
*/
function assertFails(func) {
assertThrows(func);
}
describe('binaryWriterTest', function() {
/**
* Verifies that misuse of the writer class triggers assertions.
*/
it('testWriteErrors', function() {
// Submessages with invalid field indices should assert.
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
assertFails(function() {
writer.writeMessage(-1, dummyMessage, () => {});
});
// Writing invalid field indices should assert.
writer = new jspb.BinaryWriter();
assertFails(function() {
writer.writeUint64(-1, 1);
});
// Writing out-of-range field values should assert.
writer = new jspb.BinaryWriter();
assertFails(function() {
writer.writeInt32(1, -Infinity);
});
assertFails(function() {
writer.writeInt32(1, Infinity);
});
assertFails(function() {
writer.writeInt64(1, -Infinity);
});
assertFails(function() {
writer.writeInt64(1, Infinity);
});
assertFails(function() {
writer.writeUint32(1, -1);
});
assertFails(function() {
writer.writeUint32(1, Infinity);
});
assertFails(function() {
writer.writeUint64(1, -1);
});
assertFails(function() {
writer.writeUint64(1, Infinity);
});
assertFails(function() {
writer.writeSint32(1, -Infinity);
});
assertFails(function() {
writer.writeSint32(1, Infinity);
});
assertFails(function() {
writer.writeSint64(1, -Infinity);
});
assertFails(function() {
writer.writeSint64(1, Infinity);
});
assertFails(function() {
writer.writeFixed32(1, -1);
});
assertFails(function() {
writer.writeFixed32(1, Infinity);
});
assertFails(function() {
writer.writeFixed64(1, -1);
});
assertFails(function() {
writer.writeFixed64(1, Infinity);
});
assertFails(function() {
writer.writeSfixed32(1, -Infinity);
});
assertFails(function() {
writer.writeSfixed32(1, Infinity);
});
assertFails(function() {
writer.writeSfixed64(1, -Infinity);
});
assertFails(function() {
writer.writeSfixed64(1, Infinity);
});
});
/**
* Basic test of retrieving the result as a Uint8Array buffer
*/
it('testGetResultBuffer', function() {
var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';
var writer = new jspb.BinaryWriter();
writer.writeUint32(1, 100);
writer.writeString(2, 'Hello world');
writer.writeBytes(3, new Uint8Array([1, 2, 3]));
writer.writeUint32(4, 200);
var buffer = writer.getResultBuffer();
assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
});
/**
* Tests websafe encodings for base64 strings.
*/
it('testWebSafeOption', function() {
var writer = new jspb.BinaryWriter();
writer.writeBytes(1, new Uint8Array([127]));
assertEquals('CgF/', writer.getResultBase64String());
assertEquals(
'CgF/',
writer.getResultBase64String(goog.crypt.base64.Alphabet.DEFAULT));
assertEquals(
'CgF_',
writer.getResultBase64String(
goog.crypt.base64.Alphabet.WEBSAFE_NO_PADDING));
});
it('writes split 64 fields', function() {
var writer = new jspb.BinaryWriter();
writer.writeSplitVarint64(1, 0x1, 0x2);
writer.writeSplitVarint64(1, 0xFFFFFFFF, 0xFFFFFFFF);
writer.writeSplitFixed64(2, 0x1, 0x2);
writer.writeSplitFixed64(2, 0xFFFFFFF0, 0xFFFFFFFF);
function lo(i) {
return i + 1;
}
function hi(i) {
return i + 2;
}
writer.writeRepeatedSplitVarint64(3, [0, 1, 2], lo, hi);
writer.writeRepeatedSplitFixed64(4, [0, 1, 2], lo, hi);
writer.writePackedSplitVarint64(5, [0, 1, 2], lo, hi);
writer.writePackedSplitFixed64(6, [0, 1, 2], lo, hi);
function bitsAsArray(lowBits, highBits) {
return [lowBits >>> 0, highBits >>> 0];
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
expect(reader.readSplitVarint64(bitsAsArray)).toEqual([0x1, 0x2]);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
expect(reader.readSplitVarint64(bitsAsArray)).toEqual([
0xFFFFFFFF, 0xFFFFFFFF
]);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(2);
expect(reader.readSplitFixed64(bitsAsArray)).toEqual([0x1, 0x2]);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(2);
expect(reader.readSplitFixed64(bitsAsArray)).toEqual([
0xFFFFFFF0, 0xFFFFFFFF
]);
for (let i = 0; i < 3; i++) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(3);
expect(reader.readSplitVarint64(bitsAsArray)).toEqual([i + 1, i + 2]);
}
for (let i = 0; i < 3; i++) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(4);
expect(reader.readSplitFixed64(bitsAsArray)).toEqual([i + 1, i + 2]);
}
reader.nextField();
expect(reader.getFieldNumber()).toEqual(5);
expect(reader.readPackedInt64String()).toEqual([
String(2 * 2 ** 32 + 1),
String(3 * 2 ** 32 + 2),
String(4 * 2 ** 32 + 3),
]);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(6);
expect(reader.readPackedFixed64String()).toEqual([
String(2 * 2 ** 32 + 1),
String(3 * 2 ** 32 + 2),
String(4 * 2 ** 32 + 3),
]);
});
it('writes zigzag 64 fields', function() {
// Test cases directly from the protobuf dev guide.
// https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
var testCases = [
{original: '0', zigzag: '0'},
{original: '-1', zigzag: '1'},
{original: '1', zigzag: '2'},
{original: '-2', zigzag: '3'},
{original: '2147483647', zigzag: '4294967294'},
{original: '-2147483648', zigzag: '4294967295'},
// 64-bit extremes, not in dev guide.
{original: '9223372036854775807', zigzag: '18446744073709551614'},
{original: '-9223372036854775808', zigzag: '18446744073709551615'},
];
function decimalToLowBits(v) {
jspb.utils.splitDecimalString(v);
return jspb.utils.split64Low >>> 0;
}
function decimalToHighBits(v) {
jspb.utils.splitDecimalString(v);
return jspb.utils.split64High >>> 0;
}
var writer = new jspb.BinaryWriter();
testCases.forEach(function(c) {
writer.writeSint64String(1, c.original);
writer.writeSintHash64(1, jspb.utils.decimalStringToHash64(c.original));
jspb.utils.splitDecimalString(c.original);
writer.writeSplitZigzagVarint64(
1, jspb.utils.split64Low, jspb.utils.split64High);
});
writer.writeRepeatedSint64String(2, testCases.map(function(c) {
return c.original;
}));
writer.writeRepeatedSintHash64(3, testCases.map(function(c) {
return jspb.utils.decimalStringToHash64(c.original);
}));
writer.writeRepeatedSplitZigzagVarint64(
4, testCases.map(function(c) {
return c.original;
}),
decimalToLowBits, decimalToHighBits);
writer.writePackedSint64String(5, testCases.map(function(c) {
return c.original;
}));
writer.writePackedSintHash64(6, testCases.map(function(c) {
return jspb.utils.decimalStringToHash64(c.original);
}));
writer.writePackedSplitZigzagVarint64(
7, testCases.map(function(c) {
return c.original;
}),
decimalToLowBits, decimalToHighBits);
// Verify by reading the stream as normal int64 fields and checking with
// the canonical zigzag encoding of each value.
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
testCases.forEach(function(c) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
expect(reader.readUint64String()).toEqual(c.zigzag);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
expect(reader.readUint64String()).toEqual(c.zigzag);
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
expect(reader.readUint64String()).toEqual(c.zigzag);
});
testCases.forEach(function(c) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(2);
expect(reader.readUint64String()).toEqual(c.zigzag);
});
testCases.forEach(function(c) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(3);
expect(reader.readUint64String()).toEqual(c.zigzag);
});
testCases.forEach(function(c) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(4);
expect(reader.readUint64String()).toEqual(c.zigzag);
});
reader.nextField();
expect(reader.getFieldNumber()).toEqual(5);
expect(reader.readPackedUint64String()).toEqual(testCases.map(function(c) {
return c.zigzag;
}));
reader.nextField();
expect(reader.getFieldNumber()).toEqual(6);
expect(reader.readPackedUint64String()).toEqual(testCases.map(function(c) {
return c.zigzag;
}));
reader.nextField();
expect(reader.getFieldNumber()).toEqual(7);
expect(reader.readPackedUint64String()).toEqual(testCases.map(function(c) {
return c.zigzag;
}));
});
it('writes float32 fields', function() {
var testCases = [
0, 1, -1, jspb.BinaryConstants.FLOAT32_MIN,
-jspb.BinaryConstants.FLOAT32_MIN, jspb.BinaryConstants.FLOAT32_MAX,
-jspb.BinaryConstants.FLOAT32_MAX, 3.1415927410125732, Infinity,
-Infinity, NaN
];
var writer = new jspb.BinaryWriter();
testCases.forEach(function(f) {
writer.writeFloat(1, f);
});
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
testCases.forEach(function(f) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
if (isNaN(f)) {
expect(isNaN(reader.readFloat())).toEqual(true);
} else {
expect(reader.readFloat()).toEqual(f);
}
});
});
it('writes double fields', function() {
var testCases = [
0, 1, -1, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER,
Number.MAX_VALUE, Number.MIN_VALUE, jspb.BinaryConstants.FLOAT32_MIN,
-jspb.BinaryConstants.FLOAT32_MIN, jspb.BinaryConstants.FLOAT32_MAX,
-jspb.BinaryConstants.FLOAT32_MAX, Math.PI, Infinity, -Infinity, NaN
];
var writer = new jspb.BinaryWriter();
testCases.forEach(function(f) {
writer.writeDouble(1, f);
});
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
testCases.forEach(function(f) {
reader.nextField();
expect(reader.getFieldNumber()).toEqual(1);
if (isNaN(f)) {
expect(isNaN(reader.readDouble())).toEqual(true);
} else {
expect(reader.readDouble()).toEqual(f);
}
});
});
});

View File

@ -1,32 +0,0 @@
/**
* @fileoverview Export symbols needed by generated code in CommonJS style.
*
* This effectively is our canonical list of what we publicly export from
* the google-protobuf.js file that we build at distribution time.
*/
goog.provide('jspb.Export');
goog.require('goog.object');
goog.require('jspb.BinaryReader');
goog.require('jspb.BinaryWriter');
goog.require('jspb.ExtensionFieldBinaryInfo');
goog.require('jspb.ExtensionFieldInfo');
goog.require('jspb.Message');
goog.require('jspb.Map');
if (typeof exports === 'object') {
exports.Map = jspb.Map;
exports.Message = jspb.Message;
exports.BinaryReader = jspb.BinaryReader;
exports.BinaryWriter = jspb.BinaryWriter;
exports.ExtensionFieldInfo = jspb.ExtensionFieldInfo;
exports.ExtensionFieldBinaryInfo = jspb.ExtensionFieldBinaryInfo;
// These are used by generated code but should not be used directly by
// clients.
exports.exportSymbol = goog.exportSymbol;
exports.inherits = goog.inherits;
exports.object = {extend: goog.object.extend};
exports.typeOf = goog.typeOf;
}

View File

@ -1,39 +0,0 @@
/**
* @fileoverview Exports symbols needed only by tests.
*
* This file exports several Closure Library symbols that are only
* used by tests. It is used to generate a file
* closure_asserts_commonjs.js that is only used at testing time.
*/
goog.provide('jspb.ExportAsserts');
goog.require('goog.testing.asserts');
var global = Function('return this')();
// All of the closure "assert" functions are exported at the global level.
//
// The Google Closure assert functions start with assert, eg.
// assertThrows
// assertNotThrows
// assertTrue
// ...
//
// The one exception is the "fail" function.
function shouldExport(str) {
return str.lastIndexOf('assert') === 0 || str == 'fail';
}
for (var key in global) {
if ((typeof key == "string") && global.hasOwnProperty(key) &&
shouldExport(key)) {
exports[key] = global[key];
}
}
// The COMPILED variable is set by Closure compiler to "true" when it compiles
// JavaScript, so in practice this is equivalent to "exports.COMPILED = true".
// This will disable some debugging functionality in debug.js. We could
// investigate whether this can/should be enabled in CommonJS builds.
exports.COMPILED = COMPILED

View File

@ -1,22 +0,0 @@
/**
* @fileoverview Export symbols needed by tests in CommonJS style.
*
* This file is like export.js, but for symbols that are only used by tests.
* However we exclude assert functions here, because they are exported into
* the global namespace, so those are handled as a special case in
* export_asserts.js.
*/
goog.provide('jspb.ExportTestDeps');
goog.require('goog.crypt.base64');
goog.require('goog.testing.PropertyReplacer');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
goog.require('jspb.BinaryEncoder');
goog.require('jspb.BinaryDecoder');
goog.require('jspb.BinaryWriter');
goog.require('jspb.utils');
exports.goog = goog;
exports.jspb = jspb;

View File

@ -1,52 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test suite is written using Jasmine -- see http://jasmine.github.io/
var googleProtobuf = require('google-protobuf');
var asserts = require('closure_asserts_commonjs');
var global = Function('return this')();
// Bring asserts into the global namespace.
googleProtobuf.object.extend(global, asserts);
googleProtobuf.exportSymbol('jspb.Message', googleProtobuf.Message, global);
var test7_pb = require('./test7/test7_pb');
googleProtobuf.exportSymbol('proto.jspb.test.framing.FramingMessage', test7_pb.FramingMessage, global);
describe('Import test suite', function() {
it('testImportedMessage', function() {
var framing1 = new proto.jspb.test.framing.FramingMessage([]);
var framing2 = new proto.jspb.test.framing.FramingMessage([]);
assertObjectEquals(framing1.toObject(), framing2.toObject());
});
});

View File

@ -1,9 +0,0 @@
{
"spec_dir": "",
"spec_files": [
"*_test.js",
"binary/proto_test.js"
],
"helpers": [
]
}

View File

@ -1,99 +0,0 @@
/**
* @fileoverview Utility to translate test files to CommonJS imports.
*
* This is a somewhat hacky tool designed to do one very specific thing.
* All of the test files in *_test.js are written with Closure-style
* imports (goog.require()). This works great for running the tests
* against Closure-style generated code, but we also want to run the
* tests against CommonJS-style generated code without having to fork
* the tests.
*
* Closure-style imports import each individual type by name. This is
* very different than CommonJS imports which are by file. So we put
* special comments in these tests like:
*
* // CommonJS-LoadFromFile: test_pb
* goog.require('proto.jspb.test.CloneExtension');
* goog.require('proto.jspb.test.Complex');
* goog.require('proto.jspb.test.DefaultValues');
*
* This script parses that special comment and uses it to generate proper
* CommonJS require() statements so that the tests can run and pass using
* CommonJS imports. The script will change the above statements into:
*
* var test_pb = require('test_pb');
* googleProtobuf.exportSymbol('proto.jspb.test.CloneExtension', test_pb.CloneExtension, global);
* googleProtobuf.exportSymbol('proto.jspb.test.Complex', test_pb.Complex, global);
* googleProtobuf.exportSymbol('proto.jspb.test.DefaultValues', test_pb.DefaultValues, global);
*
* (The "exportSymbol" function will define the given names in the global
* namespace, taking care not to overwrite any previous value for
* "proto.jspb.test").
*/
var lineReader = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
function tryStripPrefix(str, prefix) {
if (str.lastIndexOf(prefix) !== 0) {
throw "String: " + str + " didn't start with: " + prefix;
}
return str.substr(prefix.length);
}
function camelCase(str) {
var ret = '';
var ucaseNext = false;
for (var i = 0; i < str.length; i++) {
if (str[i] == '-') {
ucaseNext = true;
} else if (ucaseNext) {
ret += str[i].toUpperCase();
ucaseNext = false;
} else {
ret += str[i];
}
}
return ret;
}
var module = null;
var pkg = null;
// Header: goes in every file at the top.
console.log("var global = Function('return this')();");
console.log("var googleProtobuf = require('google-protobuf');");
console.log("var testdeps = require('testdeps_commonjs');");
console.log("global.goog = testdeps.goog;");
console.log("global.jspb = testdeps.jspb;");
console.log("var asserts = require('closure_asserts_commonjs');");
console.log("");
console.log("// Bring asserts into the global namespace.");
console.log("googleProtobuf.object.extend(global, asserts);");
lineReader.on('line', function(line) {
var isRequire = line.match(/goog\.require\('([^']*)'\)/);
var isLoadFromFile = line.match(/CommonJS-LoadFromFile: (\S*) (.*)/);
var isSetTestOnly = line.match(/goog.setTestOnly()/);
if (isRequire) {
if (module) { // Skip goog.require() lines before the first directive.
var fullSym = isRequire[1];
// Skip lines importing from jspb.*, these are handled by the header above.
if (fullSym.match(/^jspb\./)) return;
var sym = tryStripPrefix(fullSym, pkg);
console.log("googleProtobuf.exportSymbol('" + fullSym + "', " + module + sym + ', global);');
}
} else if (isLoadFromFile) {
var module_path = isLoadFromFile[1].split('/');
module = camelCase(module_path[module_path.length - 1]);
pkg = isLoadFromFile[2];
if (module != "googleProtobuf") { // We unconditionally require this in the header.
console.log("var " + module + " = require('./" + isLoadFromFile[1] + "');");
}
} else if (!isSetTestOnly) { // Remove goog.setTestOnly() lines.
console.log(line);
}
});

View File

@ -1,67 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test suite is written using Jasmine -- see http://jasmine.github.io/
var googleProtobuf = require('google-protobuf');
var asserts = require('closure_asserts_commonjs');
var global = Function('return this')();
// Bring asserts into the global namespace.
googleProtobuf.object.extend(global, asserts);
var test9_pb = require('./test9_pb');
var test10_pb = require('./test10_pb');
describe('Strict test suite', function() {
it('testImportedMessage', function() {
var simple1 = new test9_pb.jspb.exttest.strict.nine.Simple9()
var simple2 = new test9_pb.jspb.exttest.strict.nine.Simple9()
assertObjectEquals(simple1.toObject(), simple2.toObject());
});
it('testGlobalScopePollution', function() {
assertObjectEquals(global.jspb.exttest, undefined);
});
describe('with imports', function() {
it('testImportedMessage', function() {
var simple1 = new test10_pb.jspb.exttest.strict.ten.Simple10()
var simple2 = new test10_pb.jspb.exttest.strict.ten.Simple10()
assertObjectEquals(simple1.toObject(), simple2.toObject());
});
it('testGlobalScopePollution', function() {
assertObjectEquals(global.jspb.exttest, undefined);
});
});
});

View File

@ -1,40 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test.importing;
message ImportedMessage {
string string_value = 1;
}

View File

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test.framing;
import "test6/test6.proto";
message FramingMessage {
jspb.test.importing.ImportedMessage imported_message = 1;
}

View File

@ -1,355 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for Int64-manipulation functions.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author cfallin@google.com (Chris Fallin)
*/
goog.require('goog.testing.asserts');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
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);
assertEquals(a.cmp(b), 0);
assertEquals(b.cmp(a), 0);
b.lo -= 1;
assertEquals(a.cmp(b), 1);
assertEquals(b.cmp(a), -1);
b.lo += 2;
assertEquals(a.cmp(b), -1);
assertEquals(b.cmp(a), 1);
b.lo = a.lo;
b.hi = a.hi - 1;
assertEquals(a.cmp(b), 1);
assertEquals(b.cmp(a), -1);
assertEquals(a.zero(), false);
assertEquals(a.msb(), false);
assertEquals(a.lsb(), false);
a.hi = 0;
a.lo = 0;
assertEquals(a.zero(), true);
a.hi = 0x80000000;
assertEquals(a.zero(), false);
assertEquals(a.msb(), true);
a.lo = 0x00000001;
assertEquals(a.lsb(), true);
});
/**
* Tests shifts.
*/
it('testShifts', function() {
var a = new jspb.arith.UInt64(1, 0);
assertEquals(a.lo, 1);
assertEquals(a.hi, 0);
var orig = a;
a = a.leftShift();
assertEquals(orig.lo, 1); // original unmodified.
assertEquals(orig.hi, 0);
assertEquals(a.lo, 2);
assertEquals(a.hi, 0);
a = a.leftShift();
assertEquals(a.lo, 4);
assertEquals(a.hi, 0);
for (var i = 0; i < 29; i++) {
a = a.leftShift();
}
assertEquals(a.lo, 0x80000000);
assertEquals(a.hi, 0);
a = a.leftShift();
assertEquals(a.lo, 0);
assertEquals(a.hi, 1);
a = a.leftShift();
assertEquals(a.lo, 0);
assertEquals(a.hi, 2);
a = a.rightShift();
a = a.rightShift();
assertEquals(a.lo, 0x80000000);
assertEquals(a.hi, 0);
a = a.rightShift();
assertEquals(a.lo, 0x40000000);
assertEquals(a.hi, 0);
});
/**
* 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);
// Addition with carry.
var c = a.add(b);
assertEquals(a.lo, 0x89abcdef); // originals unmodified.
assertEquals(a.hi, 0x01234567);
assertEquals(b.lo, 0xff52ab91);
assertEquals(b.hi, 0x92fa2123);
assertEquals(c.lo, 0x88fe7980);
assertEquals(c.hi, 0x941d668b);
// Simple addition without carry.
a.lo = 2;
a.hi = 0;
b.lo = 3;
b.hi = 0;
c = a.add(b);
assertEquals(c.lo, 5);
assertEquals(c.hi, 0);
});
/**
* 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);
assertEquals(c.hi, a.hi);
assertEquals(c.lo, a.lo);
}
}
});
/**
* Tests 32-by-32 multiplication.
*/
it('testMul32x32', function() {
var testData = [
// a b low(a*b) high(a*b)
[0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8],
[0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc],
[0xfe4efe70, 0x80b48c37, 0xbcddea10, 0x7fdada0c],
[0xe222fd4a, 0xe43d524a, 0xd5e0eb64, 0xc99d549c],
[0xd171f469, 0xb94ebd01, 0x4be17969, 0x979bc4fa],
[0x829cc1df, 0xe2598b38, 0xf4157dc8, 0x737c12ad],
[0xf10c3767, 0x8382881e, 0x942b3612, 0x7bd428b8],
[0xb0f6dd24, 0x232597e1, 0x079c98a4, 0x184bbce7],
[0xfcdb05a7, 0x902f55bc, 0x636199a4, 0x8e69f412],
[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);
assertEquals(c.lo, cLow);
assertEquals(c.hi, cHigh);
}
});
/**
* Tests 64-by-32 multiplication.
*/
it('testMul', 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 = [
// low(a) high(a) low(a*b) high(a*b)
[0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f],
[0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b],
[0xf42d4fb4, 0xae366403, 0xa65a1000, 0x92434000, 0x1ff978df],
[0x17e2f56b, 0x25487693, 0xf13f98c7, 0x73794e2d, 0xa96b0c6a],
[0x492f241f, 0x76c0eb67, 0x7377ac44, 0xd4336c3c, 0xfc4b1ebe],
[0xd6b92321, 0xe184fa48, 0xd6e76904, 0x93141584, 0xcbf44da1],
[0x4bf007ea, 0x968c0a9e, 0xf5e4026a, 0x4fdb1ae4, 0x61b9fb7d],
[0x10a83be7, 0x2d685ba6, 0xc9e5fb7f, 0x2ad43499, 0x3742473d],
[0x2f261829, 0x1aca681a, 0x3d3494e3, 0x8213205b, 0x283719f8],
[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]);
assertEquals(prod.lo, testData[i][3]);
assertEquals(prod.hi, testData[i][4]);
}
});
/**
* Tests 64-div-by-32 division.
*/
it('testDiv', function() {
// Compute a/b, yielding quot = a/b and rem = a%b.
var 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],
[0x11912915, 0xb2699eb5, 0x30467cbe, 0xb21b4be4, 0x00000003, 0x283465dd],
[0x0d917982, 0x201f2a6e, 0x3f35bf03, 0x8217c8e4, 0x00000000, 0x153402d6],
[0xa072c108, 0x74020c96, 0xc60568fd, 0x95f9613e, 0x00000000, 0x3f4676c2],
[0xd845d5d8, 0xcdd235c4, 0x20426475, 0x6154e78b, 0x00000006, 0x202fb751],
[0xa4dbf71f, 0x9e90465e, 0xf08e022f, 0xa8be947f, 0x00000000, 0xbe43b5ce],
[0x3dbe627f, 0xa791f4b9, 0x28a5bd89, 0x1f5dfe93, 0x00000004, 0x02bf9ed4],
[0x5c1c53ee, 0xccf5102e, 0x198576e7, 0x07e3ae31, 0x00000008, 0x02ea8fb7],
[0xfef1e581, 0x04714067, 0xca6540c1, 0x059e73ec, 0x00000000, 0x31658095],
[0x1e2dd90c, 0x13dd6667, 0x8b2184c3, 0x248d1a42, 0x00000000, 0x4ca6d0c6],
// --- divisors in (0, 2^16-1) to test larger quotient high-words
// low(a) high(a) b low(quot) high(quot) rem
[0x86722b47, 0x2cd57c9a, 0x00003123, 0x2ae41b7a, 0x0000e995, 0x00000f99],
[0x1dd7884c, 0xf5e839bc, 0x00009eeb, 0x5c886242, 0x00018c21, 0x000099b6],
[0x5c53d625, 0x899fc7e5, 0x000087d7, 0xd625007a, 0x0001035c, 0x000019af],
[0x6932d932, 0x9d0a5488, 0x000051fb, 0x9d976143, 0x0001ea63, 0x00004981],
[0x4d18bb85, 0x0c92fb31, 0x00001d9f, 0x03265ab4, 0x00006cac, 0x000001b9],
[0xbe756768, 0xdea67ccb, 0x00008a03, 0x58add442, 0x00019cff, 0x000056a2],
[0xe2466f9a, 0x2521f114, 0x0000c350, 0xa0c0860d, 0x000030ab, 0x0000a48a],
[0xf00ddad1, 0xe2f5446a, 0x00002cfc, 0x762697a6, 0x00050b96, 0x00000b69],
[0xa879152a, 0x0a70e0a5, 0x00007cdf, 0xb44151b3, 0x00001567, 0x0000363d],
[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];
assertEquals(quotient.lo, testData[i][3]);
assertEquals(quotient.hi, testData[i][4]);
assertEquals(remainder.lo, testData[i][5]);
}
});
/**
* 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']
];
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());
assertEquals(roundtrip.lo, a.lo);
assertEquals(roundtrip.hi, a.hi);
assertEquals(a.toString(), testData[i][2]);
}
});
/**
* Tests signed Int64s. These are built on UInt64s, so we only need to test
* 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'
];
for (var i = 0; i < testStrings.length; i++) {
var roundtrip =
jspb.arith.Int64.fromString(testStrings[i]).toString();
assertEquals(roundtrip, testStrings[i]);
}
});
});

View File

@ -1,317 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer decoder.
*
* There are two particular magic numbers that need to be pointed out -
* 2^64-1025 is the largest number representable as both a double and an
* unsigned 64-bit integer, and 2^63-513 is the largest number representable as
* both a double and a signed 64-bit integer.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryConstants');
goog.require('jspb.BinaryDecoder');
goog.require('jspb.BinaryEncoder');
/**
* Tests encoding and decoding of unsigned types.
* @param {Function} readValue
* @param {Function} writeValue
* @param {number} epsilon
* @param {number} upperLimit
* @param {Function} filter
* @suppress {missingProperties|visibility}
*/
function doTestUnsignedValue(readValue,
writeValue, epsilon, upperLimit, filter) {
var encoder = new jspb.BinaryEncoder();
// Encode zero and limits.
writeValue.call(encoder, filter(0));
writeValue.call(encoder, filter(epsilon));
writeValue.call(encoder, filter(upperLimit));
// Encode positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
writeValue.call(encoder, filter(cursor));
}
var 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));
// Check positive values.
for (var 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);});
}
/**
* Tests encoding and decoding of signed types.
* @param {Function} readValue
* @param {Function} writeValue
* @param {number} epsilon
* @param {number} lowerLimit
* @param {number} upperLimit
* @param {Function} filter
* @suppress {missingProperties}
*/
function doTestSignedValue(readValue,
writeValue, epsilon, lowerLimit, upperLimit, filter) {
var encoder = new jspb.BinaryEncoder();
// Encode zero and limits.
writeValue.call(encoder, filter(lowerLimit));
writeValue.call(encoder, filter(-epsilon));
writeValue.call(encoder, filter(0));
writeValue.call(encoder, filter(epsilon));
writeValue.call(encoder, filter(upperLimit));
var inputValues = [];
// Encode negative values.
for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
var 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);
writeValue.call(encoder, val);
inputValues.push(val);
}
var 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));
// Verify decoded values.
for (var i = 0; i < inputValues.length; i++) {
assertEquals(inputValues[i], readValue.call(decoder));
}
// Encoding values outside the valid range should assert.
assertThrows(function() {writeValue.call(encoder, lowerLimit * 1.1);});
assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
}
describe('binaryDecoderTest', function() {
/**
* Tests the decoder instance cache.
*/
it('testInstanceCache', /** @suppress {visibility} */ function() {
// Empty the instance caches.
jspb.BinaryDecoder.instanceCache_ = [];
// Allocating and then freeing a decoder should put it in the instance
// cache.
jspb.BinaryDecoder.alloc().free();
assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
// 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();
decoder1.free();
decoder2.free();
decoder3.free();
assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
});
/**
* Tests reading 64-bit integers as hash strings.
*/
it('testHashStrings', function() {
var encoder = new jspb.BinaryEncoder();
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);
encoder.writeVarintHash64(hashA);
encoder.writeVarintHash64(hashB);
encoder.writeVarintHash64(hashC);
encoder.writeVarintHash64(hashD);
encoder.writeFixedHash64(hashA);
encoder.writeFixedHash64(hashB);
encoder.writeFixedHash64(hashC);
encoder.writeFixedHash64(hashD);
var decoder = jspb.BinaryDecoder.alloc(encoder.end());
assertEquals(hashA, decoder.readVarintHash64());
assertEquals(hashB, decoder.readVarintHash64());
assertEquals(hashC, decoder.readVarintHash64());
assertEquals(hashD, decoder.readVarintHash64());
assertEquals(hashA, decoder.readFixedHash64());
assertEquals(hashB, decoder.readFixedHash64());
assertEquals(hashC, decoder.readFixedHash64());
assertEquals(hashD, decoder.readFixedHash64());
});
/**
* Verifies that misuse of the decoder class triggers assertions.
* @suppress {checkTypes|visibility}
*/
it('testDecodeErrors', function() {
// 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()});
// Overlong varints should trigger assertions.
decoder.setBlock([255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0]);
assertThrows(function() {decoder.readUnsignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readSignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readZigzagVarint64()});
decoder.reset();
assertThrows(function() {decoder.readUnsignedVarint32()});
});
/**
* Tests encoding and decoding of unsigned integers.
*/
it('testUnsignedIntegers', function() {
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint8,
jspb.BinaryEncoder.prototype.writeUint8,
1, 0xFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint16,
jspb.BinaryEncoder.prototype.writeUint16,
1, 0xFFFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint32,
jspb.BinaryEncoder.prototype.writeUint32,
1, 0xFFFFFFFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint64,
jspb.BinaryEncoder.prototype.writeUint64,
1, Math.pow(2, 64) - 1025, Math.round);
});
/**
* Tests encoding and decoding of signed integers.
*/
it('testSignedIntegers', function() {
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt8,
jspb.BinaryEncoder.prototype.writeInt8,
1, -0x80, 0x7F, Math.round);
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt16,
jspb.BinaryEncoder.prototype.writeInt16,
1, -0x8000, 0x7FFF, Math.round);
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt32,
jspb.BinaryEncoder.prototype.writeInt32,
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);
});
/**
* Tests encoding and decoding of floats.
*/
it('testFloats', function() {
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var 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);
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; });
});
});

View File

@ -1,628 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test suite is written using Jasmine -- see http://jasmine.github.io/
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
goog.require('jspb.Message');
// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test
goog.require('proto.jspb.test.ExtendsWithMessage');
goog.require('proto.jspb.test.ForeignEnum');
goog.require('proto.jspb.test.ForeignMessage');
goog.require('proto.jspb.test.TestAllTypes');
goog.require('proto.jspb.test.TestExtendable');
goog.require('proto.jspb.test.extendOptionalBool');
goog.require('proto.jspb.test.extendOptionalBytes');
goog.require('proto.jspb.test.extendOptionalDouble');
goog.require('proto.jspb.test.extendOptionalFixed32');
goog.require('proto.jspb.test.extendOptionalFixed64');
goog.require('proto.jspb.test.extendOptionalFloat');
goog.require('proto.jspb.test.extendOptionalForeignEnum');
goog.require('proto.jspb.test.extendOptionalInt32');
goog.require('proto.jspb.test.extendOptionalInt64');
goog.require('proto.jspb.test.extendOptionalSfixed32');
goog.require('proto.jspb.test.extendOptionalSfixed64');
goog.require('proto.jspb.test.extendOptionalSint32');
goog.require('proto.jspb.test.extendOptionalSint64');
goog.require('proto.jspb.test.extendOptionalString');
goog.require('proto.jspb.test.extendOptionalUint32');
goog.require('proto.jspb.test.extendOptionalUint64');
goog.require('proto.jspb.test.extendPackedRepeatedBoolList');
goog.require('proto.jspb.test.extendPackedRepeatedDoubleList');
goog.require('proto.jspb.test.extendPackedRepeatedFixed32List');
goog.require('proto.jspb.test.extendPackedRepeatedFixed64List');
goog.require('proto.jspb.test.extendPackedRepeatedFloatList');
goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList');
goog.require('proto.jspb.test.extendPackedRepeatedInt32List');
goog.require('proto.jspb.test.extendPackedRepeatedInt64List');
goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List');
goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List');
goog.require('proto.jspb.test.extendPackedRepeatedSint32List');
goog.require('proto.jspb.test.extendPackedRepeatedSint64List');
goog.require('proto.jspb.test.extendPackedRepeatedUint32List');
goog.require('proto.jspb.test.extendPackedRepeatedUint64List');
goog.require('proto.jspb.test.extendRepeatedBoolList');
goog.require('proto.jspb.test.extendRepeatedBytesList');
goog.require('proto.jspb.test.extendRepeatedDoubleList');
goog.require('proto.jspb.test.extendRepeatedFixed32List');
goog.require('proto.jspb.test.extendRepeatedFixed64List');
goog.require('proto.jspb.test.extendRepeatedFloatList');
goog.require('proto.jspb.test.extendRepeatedForeignEnumList');
goog.require('proto.jspb.test.extendRepeatedInt32List');
goog.require('proto.jspb.test.extendRepeatedInt64List');
goog.require('proto.jspb.test.extendRepeatedSfixed32List');
goog.require('proto.jspb.test.extendRepeatedSfixed64List');
goog.require('proto.jspb.test.extendRepeatedSint32List');
goog.require('proto.jspb.test.extendRepeatedSint64List');
goog.require('proto.jspb.test.extendRepeatedStringList');
goog.require('proto.jspb.test.extendRepeatedUint32List');
goog.require('proto.jspb.test.extendRepeatedUint64List');
var suite = {};
var BYTES = new Uint8Array([1, 2, 8, 9]);
var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
/**
* Helper: fill all fields on a TestAllTypes message.
* @param {proto.jspb.test.TestAllTypes} msg
*/
function fillAllFields(msg) {
msg.setOptionalInt32(-42);
// can be exactly represented by JS number (64-bit double, i.e., 52-bit
// mantissa).
msg.setOptionalInt64(-0x7fffffff00000000);
msg.setOptionalUint32(0x80000000);
msg.setOptionalUint64(0xf000000000000000);
msg.setOptionalSint32(-100);
msg.setOptionalSint64(-0x8000000000000000);
msg.setOptionalFixed32(1234);
msg.setOptionalFixed64(0x1234567800000000);
msg.setOptionalSfixed32(-1234);
msg.setOptionalSfixed64(-0x1234567800000000);
msg.setOptionalFloat(1.5);
msg.setOptionalDouble(-1.5);
msg.setOptionalBool(true);
msg.setOptionalString('hello world');
msg.setOptionalBytes(BYTES);
msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup());
msg.getOptionalGroup().setA(100);
var submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(16);
msg.setOptionalForeignMessage(submsg);
msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO);
msg.setOneofString('oneof');
msg.setRepeatedInt32List([-42]);
msg.setRepeatedInt64List([-0x7fffffff00000000]);
msg.setRepeatedUint32List([0x80000000]);
msg.setRepeatedUint64List([0xf000000000000000]);
msg.setRepeatedSint32List([-100]);
msg.setRepeatedSint64List([-0x8000000000000000]);
msg.setRepeatedFixed32List([1234]);
msg.setRepeatedFixed64List([0x1234567800000000]);
msg.setRepeatedSfixed32List([-1234]);
msg.setRepeatedSfixed64List([-0x1234567800000000]);
msg.setRepeatedFloatList([1.5]);
msg.setRepeatedDoubleList([-1.5]);
msg.setRepeatedBoolList([true]);
msg.setRepeatedStringList(['hello world']);
msg.setRepeatedBytesList([BYTES, BYTES]);
msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]);
msg.getRepeatedGroupList()[0].setA(100);
submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(1000);
msg.setRepeatedForeignMessageList([submsg]);
msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
msg.setPackedRepeatedInt32List([-42]);
msg.setPackedRepeatedInt64List([-0x7fffffff00000000]);
msg.setPackedRepeatedUint32List([0x80000000]);
msg.setPackedRepeatedUint64List([0xf000000000000000]);
msg.setPackedRepeatedSint32List([-100]);
msg.setPackedRepeatedSint64List([-0x8000000000000000]);
msg.setPackedRepeatedFixed32List([1234]);
msg.setPackedRepeatedFixed64List([0x1234567800000000]);
msg.setPackedRepeatedSfixed32List([-1234]);
msg.setPackedRepeatedSfixed64List([-0x1234567800000000]);
msg.setPackedRepeatedFloatList([1.5]);
msg.setPackedRepeatedDoubleList([-1.5]);
msg.setPackedRepeatedBoolList([true]);
}
/**
* Helper: compare a bytes field to an expected value
* @param {Uint8Array|string} arr
* @param {Uint8Array} expected
* @return {boolean}
*/
function bytesCompare(arr, expected) {
if (typeof arr === 'string') {
arr = goog.crypt.base64.decodeStringToUint8Array(arr);
}
if (arr.length != expected.length) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] != expected[i]) {
return false;
}
}
return true;
}
/**
* Helper: verify contents of given TestAllTypes message as set by
* fillAllFields().
* @param {proto.jspb.test.TestAllTypes} original
* @param {proto.jspb.test.TestAllTypes} copy
*/
function checkAllFields(original, copy) {
assertTrue(jspb.Message.equals(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]);
}
/**
* Helper: verify that all expected extensions are present.
* @param {!proto.jspb.test.TestExtendable} msg
*/
function checkExtensions(msg) {
assertEquals(-42,
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,
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,
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]);
}
describe('protoBinaryTest', function() {
/**
* 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();
fillAllFields(msg);
var encoded = msg.serializeBinary();
var 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();
// 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));
// 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));
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));
});
/**
* Test that bytes setters will receive result of any of the getters.
*/
it('testBytesFieldsSettersInterop', function() {
var msg = new proto.jspb.test.TestAllTypes();
msg.setOptionalBytes(BYTES);
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes_asB64());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes_asU8());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
});
/**
* Test that bytes setters will receive result of any of the getters.
*/
it('testRepeatedBytesGetters', function() {
var 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));
}
msg.setRepeatedBytesList([BYTES, BYTES]);
assertGetters();
msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
assertGetters();
msg.setRepeatedBytesList(null);
assertEquals(0, msg.getRepeatedBytesList().length);
assertEquals(0, msg.getRepeatedBytesList_asB64().length);
assertEquals(0, msg.getRepeatedBytesList_asU8().length);
});
/**
* Helper: fill all extension values.
* @param {proto.jspb.test.TestExtendable} msg
*/
function fillExtensions(msg) {
msg.setExtension(
proto.jspb.test.extendOptionalInt32, -42);
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.extendOptionalBytes, BYTES);
var submsg = new proto.jspb.test.ExtendsWithMessage();
submsg.setFoo(16);
msg.setExtension(
proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg);
msg.setExtension(
proto.jspb.test.extendOptionalForeignEnum,
proto.jspb.test.ForeignEnum.FOREIGN_FOO);
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.extendRepeatedUint64List, [0xf000000000000000]);
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.extendRepeatedFixed64List, [0x1234567800000000]);
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.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,
[proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
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.extendPackedRepeatedSint64List, [-0x8000000000000000]);
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.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.extendPackedRepeatedForeignEnumList,
[proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
}
/**
* Tests extension serialization and deserialization.
*/
it('testExtensions', function() {
var msg = new proto.jspb.test.TestExtendable();
fillExtensions(msg);
var encoded = msg.serializeBinary();
var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded);
checkExtensions(decoded);
});
});

View File

@ -1,922 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer reader.
*
* There are two particular magic numbers that need to be pointed out -
* 2^64-1025 is the largest number representable as both a double and an
* unsigned 64-bit integer, and 2^63-513 is the largest number representable as
* both a double and a signed 64-bit integer.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @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');
describe('binaryReaderTest', function() {
/**
* Tests the reader instance cache.
*/
it('testInstanceCaches', /** @suppress {visibility} */ function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
writer.writeMessage(1, dummyMessage, () => {});
writer.writeMessage(2, dummyMessage, () => {});
var buffer = writer.getResultBuffer();
// Empty the instance caches.
jspb.BinaryReader.instanceCache_ = [];
// 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();
decoder1.free();
decoder2.free();
decoder3.free();
assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// 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);
// Allocating a reader should remove a reader from the cache.
var reader = jspb.BinaryReader.alloc(buffer);
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// Processing the message reuses the current reader.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
});
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
});
assertEquals(false, reader.nextField());
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// Freeing the reader should put it back into the cache.
reader.free();
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(1, jspb.BinaryReader.instanceCache_.length);
});
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var temp = new Float32Array(1);
temp[0] = x;
return temp[0];
}
/**
* 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() {
reader.nextField();
assertThrows(function() {reader.readFixed32()});
});
// Skipping an invalid field should trigger an assertion.
reader = jspb.BinaryReader.alloc([12, 1]);
reader.nextWireType_ = 1000;
assertThrows(function() {reader.skipField()});
// 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()});
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()});
assertThrows(function() {reader.readString()});
assertThrows(function() {reader.readBytes()});
});
/**
* Tests encoding and decoding of unsigned field types.
* @param {Function} readField
* @param {Function} writeField
* @param {number} epsilon
* @param {number} upperLimit
* @param {Function} filter
* @private
* @suppress {missingProperties}
*/
var doTestUnsignedField_ = function(readField,
writeField, epsilon, upperLimit, filter) {
assertNotNull(readField);
assertNotNull(writeField);
var writer = new jspb.BinaryWriter();
// Encode zero and limits.
writeField.call(writer, 1, filter(0));
writeField.call(writer, 2, filter(epsilon));
writeField.call(writer, 3, filter(upperLimit));
// Encode positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
writeField.call(writer, 4, filter(cursor));
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Check zero and limits.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(filter(0), readField.call(reader));
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(filter(epsilon), readField.call(reader));
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(filter(upperLimit), readField.call(reader));
// Check positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
reader.nextField();
if (4 != reader.getFieldNumber()) throw 'fail!';
if (filter(cursor) != readField.call(reader)) throw 'fail!';
}
};
/**
* Tests encoding and decoding of signed field types.
* @param {Function} readField
* @param {Function} writeField
* @param {number} epsilon
* @param {number} lowerLimit
* @param {number} upperLimit
* @param {Function} filter
* @private
* @suppress {missingProperties}
*/
var doTestSignedField_ = function(readField,
writeField, epsilon, lowerLimit, upperLimit, filter) {
var writer = new jspb.BinaryWriter();
// Encode zero and limits.
writeField.call(writer, 1, filter(lowerLimit));
writeField.call(writer, 2, filter(-epsilon));
writeField.call(writer, 3, filter(0));
writeField.call(writer, 4, filter(epsilon));
writeField.call(writer, 5, filter(upperLimit));
var inputValues = [];
// Encode negative values.
for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
var 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);
writeField.call(writer, 7, val);
inputValues.push({
fieldNumber: 7,
value: val
});
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Check zero and limits.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(filter(lowerLimit), readField.call(reader));
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(filter(-epsilon), readField.call(reader));
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(filter(0), readField.call(reader));
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(filter(epsilon), readField.call(reader));
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(filter(upperLimit), readField.call(reader));
for (var i = 0; i < inputValues.length; i++) {
var expected = inputValues[i];
reader.nextField();
assertEquals(expected.fieldNumber, reader.getFieldNumber());
assertEquals(expected.value, readField.call(reader));
}
};
/**
* 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);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readUint32,
jspb.BinaryWriter.prototype.writeUint32,
1, Math.pow(2, 32) - 1, Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readUint64,
jspb.BinaryWriter.prototype.writeUint64,
1, Math.pow(2, 64) - 1025, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readInt32,
jspb.BinaryWriter.prototype.writeInt32,
1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readInt64,
jspb.BinaryWriter.prototype.writeInt64,
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readEnum,
jspb.BinaryWriter.prototype.writeEnum,
1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readBool,
jspb.BinaryWriter.prototype.writeBool,
1, 1, function(x) { return !!x; });
});
/**
* Tests reading a field from hexadecimal string (format: '08 BE EF').
* @param {Function} readField
* @param {number} expected
* @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++) {
bytes[i] = parseInt(hexString.substring(i * 3, i * 3 + 2), 16);
}
var reader = jspb.BinaryReader.alloc(bytes);
reader.nextField();
assertEquals(expected, readField.call(reader));
}
/**
* 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);
// uint32 and sint32 take no more than 5 bytes
// 08 - field prefix (type = 0 means varint)
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readUint32,
12, '08 8C 80 80 80 00');
// 11 stands for -6 in zigzag encoding
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readSint32,
-6, '08 8B 80 80 80 00');
// uint64 and sint64 take no more than 10 bytes
// 08 - field prefix (type = 0 means varint)
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readUint64,
12, '08 8C 80 80 80 80 80 80 80 80 00');
// 11 stands for -6 in zigzag encoding
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readSint64,
-6, '08 8B 80 80 80 80 80 80 80 80 00');
});
/**
* Tests 64-bit fields that are handled as strings.
*/
it('testStringInt64Fields', function() {
var writer = new jspb.BinaryWriter();
var testSignedData = [
'2730538252207801776',
'-2688470994844604560',
'3398529779486536359',
'3568577411627971000',
'272477188847484900',
'-6649058714086158188',
'-7695254765712060806',
'-4525541438037104029',
'-4993706538836508568',
'4990160321893729138'
];
var testUnsignedData = [
'7822732630241694882',
'6753602971916687352',
'2399935075244442116',
'8724292567325338867',
'16948784802625696584',
'4136275908516066934',
'3575388346793700364',
'5167142028379259461',
'1557573948689737699',
'17100725280812548567'
];
for (var 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());
for (var i = 0; i < testSignedData.length; i++) {
reader.nextField();
assertEquals(2 * i + 1, reader.getFieldNumber());
assertEquals(testSignedData[i], reader.readInt64String());
reader.nextField();
assertEquals(2 * i + 2, reader.getFieldNumber());
assertEquals(testUnsignedData[i], reader.readUint64String());
}
});
/**
* Tests fields that use zigzag encoding.
*/
it('testZigzagFields', function() {
doTestSignedField_(
jspb.BinaryReader.prototype.readSint32,
jspb.BinaryWriter.prototype.writeSint32,
1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSint64,
jspb.BinaryWriter.prototype.writeSint64,
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
});
/**
* Tests fields that use fixed-length encoding.
*/
it('testFixedFields', function() {
doTestUnsignedField_(
jspb.BinaryReader.prototype.readFixed32,
jspb.BinaryWriter.prototype.writeFixed32,
1, Math.pow(2, 32) - 1, Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readFixed64,
jspb.BinaryWriter.prototype.writeFixed64,
1, Math.pow(2, 64) - 1025, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSfixed32,
jspb.BinaryWriter.prototype.writeSfixed32,
1, -Math.pow(2, 31), Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSfixed64,
jspb.BinaryWriter.prototype.writeSfixed64,
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
});
/**
* Tests floating point fields.
*/
it('testFloatFields', function() {
doTestSignedField_(
jspb.BinaryReader.prototype.readFloat,
jspb.BinaryWriter.prototype.writeFloat,
jspb.BinaryConstants.FLOAT32_MIN,
-jspb.BinaryConstants.FLOAT32_MAX,
jspb.BinaryConstants.FLOAT32_MAX,
truncate);
doTestSignedField_(
jspb.BinaryReader.prototype.readDouble,
jspb.BinaryWriter.prototype.writeDouble,
jspb.BinaryConstants.FLOAT64_EPS * 10,
-jspb.BinaryConstants.FLOAT64_MIN,
jspb.BinaryConstants.FLOAT64_MIN,
function(x) { return x; });
});
/**
* Tests length-delimited string fields.
*/
it('testStringFields', function() {
var s1 = 'The quick brown fox jumps over the lazy dog.';
var s2 = '人人生而自由,在尊嚴和權利上一律平等。';
var writer = new jspb.BinaryWriter();
writer.writeString(1, s1);
writer.writeString(2, s2);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(s1, reader.readString());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(s2, reader.readString());
});
/**
* Tests length-delimited byte fields.
*/
it('testByteFields', function() {
var message = [];
var lowerLimit = 1;
var upperLimit = 256;
var scale = 1.1;
var 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);
writer.writeBytes(len, bytes);
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
for (var cursor = lowerLimit; reader.nextField(); cursor *= 1.1) {
var len = Math.round(cursor);
if (len != reader.getFieldNumber()) throw 'fail!';
var bytes = reader.readBytes();
if (len != bytes.length) throw 'fail!';
for (var i = 0; i < bytes.length; i++) {
if (i % 256 != bytes[i]) throw 'fail!';
}
}
});
/**
* Tests nested messages.
*/
it('testNesting', function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
writer.writeInt32(1, 100);
// Add one message with 3 int fields.
writer.writeMessage(2, dummyMessage, function() {
writer.writeInt32(3, 300);
writer.writeInt32(4, 400);
writer.writeInt32(5, 500);
});
// Add one empty message.
writer.writeMessage(6, dummyMessage, () => {});
writer.writeInt32(7, 700);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Validate outermost message.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(100, reader.readInt32());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Validate embedded message 1.
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(300, reader.readInt32());
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(400, reader.readInt32());
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(500, reader.readInt32());
assertEquals(false, reader.nextField());
});
reader.nextField();
assertEquals(6, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Validate embedded message 2.
assertEquals(false, reader.nextField());
});
reader.nextField();
assertEquals(7, reader.getFieldNumber());
assertEquals(700, reader.readInt32());
assertEquals(false, reader.nextField());
});
/**
* 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();
var sentinel = 123456789;
// Write varint fields of different sizes.
writer.writeInt32(1, sentinel);
writer.writeInt32(1, 1);
writer.writeInt32(1, 1000);
writer.writeInt32(1, 1000000);
writer.writeInt32(1, 1000000000);
// Write fixed 64-bit encoded fields.
writer.writeInt32(2, sentinel);
writer.writeDouble(2, 1);
writer.writeFixed64(2, 1);
writer.writeSfixed64(2, 1);
// Write fixed 32-bit encoded fields.
writer.writeInt32(3, sentinel);
writer.writeFloat(3, 1);
writer.writeFixed32(3, 1);
writer.writeSfixed32(3, 1);
// Write delimited fields.
writer.writeInt32(4, sentinel);
writer.writeBytes(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
writer.writeString(4, 'The quick brown fox jumps over the lazy dog');
// Write a group with a nested group inside.
writer.writeInt32(5, sentinel);
var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
writer.writeGroup(5, dummyMessage, function() {
writer.writeInt64(42, 42);
writer.writeGroup(6, dummyMessage, function() {
writer.writeInt64(84, 42);
});
});
// Write final sentinel.
writer.writeInt32(6, sentinel);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
function skip(field, count) {
for (var i = 0; i < count; i++) {
reader.nextField();
if (field != reader.getFieldNumber()) throw 'fail!';
reader.skipField();
}
}
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(1, 4);
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(2, 3);
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(3, 3);
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(4, 2);
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(5, 1);
reader.nextField();
assertEquals(6, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
});
/**
* Tests packed fields.
*/
it('testPackedFields', function() {
var writer = new jspb.BinaryWriter();
var 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];
for (var i = 0; i < floatData.length; i++) {
floatData[i] = truncate(floatData[i]);
}
writer.writeInt32(1, sentinel);
writer.writePackedInt32(2, signedData);
writer.writePackedInt64(2, signedData);
writer.writePackedUint32(2, unsignedData);
writer.writePackedUint64(2, unsignedData);
writer.writePackedSint32(2, signedData);
writer.writePackedSint64(2, signedData);
writer.writePackedFixed32(2, unsignedData);
writer.writePackedFixed64(2, unsignedData);
writer.writePackedSfixed32(2, signedData);
writer.writePackedSfixed64(2, signedData);
writer.writePackedFloat(2, floatData);
writer.writePackedDouble(2, doubleData);
writer.writePackedBool(2, boolData);
writer.writePackedEnum(2, unsignedData);
writer.writeInt32(3, sentinel);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
assertEquals(sentinel, reader.readInt32());
reader.nextField();
assertElementsEquals(reader.readPackedInt32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedInt64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedUint32(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedUint64(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedSint32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedSint64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedFixed32(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedFixed64(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedSfixed32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedSfixed64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedFloat(), floatData);
reader.nextField();
assertElementsEquals(reader.readPackedDouble(), doubleData);
reader.nextField();
assertElementsEquals(reader.readPackedBool(), boolData);
reader.nextField();
assertElementsEquals(reader.readPackedEnum(), unsignedData);
reader.nextField();
assertEquals(sentinel, reader.readInt32());
});
/**
* Byte blobs inside nested messages should always have their byte offset set
* relative to the start of the outermost blob, not the start of their parent
* blob.
*/
it('testNestedBlobs', function() {
// 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} */({});
writer.writeMessage(1, dummyMessage, function() {
writer.writeMessage(1, dummyMessage, function() {
writer.writeBytes(1, blob);
});
});
// Peel off the outer two message layers. Each layer should have two bytes
// 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());
var decoder2 = new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4));
assertEquals(fieldTag, decoder2.readUnsignedVarint32());
assertEquals(blob.length + 2, decoder2.readUnsignedVarint32());
assertEquals(fieldTag, decoder2.readUnsignedVarint32());
assertEquals(blob.length, decoder2.readUnsignedVarint32());
var bytes = decoder2.readBytes(blob.length);
assertElementsEquals(bytes, blob);
});
/**
* Tests read callbacks.
*/
it('testReadCallbacks', function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
// Add an int, a submessage, and another int.
writer.writeInt32(1, 100);
writer.writeMessage(2, dummyMessage, function() {
writer.writeInt32(3, 300);
writer.writeInt32(4, 400);
writer.writeInt32(5, 500);
});
writer.writeInt32(7, 700);
// Create the reader and register a custom read callback.
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
/**
* @param {!jspb.BinaryReader} reader
* @return {*}
*/
function readCallback(reader) {
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(300, reader.readInt32());
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(400, reader.readInt32());
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(500, reader.readInt32());
assertEquals(false, reader.nextField());
};
reader.registerReadCallback('readCallback', readCallback);
// Read the container message.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(100, reader.readInt32());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Decode the embedded message using the registered callback.
reader.runReadCallback('readCallback');
});
reader.nextField();
assertEquals(7, reader.getFieldNumber());
assertEquals(700, reader.readInt32());
assertEquals(false, reader.nextField());
});
});

View File

@ -1,668 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's helper functions.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryConstants');
goog.require('jspb.BinaryWriter');
goog.require('jspb.utils');
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var temp = new Float32Array(1);
temp[0] = x;
return temp[0];
}
/**
* Converts an 64-bit integer in split representation to a 64-bit hash string
* (8 bits encoded per character).
* @param {number} bitsLow The low 32 bits of the split 64-bit integer.
* @param {number} bitsHigh The high 32 bits of the split 64-bit integer.
* @return {string} The encoded hash string, 8 bits per character.
*/
function toHashString(bitsLow, bitsHigh) {
return String.fromCharCode((bitsLow >>> 0) & 0xFF,
(bitsLow >>> 8) & 0xFF,
(bitsLow >>> 16) & 0xFF,
(bitsLow >>> 24) & 0xFF,
(bitsHigh >>> 0) & 0xFF,
(bitsHigh >>> 8) & 0xFF,
(bitsHigh >>> 16) & 0xFF,
(bitsHigh >>> 24) & 0xFF);
}
describe('binaryUtilsTest', function() {
/**
* Tests lossless binary-to-decimal conversion.
*/
it('testDecimalConversion', function() {
// Check some magic numbers.
var result =
jspb.utils.joinUnsignedDecimalString(0x89e80001, 0x8ac72304);
assertEquals('10000000000000000001', result);
result = jspb.utils.joinUnsignedDecimalString(0xacd05f15, 0x1b69b4b);
assertEquals('123456789123456789', result);
result = jspb.utils.joinUnsignedDecimalString(0xeb1f0ad2, 0xab54a98c);
assertEquals('12345678901234567890', result);
result = jspb.utils.joinUnsignedDecimalString(0xe3b70cb1, 0x891087b8);
assertEquals('9876543210987654321', result);
// Check limits.
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00000000);
assertEquals('0', result);
result = jspb.utils.joinUnsignedDecimalString(0xFFFFFFFF, 0xFFFFFFFF);
assertEquals('18446744073709551615', result);
// Check each bit of the low dword.
for (var i = 0; i < 32; i++) {
var low = (1 << i) >>> 0;
result = jspb.utils.joinUnsignedDecimalString(low, 0);
assertEquals('' + Math.pow(2, i), result);
}
// Check the first 20 bits of the high dword.
for (var i = 0; i < 20; i++) {
var high = (1 << i) >>> 0;
result = jspb.utils.joinUnsignedDecimalString(0, high);
assertEquals('' + Math.pow(2, 32 + i), result);
}
// V8's internal double-to-string conversion is inaccurate for values above
// 2^52, even if they're representable integers - check the rest of the bits
// manually against the correct string representations of 2^N.
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00100000);
assertEquals('4503599627370496', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00200000);
assertEquals('9007199254740992', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00400000);
assertEquals('18014398509481984', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00800000);
assertEquals('36028797018963968', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x01000000);
assertEquals('72057594037927936', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x02000000);
assertEquals('144115188075855872', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x04000000);
assertEquals('288230376151711744', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x08000000);
assertEquals('576460752303423488', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x10000000);
assertEquals('1152921504606846976', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x20000000);
assertEquals('2305843009213693952', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x40000000);
assertEquals('4611686018427387904', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x80000000);
assertEquals('9223372036854775808', result);
});
/**
* Going from hash strings to decimal strings should also be lossless.
*/
it('testHashToDecimalConversion', function() {
var result;
var convert = jspb.utils.hash64ToDecimalString;
result = convert(toHashString(0x00000000, 0x00000000), false);
assertEquals('0', result);
result = convert(toHashString(0x00000000, 0x00000000), true);
assertEquals('0', result);
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), false);
assertEquals('18446744073709551615', result);
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), true);
assertEquals('-1', result);
result = convert(toHashString(0x00000000, 0x80000000), false);
assertEquals('9223372036854775808', result);
result = convert(toHashString(0x00000000, 0x80000000), true);
assertEquals('-9223372036854775808', result);
result = convert(toHashString(0xacd05f15, 0x01b69b4b), false);
assertEquals('123456789123456789', result);
result = convert(toHashString(~0xacd05f15 + 1, ~0x01b69b4b), true);
assertEquals('-123456789123456789', result);
// And converting arrays of hashes should work the same way.
result = jspb.utils.hash64ArrayToDecimalStrings([
toHashString(0xFFFFFFFF, 0xFFFFFFFF),
toHashString(0x00000000, 0x80000000),
toHashString(0xacd05f15, 0x01b69b4b)], false);
assertEquals(3, result.length);
assertEquals('18446744073709551615', result[0]);
assertEquals('9223372036854775808', result[1]);
assertEquals('123456789123456789', result[2]);
});
/*
* Going from decimal strings to hash strings should be lossless.
*/
it('testDecimalToHashConversion', function() {
var result;
var convert = jspb.utils.decimalStringToHash64;
result = convert('0');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
result = convert('-1');
assertEquals(String.fromCharCode.apply(null,
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
result = convert('18446744073709551615');
assertEquals(String.fromCharCode.apply(null,
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
result = convert('9223372036854775808');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
result = convert('-9223372036854775808');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
result = convert('123456789123456789');
assertEquals(String.fromCharCode.apply(null,
[0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]), result);
result = convert('-123456789123456789');
assertEquals(String.fromCharCode.apply(null,
[0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]), result);
});
/**
* Going from hash strings to hex strings should be lossless.
*/
it('testHashToHexConversion', function() {
var result;
var convert = jspb.utils.hash64ToHexString;
result = convert(toHashString(0x00000000, 0x00000000));
assertEquals('0x0000000000000000', result);
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF));
assertEquals('0xffffffffffffffff', result);
result = convert(toHashString(0x12345678, 0x9ABCDEF0));
assertEquals('0x9abcdef012345678', result);
});
/**
* Going from hex strings to hash strings should be lossless.
*/
it('testHexToHashConversion', function() {
var result;
var convert = jspb.utils.hexStringToHash64;
result = convert('0x0000000000000000');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
result = convert('0xffffffffffffffff');
assertEquals(String.fromCharCode.apply(null,
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
// Hex string is big-endian, hash string is little-endian.
result = convert('0x123456789ABCDEF0');
assertEquals(String.fromCharCode.apply(null,
[0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]), result);
// Capitalization should not matter.
result = convert('0x0000abcdefABCDEF');
assertEquals(String.fromCharCode.apply(null,
[0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]), result);
});
/**
* Going from numbers to hash strings should be lossless for up to 53 bits of
* precision.
*/
it('testNumberToHashConversion', function() {
var result;
var convert = jspb.utils.numberToHash64;
result = convert(0x0000000000000);
assertEquals('0x0000000000000000', jspb.utils.hash64ToHexString(result));
result = convert(0xFFFFFFFFFFFFF);
assertEquals('0x000fffffffffffff', jspb.utils.hash64ToHexString(result));
result = convert(0x123456789ABCD);
assertEquals('0x000123456789abcd', jspb.utils.hash64ToHexString(result));
result = convert(0xDCBA987654321);
assertEquals('0x000dcba987654321', jspb.utils.hash64ToHexString(result));
// 53 bits of precision should not be truncated.
result = convert(0x10000000000001);
assertEquals('0x0010000000000001', jspb.utils.hash64ToHexString(result));
// 54 bits of precision should be truncated.
result = convert(0x20000000000001);
assertNotEquals(
'0x0020000000000001', jspb.utils.hash64ToHexString(result));
});
/**
* Sanity check the behavior of Javascript's strings when doing funny things
* with unicode characters.
*/
it('sanityCheckUnicodeStrings', function() {
var strings = new Array(65536);
// All possible unsigned 16-bit values should be storable in a string, they
// shouldn't do weird things with the length of the string, and they should
// come back out of the string unchanged.
for (var i = 0; i < 65536; i++) {
strings[i] = 'a' + String.fromCharCode(i) + 'a';
if (3 != strings[i].length) throw 'fail!';
if (i != strings[i].charCodeAt(1)) throw 'fail!';
}
// Each unicode character should compare equal to itself and not equal to a
// different unicode character.
for (var i = 0; i < 65536; i++) {
if (strings[i] != strings[i]) throw 'fail!';
if (strings[i] == strings[(i + 1) % 65536]) throw 'fail!';
}
});
/**
* Tests conversion from 32-bit floating point numbers to split64 numbers.
*/
it('testFloat32ToSplit64', function() {
var f32_eps = jspb.BinaryConstants.FLOAT32_EPS;
var f32_min = jspb.BinaryConstants.FLOAT32_MIN;
var f32_max = jspb.BinaryConstants.FLOAT32_MAX;
// NaN.
jspb.utils.splitFloat32(NaN);
if (!isNaN(jspb.utils.joinFloat32(jspb.utils.split64Low,
jspb.utils.split64High))) {
throw 'fail!';
}
/**
* @param {number} x
* @param {number=} opt_bits
*/
function test(x, opt_bits) {
jspb.utils.splitFloat32(x);
if (opt_bits !== undefined) {
if (opt_bits != jspb.utils.split64Low) throw 'fail!';
}
if (truncate(x) != jspb.utils.joinFloat32(jspb.utils.split64Low,
jspb.utils.split64High)) {
throw 'fail!';
}
}
// Positive and negative infinity.
test(Infinity, 0x7f800000);
test(-Infinity, 0xff800000);
// Positive and negative zero.
test(0, 0x00000000);
test(-0, 0x80000000);
// Positive and negative epsilon.
test(f32_eps, 0x00000001);
test(-f32_eps, 0x80000001);
// Positive and negative min.
test(f32_min, 0x00800000);
test(-f32_min, 0x80800000);
// Positive and negative max.
test(f32_max, 0x7F7FFFFF);
test(-f32_max, 0xFF7FFFFF);
// Various positive values.
var cursor = f32_eps * 10;
while (cursor != Infinity) {
test(cursor);
cursor *= 1.1;
}
// Various negative values.
cursor = -f32_eps * 10;
while (cursor != -Infinity) {
test(cursor);
cursor *= 1.1;
}
});
/**
* Tests conversion from 64-bit floating point numbers to split64 numbers.
*/
it('testFloat64ToSplit64', function() {
var f64_eps = jspb.BinaryConstants.FLOAT64_EPS;
var f64_min = jspb.BinaryConstants.FLOAT64_MIN;
var f64_max = jspb.BinaryConstants.FLOAT64_MAX;
// NaN.
jspb.utils.splitFloat64(NaN);
if (!isNaN(jspb.utils.joinFloat64(jspb.utils.split64Low,
jspb.utils.split64High))) {
throw 'fail!';
}
/**
* @param {number} x
* @param {number=} opt_highBits
* @param {number=} opt_lowBits
*/
function test(x, opt_highBits, opt_lowBits) {
jspb.utils.splitFloat64(x);
if (opt_highBits !== undefined) {
if (opt_highBits != jspb.utils.split64High) throw 'fail!';
}
if (opt_lowBits !== undefined) {
if (opt_lowBits != jspb.utils.split64Low) throw 'fail!';
}
if (x != jspb.utils.joinFloat64(jspb.utils.split64Low,
jspb.utils.split64High)) {
throw 'fail!';
}
}
// Positive and negative infinity.
test(Infinity, 0x7ff00000, 0x00000000);
test(-Infinity, 0xfff00000, 0x00000000);
// Positive and negative zero.
test(0, 0x00000000, 0x00000000);
test(-0, 0x80000000, 0x00000000);
// Positive and negative epsilon.
test(f64_eps, 0x00000000, 0x00000001);
test(-f64_eps, 0x80000000, 0x00000001);
// Positive and negative min.
test(f64_min, 0x00100000, 0x00000000);
test(-f64_min, 0x80100000, 0x00000000);
// Positive and negative max.
test(f64_max, 0x7FEFFFFF, 0xFFFFFFFF);
test(-f64_max, 0xFFEFFFFF, 0xFFFFFFFF);
// Various positive values.
var cursor = f64_eps * 10;
while (cursor != Infinity) {
test(cursor);
cursor *= 1.1;
}
// Various negative values.
cursor = -f64_eps * 10;
while (cursor != -Infinity) {
test(cursor);
cursor *= 1.1;
}
});
/**
* Tests counting packed varints.
*/
it('testCountVarints', function() {
var values = [];
for (var i = 1; i < 1000000000; i *= 1.1) {
values.push(Math.floor(i));
}
var writer = new jspb.BinaryWriter();
writer.writePackedUint64(1, values);
var buffer = new Uint8Array(writer.getResultBuffer());
// We should have two more varints than we started with - one for the field
// tag, one for the packed length.
assertEquals(values.length + 2,
jspb.utils.countVarints(buffer, 0, buffer.length));
});
/**
* Tests counting matching varint fields.
*/
it('testCountVarintFields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeUint64(1, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countVarintFields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeUint64(123456789, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countVarintFields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests counting matching fixed32 fields.
*/
it('testCountFixed32Fields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeFixed32(1, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeFixed32(123456789, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests counting matching fixed64 fields.
*/
it('testCountFixed64Fields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeDouble(1, i);
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeDouble(123456789, i);
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests counting matching delimited fields.
*/
it('testCountDelimitedFields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000; i *= 1.1) {
writer.writeBytes(1, [Math.floor(i)]);
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000; i *= 1.1) {
writer.writeBytes(123456789, [Math.floor(i)]);
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests byte format for debug strings.
*/
it('testDebugBytesToTextFormat', function() {
assertEquals('""', jspb.utils.debugBytesToTextFormat(null));
assertEquals('"\\x00\\x10\\xff"',
jspb.utils.debugBytesToTextFormat([0, 16, 255]));
});
/**
* Tests converting byte blob sources into byte blobs.
*/
it('testByteSourceToUint8Array', function() {
var convert = jspb.utils.byteSourceToUint8Array;
var sourceData = [];
for (var i = 0; i < 256; i++) {
sourceData.push(i);
}
var sourceBytes = new Uint8Array(sourceData);
var sourceBuffer = sourceBytes.buffer;
var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
var sourceString = String.fromCharCode.apply(null, sourceData);
function check(result) {
assertEquals(Uint8Array, result.constructor);
assertEquals(sourceData.length, result.length);
for (var i = 0; i < result.length; i++) {
assertEquals(sourceData[i], result[i]);
}
}
// Converting Uint8Arrays into Uint8Arrays should be a no-op.
assertEquals(sourceBytes, convert(sourceBytes));
// Converting Array.<numbers> into Uint8Arrays should work.
check(convert(sourceData));
// Converting ArrayBuffers into Uint8Arrays should work.
check(convert(sourceBuffer));
// Converting base64-encoded strings into Uint8Arrays should work.
check(convert(sourceBase64));
});
});

View File

@ -1,122 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer writer. In
* practice BinaryWriter is used to drive the Decoder and Reader test cases,
* so only writer-specific tests are here.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.crypt');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryWriter');
/**
* @param {function()} func This function should throw an error when run.
*/
function assertFails(func) {
var e = assertThrows(func);
//assertNotNull(e.toString().match(/Error/));
}
describe('binaryWriterTest', function() {
/**
* Verifies that misuse of the writer class triggers assertions.
*/
it('testWriteErrors', function() {
// Submessages with invalid field indices should assert.
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */({});
assertFails(function() {
writer.writeMessage(-1, dummyMessage, () => {});
});
// Writing invalid field indices should assert.
writer = new jspb.BinaryWriter();
assertFails(function() {writer.writeUint64(-1, 1);});
// Writing out-of-range field values should assert.
writer = new jspb.BinaryWriter();
assertFails(function() {writer.writeInt32(1, -Infinity);});
assertFails(function() {writer.writeInt32(1, Infinity);});
assertFails(function() {writer.writeInt64(1, -Infinity);});
assertFails(function() {writer.writeInt64(1, Infinity);});
assertFails(function() {writer.writeUint32(1, -1);});
assertFails(function() {writer.writeUint32(1, Infinity);});
assertFails(function() {writer.writeUint64(1, -1);});
assertFails(function() {writer.writeUint64(1, Infinity);});
assertFails(function() {writer.writeSint32(1, -Infinity);});
assertFails(function() {writer.writeSint32(1, Infinity);});
assertFails(function() {writer.writeSint64(1, -Infinity);});
assertFails(function() {writer.writeSint64(1, Infinity);});
assertFails(function() {writer.writeFixed32(1, -1);});
assertFails(function() {writer.writeFixed32(1, Infinity);});
assertFails(function() {writer.writeFixed64(1, -1);});
assertFails(function() {writer.writeFixed64(1, Infinity);});
assertFails(function() {writer.writeSfixed32(1, -Infinity);});
assertFails(function() {writer.writeSfixed32(1, Infinity);});
assertFails(function() {writer.writeSfixed64(1, -Infinity);});
assertFails(function() {writer.writeSfixed64(1, Infinity);});
});
/**
* Basic test of retrieving the result as a Uint8Array buffer
*/
it('testGetResultBuffer', function() {
var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';
var writer = new jspb.BinaryWriter();
writer.writeUint32(1, 100);
writer.writeString(2, 'Hello world');
writer.writeBytes(3, new Uint8Array([1, 2, 3]));
writer.writeUint32(4, 200);
var buffer = writer.getResultBuffer();
assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
});
});

View File

@ -1,37 +0,0 @@
/**
* @fileoverview Exports symbols needed only by tests.
*
* This file exports several Closure Library symbols that are only
* used by tests. It is used to generate a file
* closure_asserts_commonjs.js that is only used at testing time.
*/
goog.require('goog.testing.asserts');
var global = Function('return this')();
// All of the closure "assert" functions are exported at the global level.
//
// The Google Closure assert functions start with assert, eg.
// assertThrows
// assertNotThrows
// assertTrue
// ...
//
// The one exception is the "fail" function.
function shouldExport(str) {
return str.lastIndexOf('assert') === 0 || str == 'fail';
}
for (var key in global) {
if ((typeof key == "string") && global.hasOwnProperty(key) &&
shouldExport(key)) {
exports[key] = global[key];
}
}
// The COMPILED variable is set by Closure compiler to "true" when it compiles
// JavaScript, so in practice this is equivalent to "exports.COMPILED = true".
// This will disable some debugging functionality in debug.js. We could
// investigate whether this can/should be enabled in CommonJS builds.
exports.COMPILED = COMPILED

View File

@ -1,18 +0,0 @@
/**
* @fileoverview Export symbols needed by tests in CommonJS style.
*
* This file is like export.js, but for symbols that are only used by tests.
* However we exclude assert functions here, because they are exported into
* the global namespace, so those are handled as a special case in
* export_asserts.js.
*/
goog.require('goog.crypt.base64');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
goog.require('jspb.BinaryEncoder');
goog.require('jspb.BinaryDecoder');
goog.require('jspb.utils');
exports.goog = goog;
exports.jspb = jspb;

View File

@ -1,52 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test suite is written using Jasmine -- see http://jasmine.github.io/
var googleProtobuf = require('google-protobuf');
var asserts = require('closure_asserts_commonjs');
var global = Function('return this')();
// Bring asserts into the global namespace.
googleProtobuf.object.extend(global, asserts);
googleProtobuf.exportSymbol('jspb.Message', googleProtobuf.Message, global);
var test7_pb = require('./test7/test7_pb');
googleProtobuf.exportSymbol('proto.jspb.test.framing.FramingMessage', test7_pb.FramingMessage, global);
describe('Import test suite', function() {
it('testImportedMessage', function() {
var framing1 = new proto.jspb.test.framing.FramingMessage([]);
var framing2 = new proto.jspb.test.framing.FramingMessage([]);
assertObjectEquals(framing1.toObject(), framing2.toObject());
});
});

View File

@ -1,9 +0,0 @@
{
"spec_dir": "",
"spec_files": [
"*_test.js",
"binary/proto_test.js"
],
"helpers": [
]
}

View File

@ -1,97 +0,0 @@
/**
* @fileoverview Utility to translate test files to CommonJS imports.
*
* This is a somewhat hacky tool designed to do one very specific thing.
* All of the test files in *_test.js are written with Closure-style
* imports (goog.require()). This works great for running the tests
* against Closure-style generated code, but we also want to run the
* tests against CommonJS-style generated code without having to fork
* the tests.
*
* Closure-style imports import each individual type by name. This is
* very different than CommonJS imports which are by file. So we put
* special comments in these tests like:
*
* // CommonJS-LoadFromFile: test_pb
* goog.require('proto.jspb.test.CloneExtension');
* goog.require('proto.jspb.test.Complex');
* goog.require('proto.jspb.test.DefaultValues');
*
* This script parses that special comment and uses it to generate proper
* CommonJS require() statements so that the tests can run and pass using
* CommonJS imports. The script will change the above statements into:
*
* var test_pb = require('test_pb');
* googleProtobuf.exportSymbol('proto.jspb.test.CloneExtension', test_pb.CloneExtension, global);
* googleProtobuf.exportSymbol('proto.jspb.test.Complex', test_pb.Complex, global);
* googleProtobuf.exportSymbol('proto.jspb.test.DefaultValues', test_pb.DefaultValues, global);
*
* (The "exportSymbol" function will define the given names in the global
* namespace, taking care not to overwrite any previous value for
* "proto.jspb.test").
*/
var lineReader = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
function tryStripPrefix(str, prefix) {
if (str.lastIndexOf(prefix) !== 0) {
throw "String: " + str + " didn't start with: " + prefix;
}
return str.substr(prefix.length);
}
function camelCase(str) {
var ret = '';
var ucaseNext = false;
for (var i = 0; i < str.length; i++) {
if (str[i] == '-') {
ucaseNext = true;
} else if (ucaseNext) {
ret += str[i].toUpperCase();
ucaseNext = false;
} else {
ret += str[i];
}
}
return ret;
}
var module = null;
var pkg = null;
// Header: goes in every file at the top.
console.log("var global = Function('return this')();");
console.log("var googleProtobuf = require('google-protobuf');");
console.log("var testdeps = require('testdeps_commonjs');");
console.log("global.goog = testdeps.goog;");
console.log("global.jspb = testdeps.jspb;");
console.log("var asserts = require('closure_asserts_commonjs');");
console.log("");
console.log("// Bring asserts into the global namespace.");
console.log("googleProtobuf.object.extend(global, asserts);");
lineReader.on('line', function(line) {
var isRequire = line.match(/goog\.require\('([^']*)'\)/);
var isLoadFromFile = line.match(/CommonJS-LoadFromFile: (\S*) (.*)/);
var isSetTestOnly = line.match(/goog.setTestOnly()/);
if (isRequire) {
if (module) { // Skip goog.require() lines before the first directive.
var fullSym = isRequire[1];
var sym = tryStripPrefix(fullSym, pkg);
console.log("googleProtobuf.exportSymbol('" + fullSym + "', " + module + sym + ', global);');
}
} else if (isLoadFromFile) {
var module_path = isLoadFromFile[1].split('/');
module = camelCase(module_path[module_path.length - 1]);
pkg = isLoadFromFile[2];
if (module != "googleProtobuf") { // We unconditionally require this in the header.
console.log("var " + module + " = require('./" + isLoadFromFile[1] + "');");
}
} else if (!isSetTestOnly) { // Remove goog.setTestOnly() lines.
console.log(line);
}
});

View File

@ -1,40 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test.importing;
message ImportedMessage {
string string_value = 1;
}

View File

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test.framing;
import "test6/test6.proto";
message FramingMessage {
jspb.test.importing.ImportedMessage imported_message = 1;
}

View File

@ -1,51 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: mwr@google.com (Mark Rawling)
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test;
// legacy data, must be nested
message data {
message NestedData {
required string str = 1;
}
}
// new data, does not require nesting
message UnnestedData {
required string str = 1;
}

View File

@ -1,105 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.setTestOnly();
goog.require('goog.testing.asserts');
// CommonJS-LoadFromFile: google-protobuf
goog.require('jspb.debug');
// CommonJS-LoadFromFile: test_pb
goog.require('proto.jspb.test.HasExtensions');
goog.require('proto.jspb.test.IsExtension');
goog.require('proto.jspb.test.Simple1');
describe('debugTest', function() {
it('testSimple1', function() {
if (COMPILED) {
return;
}
var message = new proto.jspb.test.Simple1();
message.setAString('foo');
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': []
}, jspb.debug.dump(message));
message.setABoolean(true);
message.setARepeatedStringList(['1', '2']);
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
message.setAString(undefined);
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
});
it('testExtensions', function() {
if (COMPILED) {
return;
}
var extension = new proto.jspb.test.IsExtension();
extension.setExt1('ext1field');
var extendable = new proto.jspb.test.HasExtensions();
extendable.setStr1('v1');
extendable.setStr2('v2');
extendable.setStr3('v3');
extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
assertObjectEquals({
'$name': 'proto.jspb.test.HasExtensions',
'str1': 'v1',
'str2': 'v2',
'str3': 'v3',
'$extensions': {
'extField': {
'$name': 'proto.jspb.test.IsExtension',
'ext1': 'ext1field'
},
'repeatedSimpleList': []
}
}, jspb.debug.dump(extendable));
});
});

View File

@ -1,17 +0,0 @@
{
"spec_dir": "",
"spec_files": [
"*_test.js",
"binary/*_test.js"
],
"helpers": [
"../../../js/node_modules/google-closure-library/closure/goog/bootstrap/nodejs.js",
"../../../js/node_loader.js",
"../../../js/deps.js",
"../../../js/google/protobuf/any.js",
"../../../js/google/protobuf/struct.js",
"../../../js/google/protobuf/timestamp.js",
"testproto_libs1.js",
"testproto_libs2.js"
]
}

View File

@ -1,17 +0,0 @@
{
"spec_dir": "",
"spec_files": [
"*_test.js",
"binary/*_test.js"
],
"helpers": [
"../../../js/node_modules/google-closure-library/closure/goog/bootstrap/nodejs.js",
"../../../js/node_loader.js",
"../../../js/deps.js",
"../../../js/google/protobuf/any.js",
"../../../js/google/protobuf/struct.js",
"../../../js/google/protobuf/timestamp.js",
"testproto_libs1_new.js",
"testproto_libs2.js"
]
}

View File

@ -1,17 +0,0 @@
{
"spec_dir": "",
"spec_files": [
"*_test.js",
"binary/*_test.js"
],
"helpers": [
"../../../js/node_modules/google-closure-library/closure/goog/bootstrap/nodejs.js",
"../../../js/node_loader.js",
"../../../js/deps.js",
"../../../js/google/protobuf/any.js",
"../../../js/google/protobuf/struct.js",
"../../../js/google/protobuf/timestamp.js",
"testproto_libs1.js",
"testproto_libs2_new.js"
]
}

File diff suppressed because it is too large Load Diff

View File

@ -1,329 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
goog.require('proto.jspb.test.ForeignMessage');
// CommonJS-LoadFromFile: proto3_test_pb proto.jspb.test
goog.require('proto.jspb.test.Proto3Enum');
goog.require('proto.jspb.test.TestProto3');
var BYTES = new Uint8Array([1, 2, 8, 9]);
var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
/**
* Helper: compare a bytes field to an expected value
* @param {Uint8Array|string} arr
* @param {Uint8Array} expected
* @return {boolean}
*/
function bytesCompare(arr, expected) {
if (typeof arr === 'string') {
arr = goog.crypt.base64.decodeStringToUint8Array(arr);
}
if (arr.length != expected.length) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] != expected[i]) {
return false;
}
}
return true;
}
describe('proto3Test', function() {
/**
* Test defaults for proto3 message fields.
*/
it('testProto3FieldDefaults', function() {
var msg = new proto.jspb.test.TestProto3();
assertEquals(msg.getOptionalInt32(), 0);
assertEquals(msg.getOptionalInt64(), 0);
assertEquals(msg.getOptionalUint32(), 0);
assertEquals(msg.getOptionalUint64(), 0);
assertEquals(msg.getOptionalSint32(), 0);
assertEquals(msg.getOptionalSint64(), 0);
assertEquals(msg.getOptionalFixed32(), 0);
assertEquals(msg.getOptionalFixed64(), 0);
assertEquals(msg.getOptionalSfixed32(), 0);
assertEquals(msg.getOptionalSfixed64(), 0);
assertEquals(msg.getOptionalFloat(), 0);
assertEquals(msg.getOptionalDouble(), 0);
assertEquals(msg.getOptionalString(), '');
// TODO(b/26173701): when we change bytes fields default getter to return
// Uint8Array, we'll want to switch this assertion to match the u8 case.
assertEquals(typeof msg.getOptionalBytes(), 'string');
assertEquals(msg.getOptionalBytes_asU8() instanceof Uint8Array, true);
assertEquals(typeof msg.getOptionalBytes_asB64(), 'string');
assertEquals(msg.getOptionalBytes().length, 0);
assertEquals(msg.getOptionalBytes_asU8().length, 0);
assertEquals(msg.getOptionalBytes_asB64(), '');
assertEquals(msg.getOptionalForeignEnum(),
proto.jspb.test.Proto3Enum.PROTO3_FOO);
assertEquals(msg.getOptionalForeignMessage(), undefined);
assertEquals(msg.getOptionalForeignMessage(), undefined);
assertEquals(msg.getRepeatedInt32List().length, 0);
assertEquals(msg.getRepeatedInt64List().length, 0);
assertEquals(msg.getRepeatedUint32List().length, 0);
assertEquals(msg.getRepeatedUint64List().length, 0);
assertEquals(msg.getRepeatedSint32List().length, 0);
assertEquals(msg.getRepeatedSint64List().length, 0);
assertEquals(msg.getRepeatedFixed32List().length, 0);
assertEquals(msg.getRepeatedFixed64List().length, 0);
assertEquals(msg.getRepeatedSfixed32List().length, 0);
assertEquals(msg.getRepeatedSfixed64List().length, 0);
assertEquals(msg.getRepeatedFloatList().length, 0);
assertEquals(msg.getRepeatedDoubleList().length, 0);
assertEquals(msg.getRepeatedStringList().length, 0);
assertEquals(msg.getRepeatedBytesList().length, 0);
assertEquals(msg.getRepeatedForeignEnumList().length, 0);
assertEquals(msg.getRepeatedForeignMessageList().length, 0);
});
/**
* Test that all fields can be set and read via a serialization roundtrip.
*/
it('testProto3FieldSetGet', function() {
var msg = new proto.jspb.test.TestProto3();
msg.setOptionalInt32(-42);
msg.setOptionalInt64(-0x7fffffff00000000);
msg.setOptionalUint32(0x80000000);
msg.setOptionalUint64(0xf000000000000000);
msg.setOptionalSint32(-100);
msg.setOptionalSint64(-0x8000000000000000);
msg.setOptionalFixed32(1234);
msg.setOptionalFixed64(0x1234567800000000);
msg.setOptionalSfixed32(-1234);
msg.setOptionalSfixed64(-0x1234567800000000);
msg.setOptionalFloat(1.5);
msg.setOptionalDouble(-1.5);
msg.setOptionalBool(true);
msg.setOptionalString('hello world');
msg.setOptionalBytes(BYTES);
var submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(16);
msg.setOptionalForeignMessage(submsg);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
msg.setRepeatedInt32List([-42]);
msg.setRepeatedInt64List([-0x7fffffff00000000]);
msg.setRepeatedUint32List([0x80000000]);
msg.setRepeatedUint64List([0xf000000000000000]);
msg.setRepeatedSint32List([-100]);
msg.setRepeatedSint64List([-0x8000000000000000]);
msg.setRepeatedFixed32List([1234]);
msg.setRepeatedFixed64List([0x1234567800000000]);
msg.setRepeatedSfixed32List([-1234]);
msg.setRepeatedSfixed64List([-0x1234567800000000]);
msg.setRepeatedFloatList([1.5]);
msg.setRepeatedDoubleList([-1.5]);
msg.setRepeatedBoolList([true]);
msg.setRepeatedStringList(['hello world']);
msg.setRepeatedBytesList([BYTES]);
submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(1000);
msg.setRepeatedForeignMessageList([submsg]);
msg.setRepeatedForeignEnumList([proto.jspb.test.Proto3Enum.PROTO3_BAR]);
msg.setOneofString('asdf');
var serialized = msg.serializeBinary();
msg = proto.jspb.test.TestProto3.deserializeBinary(serialized);
assertEquals(msg.getOptionalInt32(), -42);
assertEquals(msg.getOptionalInt64(), -0x7fffffff00000000);
assertEquals(msg.getOptionalUint32(), 0x80000000);
assertEquals(msg.getOptionalUint64(), 0xf000000000000000);
assertEquals(msg.getOptionalSint32(), -100);
assertEquals(msg.getOptionalSint64(), -0x8000000000000000);
assertEquals(msg.getOptionalFixed32(), 1234);
assertEquals(msg.getOptionalFixed64(), 0x1234567800000000);
assertEquals(msg.getOptionalSfixed32(), -1234);
assertEquals(msg.getOptionalSfixed64(), -0x1234567800000000);
assertEquals(msg.getOptionalFloat(), 1.5);
assertEquals(msg.getOptionalDouble(), -1.5);
assertEquals(msg.getOptionalBool(), true);
assertEquals(msg.getOptionalString(), 'hello world');
assertEquals(true, bytesCompare(msg.getOptionalBytes(), BYTES));
assertEquals(msg.getOptionalForeignMessage().getC(), 16);
assertEquals(msg.getOptionalForeignEnum(),
proto.jspb.test.Proto3Enum.PROTO3_BAR);
assertElementsEquals(msg.getRepeatedInt32List(), [-42]);
assertElementsEquals(msg.getRepeatedInt64List(), [-0x7fffffff00000000]);
assertElementsEquals(msg.getRepeatedUint32List(), [0x80000000]);
assertElementsEquals(msg.getRepeatedUint64List(), [0xf000000000000000]);
assertElementsEquals(msg.getRepeatedSint32List(), [-100]);
assertElementsEquals(msg.getRepeatedSint64List(), [-0x8000000000000000]);
assertElementsEquals(msg.getRepeatedFixed32List(), [1234]);
assertElementsEquals(msg.getRepeatedFixed64List(), [0x1234567800000000]);
assertElementsEquals(msg.getRepeatedSfixed32List(), [-1234]);
assertElementsEquals(msg.getRepeatedSfixed64List(), [-0x1234567800000000]);
assertElementsEquals(msg.getRepeatedFloatList(), [1.5]);
assertElementsEquals(msg.getRepeatedDoubleList(), [-1.5]);
assertElementsEquals(msg.getRepeatedBoolList(), [true]);
assertElementsEquals(msg.getRepeatedStringList(), ['hello world']);
assertEquals(msg.getRepeatedBytesList().length, 1);
assertEquals(true, bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
assertEquals(msg.getRepeatedForeignMessageList().length, 1);
assertEquals(msg.getRepeatedForeignMessageList()[0].getC(), 1000);
assertElementsEquals(msg.getRepeatedForeignEnumList(),
[proto.jspb.test.Proto3Enum.PROTO3_BAR]);
assertEquals(msg.getOneofString(), 'asdf');
});
/**
* Test that oneofs continue to have a notion of field presence.
*/
it('testOneofs', function() {
var msg = new proto.jspb.test.TestProto3();
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
assertFalse(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
msg.setOneofUint32(42);
assertEquals(msg.getOneofUint32(), 42);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
assertTrue(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
var submsg = new proto.jspb.test.ForeignMessage();
msg.setOneofForeignMessage(submsg);
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), submsg);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
assertFalse(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
msg.setOneofString('hello');
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), 'hello');
assertEquals(msg.getOneofBytes(), '');
assertFalse(msg.hasOneofUint32());
assertTrue(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes_asB64(),
goog.crypt.base64.encodeString('\u00FF\u00FF'));
assertFalse(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertTrue(msg.hasOneofBytes());
});
/**
* Test that "default"-valued primitive fields are not emitted on the wire.
*/
it('testNoSerializeDefaults', function() {
var msg = new proto.jspb.test.TestProto3();
// Set each primitive to a non-default value, then back to its default, to
// ensure that the serialization is actually checking the value and not just
// whether it has ever been set.
msg.setOptionalInt32(42);
msg.setOptionalInt32(0);
msg.setOptionalDouble(3.14);
msg.setOptionalDouble(0.0);
msg.setOptionalBool(true);
msg.setOptionalBool(false);
msg.setOptionalString('hello world');
msg.setOptionalString('');
msg.setOptionalBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
msg.setOptionalBytes('');
msg.setOptionalForeignMessage(new proto.jspb.test.ForeignMessage());
msg.setOptionalForeignMessage(null);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO);
msg.setOneofUint32(32);
msg.setOneofUint32(null);
var serialized = msg.serializeBinary();
assertEquals(0, serialized.length);
});
/**
* Test that base64 string and Uint8Array are interchangeable in bytes fields.
*/
it('testBytesFieldsInterop', function() {
var msg = new proto.jspb.test.TestProto3();
// Set as 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));
// Test binary serialize round trip doesn't break it.
msg = proto.jspb.test.TestProto3.deserializeBinary(msg.serializeBinary());
assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg = new proto.jspb.test.TestProto3();
// Set as 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));
});
});

View File

@ -1,89 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
import "testbinary.proto";
package jspb.test;
message TestProto3 {
int32 optional_int32 = 1;
int64 optional_int64 = 2;
uint32 optional_uint32 = 3;
uint64 optional_uint64 = 4;
sint32 optional_sint32 = 5;
sint64 optional_sint64 = 6;
fixed32 optional_fixed32 = 7;
fixed64 optional_fixed64 = 8;
sfixed32 optional_sfixed32 = 9;
sfixed64 optional_sfixed64 = 10;
float optional_float = 11;
double optional_double = 12;
bool optional_bool = 13;
string optional_string = 14;
bytes optional_bytes = 15;
ForeignMessage optional_foreign_message = 19;
Proto3Enum optional_foreign_enum = 22;
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated ForeignMessage repeated_foreign_message = 49;
repeated Proto3Enum repeated_foreign_enum = 52;
oneof oneof_field {
uint32 oneof_uint32 = 111;
ForeignMessage oneof_foreign_message = 112;
string oneof_string = 113;
bytes oneof_bytes = 114;
}
}
enum Proto3Enum {
PROTO3_FOO = 0;
PROTO3_BAR = 1;
PROTO3_BAZ = 2;
}

View File

@ -1,236 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: mwr@google.com (Mark Rawling)
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
import "google/protobuf/descriptor.proto";
package jspb.test;
message Empty {
}
enum OuterEnum {
FOO = 1;
BAR = 2;
}
message EnumContainer {
optional OuterEnum outer_enum = 1;
}
message Simple1 {
required string a_string = 1;
repeated string a_repeated_string = 2;
optional bool a_boolean = 3;
}
// A message that differs from Simple1 only by name
message Simple2 {
required string a_string = 1;
repeated string a_repeated_string = 2;
}
message SpecialCases {
required string normal = 1;
// Examples of Js reserved names that are converted to pb_<name>.
required string default = 2;
required string function = 3;
required string var = 4;
}
message OptionalFields {
message Nested {
optional int32 an_int = 1;
}
optional string a_string = 1;
required bool a_bool = 2;
optional Nested a_nested_message = 3;
repeated Nested a_repeated_message = 4;
repeated string a_repeated_string = 5;
}
message HasExtensions {
optional string str1 = 1;
optional string str2 = 2;
optional string str3 = 3;
extensions 10 to max;
}
message Complex {
message Nested {
required int32 an_int = 2;
}
required string a_string = 1;
required bool an_out_of_order_bool = 9;
optional Nested a_nested_message = 4;
repeated Nested a_repeated_message = 5;
repeated string a_repeated_string = 7;
}
message OuterMessage {
// Make sure this doesn't conflict with the other Complex message.
message Complex {
optional int32 inner_complex_field = 1;
}
}
message IsExtension {
extend HasExtensions {
optional IsExtension ext_field = 100;
}
optional string ext1 = 1;
// Extensions of proto2 Descriptor messages will be ignored.
extend google.protobuf.EnumOptions {
optional string simple_option = 42113038;
}
}
message IndirectExtension {
extend HasExtensions {
optional Simple1 simple = 101;
optional string str = 102;
repeated string repeated_str = 103;
repeated Simple1 repeated_simple = 104;
}
}
extend HasExtensions {
optional Simple1 simple1 = 105;
}
message DefaultValues {
enum Enum {
E1 = 13;
E2 = 77;
}
optional string string_field = 1 [default="default<>\'\"abc"];
optional bool bool_field = 2 [default=true];
optional int64 int_field = 3 [default=11];
optional Enum enum_field = 4 [default=E1];
optional string empty_field = 6 [default=""];
optional bytes bytes_field = 8 [default="moo"]; // Base64 encoding is "bW9v"
}
message FloatingPointFields {
optional float optional_float_field = 1;
required float required_float_field = 2;
repeated float repeated_float_field = 3;
optional float default_float_field = 4 [default = 2.0];
optional double optional_double_field = 5;
required double required_double_field = 6;
repeated double repeated_double_field = 7;
optional double default_double_field = 8 [default = 2.0];
}
message TestClone {
optional string str = 1;
optional Simple1 simple1 = 3;
repeated Simple1 simple2 = 5;
optional bytes bytes_field = 6;
optional string unused = 7;
extensions 10 to max;
}
message CloneExtension {
extend TestClone {
optional CloneExtension ext_field = 100;
}
optional string ext = 2;
}
message TestGroup {
repeated group RepeatedGroup = 1 {
required string id = 1;
repeated bool some_bool = 2;
}
required group RequiredGroup = 2 {
required string id = 1;
}
optional group OptionalGroup = 3 {
required string id = 1;
}
optional string id = 4;
required Simple2 required_simple = 5;
optional Simple2 optional_simple = 6;
}
message TestGroup1 {
optional TestGroup.RepeatedGroup group = 1;
}
message TestReservedNames {
optional int32 extension = 1;
extensions 10 to max;
}
message TestReservedNamesExtension {
extend TestReservedNames {
optional int32 foo = 10;
}
}
message TestMessageWithOneof {
oneof partial_oneof {
string pone = 3;
string pthree = 5;
}
oneof recursive_oneof {
TestMessageWithOneof rone = 6;
string rtwo = 7;
}
optional bool normal_field = 8;
repeated string repeated_field = 9;
oneof default_oneof_a {
int32 aone = 10 [default = 1234];
int32 atwo = 11;
}
oneof default_oneof_b {
int32 bone = 12;
int32 btwo = 13 [default = 1234];
}
}
message TestEndsWithBytes {
optional int32 value = 1;
optional bytes data = 2;
}

View File

@ -1,104 +0,0 @@
#!/bin/bash
set -e
# Download protoc 3.0.0 from Maven if it is not already present.
OLD_PROTOC_URL=https://repo1.maven.org/maven2/com/google/protobuf/protoc/3.0.0/protoc-3.0.0-linux-x86_64.exe
if [ ! -f protoc ]; then
wget $OLD_PROTOC_URL -O protoc
chmod +x protoc
fi
pushd ../..
npm install && npm test
popd
old_protoc=./protoc
new_protoc=../../../src/protoc
# The protos in group 2 have some dependencies on protos in group 1. The tests
# will verify that the generated code for one group can be regenerated
# independently of the other group in a compatible way.
#
# Note: these lists of protos duplicate the lists in gulpfile.js. Ideally we
# should find a good way of having a single source of truth for this.
group1_protos="data.proto test3.proto test5.proto commonjs/test6/test6.proto testbinary.proto testempty.proto test.proto"
group2_protos="proto3_test.proto test2.proto test4.proto commonjs/test7/test7.proto"
# We test the following cases:
#
# Case 1: build groups 1 and 2 with the old protoc
# Case 2: build group 1 with new protoc but group 2 with old protoc
# Case 3: build group 1 with old protoc but group 2 with new protoc
#
# In each case, we use the current runtime.
#
# CommonJS tests
#
mkdir -p commonjs_out{1,2,3}
# Case 1
$old_protoc --js_out=import_style=commonjs,binary:commonjs_out1 -I ../../../src -I commonjs -I . $group1_protos
$old_protoc --js_out=import_style=commonjs,binary:commonjs_out1 -I ../../../src -I commonjs -I . $group2_protos
# Case 2
$new_protoc --js_out=import_style=commonjs,binary:commonjs_out2 -I ../../../src -I commonjs -I . $group1_protos
$old_protoc --js_out=import_style=commonjs,binary:commonjs_out2 -I ../../../src -I commonjs -I . $group2_protos
# Case 3
$old_protoc --js_out=import_style=commonjs,binary:commonjs_out3 -I ../../../src -I commonjs -I . $group1_protos
$new_protoc --js_out=import_style=commonjs,binary:commonjs_out3 -I ../../../src -I commonjs -I . $group2_protos
mkdir -p commonjs_out/binary
for file in *_test.js binary/*_test.js; do
node commonjs/rewrite_tests_for_commonjs.js < "$file" > "commonjs_out/$file"
done
cp commonjs/{jasmine.json,import_test.js} commonjs_out/
mkdir -p commonjs_out/test_node_modules
../../node_modules/.bin/google-closure-compiler \
--entry_point=commonjs/export_asserts.js \
--js=commonjs/export_asserts.js \
--js=../../node_modules/google-closure-library/closure/goog/**.js \
--js=../../node_modules/google-closure-library/third_party/closure/goog/**.js \
> commonjs_out/test_node_modules/closure_asserts_commonjs.js
../../node_modules/.bin/google-closure-compiler \
--entry_point=commonjs/export_testdeps.js \
--js=commonjs/export_testdeps.js \
--js=../../binary/*.js \
--js=!../../binary/*_test.js \
--js=../../node_modules/google-closure-library/closure/goog/**.js \
--js=../../node_modules/google-closure-library/third_party/closure/goog/**.js \
> commonjs_out/test_node_modules/testdeps_commonjs.js
cp ../../google-protobuf.js commonjs_out/test_node_modules
cp -r ../../commonjs_out/node_modules commonjs_out
echo
echo "Running tests with CommonJS imports"
echo "-----------------------------------"
for i in 1 2 3; do
cp -r commonjs_out/* "commonjs_out$i"
pushd "commonjs_out$i"
JASMINE_CONFIG_PATH=jasmine.json NODE_PATH=test_node_modules ../../../node_modules/.bin/jasmine
popd
done
#
# Closure tests
#
$old_protoc --js_out=library=testproto_libs1,binary:. -I ../../../src -I commonjs -I . $group1_protos
$old_protoc --js_out=library=testproto_libs2,binary:. -I ../../../src -I commonjs -I . $group2_protos
$new_protoc --js_out=library=testproto_libs1_new,binary:. -I ../../../src -I commonjs -I . $group1_protos
$new_protoc --js_out=library=testproto_libs2_new,binary:. -I ../../../src -I commonjs -I . $group2_protos
echo
echo "Running tests with Closure-style imports"
echo "----------------------------------------"
# Case 1
JASMINE_CONFIG_PATH=jasmine1.json ../../node_modules/.bin/jasmine
# Case 2
JASMINE_CONFIG_PATH=jasmine2.json ../../node_modules/.bin/jasmine
# Case 3
JASMINE_CONFIG_PATH=jasmine3.json ../../node_modules/.bin/jasmine
# Remove these files so that calcdeps.py does not get confused by them the next
# time this script runs.
rm testproto_libs[12]*

View File

@ -1,54 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test;
message TestExtensionsMessage {
optional int32 intfield = 1;
extensions 100 to max;
}
message ExtensionMessage {
extend TestExtensionsMessage {
optional ExtensionMessage ext_field = 100;
}
optional string ext1 = 1;
}
// Floating extensions are only supported when generating a _lib.js library.
extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field = 101;
optional string floating_str_field = 102;
}

View File

@ -1,53 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.exttest;
message TestExtensionsMessage {
optional int32 intfield = 1;
extensions 100 to max;
}
message ExtensionMessage {
extend TestExtensionsMessage {
optional ExtensionMessage ext_field = 100;
}
optional string ext1 = 1;
}
extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field = 101;
optional string floating_str_field = 102;
}

View File

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.exttest;
import "test3.proto";
extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field_two = 103;
}

View File

@ -1,44 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.exttest.beta;
message TestBetaExtensionsMessage {
extensions 100 to max;
}
extend TestBetaExtensionsMessage {
optional string floating_str_field = 101;
}

View File

@ -1,212 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// LINT: ALLOW_GROUPS
syntax = "proto2";
package jspb.test;
// These types are borrowed from `unittest.proto` in the protobuf tree. We want
// to ensure that the binary-format support will handle all field types
// properly.
message TestAllTypes {
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional ForeignMessage optional_foreign_message = 19;
optional ForeignEnum optional_foreign_enum = 22;
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated ForeignMessage repeated_foreign_message = 49;
repeated ForeignEnum repeated_foreign_enum = 52;
// Packed repeated
repeated int32 packed_repeated_int32 = 61 [packed=true];
repeated int64 packed_repeated_int64 = 62 [packed=true];
repeated uint32 packed_repeated_uint32 = 63 [packed=true];
repeated uint64 packed_repeated_uint64 = 64 [packed=true];
repeated sint32 packed_repeated_sint32 = 65 [packed=true];
repeated sint64 packed_repeated_sint64 = 66 [packed=true];
repeated fixed32 packed_repeated_fixed32 = 67 [packed=true];
repeated fixed64 packed_repeated_fixed64 = 68 [packed=true];
repeated sfixed32 packed_repeated_sfixed32 = 69 [packed=true];
repeated sfixed64 packed_repeated_sfixed64 = 70 [packed=true];
repeated float packed_repeated_float = 71 [packed=true];
repeated double packed_repeated_double = 72 [packed=true];
repeated bool packed_repeated_bool = 73 [packed=true];
oneof oneof_field {
uint32 oneof_uint32 = 111;
ForeignMessage oneof_foreign_message = 112;
string oneof_string = 113;
bytes oneof_bytes = 114;
}
}
message ForeignMessage {
optional int32 c = 1;
}
enum ForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}
message TestExtendable {
extensions 1 to max;
}
message ExtendsWithMessage {
extend TestExtendable {
optional ExtendsWithMessage optional_extension = 19;
repeated ExtendsWithMessage repeated_extension = 49;
}
optional int32 foo = 1;
}
extend TestExtendable {
optional int32 extend_optional_int32 = 1;
optional int64 extend_optional_int64 = 2;
optional uint32 extend_optional_uint32 = 3;
optional uint64 extend_optional_uint64 = 4;
optional sint32 extend_optional_sint32 = 5;
optional sint64 extend_optional_sint64 = 6;
optional fixed32 extend_optional_fixed32 = 7;
optional fixed64 extend_optional_fixed64 = 8;
optional sfixed32 extend_optional_sfixed32 = 9;
optional sfixed64 extend_optional_sfixed64 = 10;
optional float extend_optional_float = 11;
optional double extend_optional_double = 12;
optional bool extend_optional_bool = 13;
optional string extend_optional_string = 14;
optional bytes extend_optional_bytes = 15;
optional ForeignEnum extend_optional_foreign_enum = 22;
repeated int32 extend_repeated_int32 = 31;
repeated int64 extend_repeated_int64 = 32;
repeated uint32 extend_repeated_uint32 = 33;
repeated uint64 extend_repeated_uint64 = 34;
repeated sint32 extend_repeated_sint32 = 35;
repeated sint64 extend_repeated_sint64 = 36;
repeated fixed32 extend_repeated_fixed32 = 37;
repeated fixed64 extend_repeated_fixed64 = 38;
repeated sfixed32 extend_repeated_sfixed32 = 39;
repeated sfixed64 extend_repeated_sfixed64 = 40;
repeated float extend_repeated_float = 41;
repeated double extend_repeated_double = 42;
repeated bool extend_repeated_bool = 43;
repeated string extend_repeated_string = 44;
repeated bytes extend_repeated_bytes = 45;
repeated ForeignEnum extend_repeated_foreign_enum = 52;
repeated int32 extend_packed_repeated_int32 = 61 [packed=true];
repeated int64 extend_packed_repeated_int64 = 62 [packed=true];
repeated uint32 extend_packed_repeated_uint32 = 63 [packed=true];
repeated uint64 extend_packed_repeated_uint64 = 64 [packed=true];
repeated sint32 extend_packed_repeated_sint32 = 65 [packed=true];
repeated sint64 extend_packed_repeated_sint64 = 66 [packed=true];
repeated fixed32 extend_packed_repeated_fixed32 = 67 [packed=true];
repeated fixed64 extend_packed_repeated_fixed64 = 68 [packed=true];
repeated sfixed32 extend_packed_repeated_sfixed32 = 69 [packed=true];
repeated sfixed64 extend_packed_repeated_sfixed64 = 70 [packed=true];
repeated float extend_packed_repeated_float = 71 [packed=true];
repeated double extend_packed_repeated_double = 72 [packed=true];
repeated bool extend_packed_repeated_bool = 73 [packed=true];
repeated ForeignEnum extend_packed_repeated_foreign_enum = 82
[packed=true];
}
message TestMapFields {
map<string, string> map_string_string = 1;
map<string, int32> map_string_int32 = 2;
map<string, int64> map_string_int64 = 3;
map<string, bool> map_string_bool = 4;
map<string, double> map_string_double = 5;
map<string, MapValueEnum> map_string_enum = 6;
map<string, MapValueMessage> map_string_msg = 7;
map<int32, string> map_int32_string = 8;
map<int64, string> map_int64_string = 9;
map<bool, string> map_bool_string = 10;
optional TestMapFields test_map_fields = 11;
map<string, TestMapFields> map_string_testmapfields = 12;
}
enum MapValueEnum {
MAP_VALUE_FOO = 0;
MAP_VALUE_BAR = 1;
MAP_VALUE_BAZ = 2;
}
message MapValueMessage {
optional int32 foo = 1;
}

View File

@ -1,34 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
package javatests.com.google.apps.jspb;

View File

@ -1,355 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for Int64-manipulation functions.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author cfallin@google.com (Chris Fallin)
*/
goog.require('goog.testing.asserts');
goog.require('jspb.arith.Int64');
goog.require('jspb.arith.UInt64');
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);
assertEquals(a.cmp(b), 0);
assertEquals(b.cmp(a), 0);
b.lo -= 1;
assertEquals(a.cmp(b), 1);
assertEquals(b.cmp(a), -1);
b.lo += 2;
assertEquals(a.cmp(b), -1);
assertEquals(b.cmp(a), 1);
b.lo = a.lo;
b.hi = a.hi - 1;
assertEquals(a.cmp(b), 1);
assertEquals(b.cmp(a), -1);
assertEquals(a.zero(), false);
assertEquals(a.msb(), false);
assertEquals(a.lsb(), false);
a.hi = 0;
a.lo = 0;
assertEquals(a.zero(), true);
a.hi = 0x80000000;
assertEquals(a.zero(), false);
assertEquals(a.msb(), true);
a.lo = 0x00000001;
assertEquals(a.lsb(), true);
});
/**
* Tests shifts.
*/
it('testShifts', function() {
var a = new jspb.arith.UInt64(1, 0);
assertEquals(a.lo, 1);
assertEquals(a.hi, 0);
var orig = a;
a = a.leftShift();
assertEquals(orig.lo, 1); // original unmodified.
assertEquals(orig.hi, 0);
assertEquals(a.lo, 2);
assertEquals(a.hi, 0);
a = a.leftShift();
assertEquals(a.lo, 4);
assertEquals(a.hi, 0);
for (var i = 0; i < 29; i++) {
a = a.leftShift();
}
assertEquals(a.lo, 0x80000000);
assertEquals(a.hi, 0);
a = a.leftShift();
assertEquals(a.lo, 0);
assertEquals(a.hi, 1);
a = a.leftShift();
assertEquals(a.lo, 0);
assertEquals(a.hi, 2);
a = a.rightShift();
a = a.rightShift();
assertEquals(a.lo, 0x80000000);
assertEquals(a.hi, 0);
a = a.rightShift();
assertEquals(a.lo, 0x40000000);
assertEquals(a.hi, 0);
});
/**
* 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);
// Addition with carry.
var c = a.add(b);
assertEquals(a.lo, 0x89abcdef); // originals unmodified.
assertEquals(a.hi, 0x01234567);
assertEquals(b.lo, 0xff52ab91);
assertEquals(b.hi, 0x92fa2123);
assertEquals(c.lo, 0x88fe7980);
assertEquals(c.hi, 0x941d668b);
// Simple addition without carry.
a.lo = 2;
a.hi = 0;
b.lo = 3;
b.hi = 0;
c = a.add(b);
assertEquals(c.lo, 5);
assertEquals(c.hi, 0);
});
/**
* 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);
assertEquals(c.hi, a.hi);
assertEquals(c.lo, a.lo);
}
}
});
/**
* Tests 32-by-32 multiplication.
*/
it('testMul32x32', function() {
var testData = [
// a b low(a*b) high(a*b)
[0xc0abe2f8, 0x1607898a, 0x5de711b0, 0x109471b8],
[0x915eb3cb, 0x4fb66d0e, 0xbd0d441a, 0x2d43d0bc],
[0xfe4efe70, 0x80b48c37, 0xbcddea10, 0x7fdada0c],
[0xe222fd4a, 0xe43d524a, 0xd5e0eb64, 0xc99d549c],
[0xd171f469, 0xb94ebd01, 0x4be17969, 0x979bc4fa],
[0x829cc1df, 0xe2598b38, 0xf4157dc8, 0x737c12ad],
[0xf10c3767, 0x8382881e, 0x942b3612, 0x7bd428b8],
[0xb0f6dd24, 0x232597e1, 0x079c98a4, 0x184bbce7],
[0xfcdb05a7, 0x902f55bc, 0x636199a4, 0x8e69f412],
[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);
assertEquals(c.lo, cLow);
assertEquals(c.hi, cHigh);
}
});
/**
* Tests 64-by-32 multiplication.
*/
it('testMul', 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 = [
// low(a) high(a) low(a*b) high(a*b)
[0xec10955b, 0x360eb168, 0x4b7f3f5b, 0xbfcb7c59, 0x9517da5f],
[0x42b000fc, 0x9d101642, 0x6fa1ab72, 0x2584c438, 0x6a9e6d2b],
[0xf42d4fb4, 0xae366403, 0xa65a1000, 0x92434000, 0x1ff978df],
[0x17e2f56b, 0x25487693, 0xf13f98c7, 0x73794e2d, 0xa96b0c6a],
[0x492f241f, 0x76c0eb67, 0x7377ac44, 0xd4336c3c, 0xfc4b1ebe],
[0xd6b92321, 0xe184fa48, 0xd6e76904, 0x93141584, 0xcbf44da1],
[0x4bf007ea, 0x968c0a9e, 0xf5e4026a, 0x4fdb1ae4, 0x61b9fb7d],
[0x10a83be7, 0x2d685ba6, 0xc9e5fb7f, 0x2ad43499, 0x3742473d],
[0x2f261829, 0x1aca681a, 0x3d3494e3, 0x8213205b, 0x283719f8],
[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]);
assertEquals(prod.lo, testData[i][3]);
assertEquals(prod.hi, testData[i][4]);
}
});
/**
* Tests 64-div-by-32 division.
*/
it('testDiv', function() {
// Compute a/b, yielding quot = a/b and rem = a%b.
var 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],
[0x11912915, 0xb2699eb5, 0x30467cbe, 0xb21b4be4, 0x00000003, 0x283465dd],
[0x0d917982, 0x201f2a6e, 0x3f35bf03, 0x8217c8e4, 0x00000000, 0x153402d6],
[0xa072c108, 0x74020c96, 0xc60568fd, 0x95f9613e, 0x00000000, 0x3f4676c2],
[0xd845d5d8, 0xcdd235c4, 0x20426475, 0x6154e78b, 0x00000006, 0x202fb751],
[0xa4dbf71f, 0x9e90465e, 0xf08e022f, 0xa8be947f, 0x00000000, 0xbe43b5ce],
[0x3dbe627f, 0xa791f4b9, 0x28a5bd89, 0x1f5dfe93, 0x00000004, 0x02bf9ed4],
[0x5c1c53ee, 0xccf5102e, 0x198576e7, 0x07e3ae31, 0x00000008, 0x02ea8fb7],
[0xfef1e581, 0x04714067, 0xca6540c1, 0x059e73ec, 0x00000000, 0x31658095],
[0x1e2dd90c, 0x13dd6667, 0x8b2184c3, 0x248d1a42, 0x00000000, 0x4ca6d0c6],
// --- divisors in (0, 2^16-1) to test larger quotient high-words
// low(a) high(a) b low(quot) high(quot) rem
[0x86722b47, 0x2cd57c9a, 0x00003123, 0x2ae41b7a, 0x0000e995, 0x00000f99],
[0x1dd7884c, 0xf5e839bc, 0x00009eeb, 0x5c886242, 0x00018c21, 0x000099b6],
[0x5c53d625, 0x899fc7e5, 0x000087d7, 0xd625007a, 0x0001035c, 0x000019af],
[0x6932d932, 0x9d0a5488, 0x000051fb, 0x9d976143, 0x0001ea63, 0x00004981],
[0x4d18bb85, 0x0c92fb31, 0x00001d9f, 0x03265ab4, 0x00006cac, 0x000001b9],
[0xbe756768, 0xdea67ccb, 0x00008a03, 0x58add442, 0x00019cff, 0x000056a2],
[0xe2466f9a, 0x2521f114, 0x0000c350, 0xa0c0860d, 0x000030ab, 0x0000a48a],
[0xf00ddad1, 0xe2f5446a, 0x00002cfc, 0x762697a6, 0x00050b96, 0x00000b69],
[0xa879152a, 0x0a70e0a5, 0x00007cdf, 0xb44151b3, 0x00001567, 0x0000363d],
[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];
assertEquals(quotient.lo, testData[i][3]);
assertEquals(quotient.hi, testData[i][4]);
assertEquals(remainder.lo, testData[i][5]);
}
});
/**
* 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']
];
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());
assertEquals(roundtrip.lo, a.lo);
assertEquals(roundtrip.hi, a.hi);
assertEquals(a.toString(), testData[i][2]);
}
});
/**
* Tests signed Int64s. These are built on UInt64s, so we only need to test
* 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'
];
for (var i = 0; i < testStrings.length; i++) {
var roundtrip =
jspb.arith.Int64.fromString(testStrings[i]).toString();
assertEquals(roundtrip, testStrings[i]);
}
});
});

View File

@ -1,327 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer decoder.
*
* There are two particular magic numbers that need to be pointed out -
* 2^64-1025 is the largest number representable as both a double and an
* unsigned 64-bit integer, and 2^63-513 is the largest number representable as
* both a double and a signed 64-bit integer.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryConstants');
goog.require('jspb.BinaryDecoder');
goog.require('jspb.BinaryEncoder');
/**
* Tests encoding and decoding of unsigned types.
* @param {Function} readValue
* @param {Function} writeValue
* @param {number} epsilon
* @param {number} upperLimit
* @param {Function} filter
* @suppress {missingProperties|visibility}
*/
function doTestUnsignedValue(readValue,
writeValue, epsilon, upperLimit, filter) {
var encoder = new jspb.BinaryEncoder();
// Encode zero and limits.
writeValue.call(encoder, filter(0));
writeValue.call(encoder, filter(epsilon));
writeValue.call(encoder, filter(upperLimit));
// Encode positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
writeValue.call(encoder, filter(cursor));
}
var 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));
// Check positive values.
for (var 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);});
}
/**
* Tests encoding and decoding of signed types.
* @param {Function} readValue
* @param {Function} writeValue
* @param {number} epsilon
* @param {number} lowerLimit
* @param {number} upperLimit
* @param {Function} filter
* @suppress {missingProperties}
*/
function doTestSignedValue(readValue,
writeValue, epsilon, lowerLimit, upperLimit, filter) {
var encoder = new jspb.BinaryEncoder();
// Encode zero and limits.
writeValue.call(encoder, filter(lowerLimit));
writeValue.call(encoder, filter(-epsilon));
writeValue.call(encoder, filter(0));
writeValue.call(encoder, filter(epsilon));
writeValue.call(encoder, filter(upperLimit));
var inputValues = [];
// Encode negative values.
for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
var 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);
writeValue.call(encoder, val);
inputValues.push(val);
}
var 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));
// Verify decoded values.
for (var i = 0; i < inputValues.length; i++) {
assertEquals(inputValues[i], readValue.call(decoder));
}
// Encoding values outside the valid range should assert, except for doubles
// whose range runs all the way to infinity.
var pastLowerLimit = lowerLimit * 1.1;
var pastUpperLimit = upperLimit * 1.1;
if (pastLowerLimit !== -Infinity) {
expect(function() {
writeValue.call(encoder, lowerLimit * 1.1);
}).toThrow();
}
if (pastUpperLimit !== Infinity) {
expect(function() {
writeValue.call(encoder, upperLimit * 1.1);
}).toThrow();
}
}
describe('binaryDecoderTest', function() {
/**
* Tests the decoder instance cache.
*/
it('testInstanceCache', /** @suppress {visibility} */ function() {
// Empty the instance caches.
jspb.BinaryDecoder.instanceCache_ = [];
// Allocating and then freeing a decoder should put it in the instance
// cache.
jspb.BinaryDecoder.alloc().free();
assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
// 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();
decoder1.free();
decoder2.free();
decoder3.free();
assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
});
/**
* Tests reading 64-bit integers as hash strings.
*/
it('testHashStrings', function() {
var encoder = new jspb.BinaryEncoder();
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);
encoder.writeVarintHash64(hashA);
encoder.writeVarintHash64(hashB);
encoder.writeVarintHash64(hashC);
encoder.writeVarintHash64(hashD);
encoder.writeFixedHash64(hashA);
encoder.writeFixedHash64(hashB);
encoder.writeFixedHash64(hashC);
encoder.writeFixedHash64(hashD);
var decoder = jspb.BinaryDecoder.alloc(encoder.end());
assertEquals(hashA, decoder.readVarintHash64());
assertEquals(hashB, decoder.readVarintHash64());
assertEquals(hashC, decoder.readVarintHash64());
assertEquals(hashD, decoder.readVarintHash64());
assertEquals(hashA, decoder.readFixedHash64());
assertEquals(hashB, decoder.readFixedHash64());
assertEquals(hashC, decoder.readFixedHash64());
assertEquals(hashD, decoder.readFixedHash64());
});
/**
* Verifies that misuse of the decoder class triggers assertions.
*/
it('testDecodeErrors', function() {
// 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()});
// Overlong varints should trigger assertions.
decoder.setBlock([255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0]);
assertThrows(function() {decoder.readUnsignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readSignedVarint64()});
decoder.reset();
assertThrows(function() {decoder.readZigzagVarint64()});
decoder.reset();
assertThrows(function() {decoder.readUnsignedVarint32()});
});
/**
* Tests encoding and decoding of unsigned integers.
*/
it('testUnsignedIntegers', function() {
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint8,
jspb.BinaryEncoder.prototype.writeUint8,
1, 0xFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint16,
jspb.BinaryEncoder.prototype.writeUint16,
1, 0xFFFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint32,
jspb.BinaryEncoder.prototype.writeUint32,
1, 0xFFFFFFFF, Math.round);
doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint64,
jspb.BinaryEncoder.prototype.writeUint64,
1, Math.pow(2, 64) - 1025, Math.round);
});
/**
* Tests encoding and decoding of signed integers.
*/
it('testSignedIntegers', function() {
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt8,
jspb.BinaryEncoder.prototype.writeInt8,
1, -0x80, 0x7F, Math.round);
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt16,
jspb.BinaryEncoder.prototype.writeInt16,
1, -0x8000, 0x7FFF, Math.round);
doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt32,
jspb.BinaryEncoder.prototype.writeInt32,
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);
});
/**
* Tests encoding and decoding of floats.
*/
it('testFloats', function() {
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var 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);
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; });
});
});

View File

@ -1,628 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Test suite is written using Jasmine -- see http://jasmine.github.io/
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
goog.require('jspb.Message');
// CommonJS-LoadFromFile: ../testbinary_pb proto.jspb.test
goog.require('proto.jspb.test.ExtendsWithMessage');
goog.require('proto.jspb.test.ForeignEnum');
goog.require('proto.jspb.test.ForeignMessage');
goog.require('proto.jspb.test.TestAllTypes');
goog.require('proto.jspb.test.TestExtendable');
goog.require('proto.jspb.test.extendOptionalBool');
goog.require('proto.jspb.test.extendOptionalBytes');
goog.require('proto.jspb.test.extendOptionalDouble');
goog.require('proto.jspb.test.extendOptionalFixed32');
goog.require('proto.jspb.test.extendOptionalFixed64');
goog.require('proto.jspb.test.extendOptionalFloat');
goog.require('proto.jspb.test.extendOptionalForeignEnum');
goog.require('proto.jspb.test.extendOptionalInt32');
goog.require('proto.jspb.test.extendOptionalInt64');
goog.require('proto.jspb.test.extendOptionalSfixed32');
goog.require('proto.jspb.test.extendOptionalSfixed64');
goog.require('proto.jspb.test.extendOptionalSint32');
goog.require('proto.jspb.test.extendOptionalSint64');
goog.require('proto.jspb.test.extendOptionalString');
goog.require('proto.jspb.test.extendOptionalUint32');
goog.require('proto.jspb.test.extendOptionalUint64');
goog.require('proto.jspb.test.extendPackedRepeatedBoolList');
goog.require('proto.jspb.test.extendPackedRepeatedDoubleList');
goog.require('proto.jspb.test.extendPackedRepeatedFixed32List');
goog.require('proto.jspb.test.extendPackedRepeatedFixed64List');
goog.require('proto.jspb.test.extendPackedRepeatedFloatList');
goog.require('proto.jspb.test.extendPackedRepeatedForeignEnumList');
goog.require('proto.jspb.test.extendPackedRepeatedInt32List');
goog.require('proto.jspb.test.extendPackedRepeatedInt64List');
goog.require('proto.jspb.test.extendPackedRepeatedSfixed32List');
goog.require('proto.jspb.test.extendPackedRepeatedSfixed64List');
goog.require('proto.jspb.test.extendPackedRepeatedSint32List');
goog.require('proto.jspb.test.extendPackedRepeatedSint64List');
goog.require('proto.jspb.test.extendPackedRepeatedUint32List');
goog.require('proto.jspb.test.extendPackedRepeatedUint64List');
goog.require('proto.jspb.test.extendRepeatedBoolList');
goog.require('proto.jspb.test.extendRepeatedBytesList');
goog.require('proto.jspb.test.extendRepeatedDoubleList');
goog.require('proto.jspb.test.extendRepeatedFixed32List');
goog.require('proto.jspb.test.extendRepeatedFixed64List');
goog.require('proto.jspb.test.extendRepeatedFloatList');
goog.require('proto.jspb.test.extendRepeatedForeignEnumList');
goog.require('proto.jspb.test.extendRepeatedInt32List');
goog.require('proto.jspb.test.extendRepeatedInt64List');
goog.require('proto.jspb.test.extendRepeatedSfixed32List');
goog.require('proto.jspb.test.extendRepeatedSfixed64List');
goog.require('proto.jspb.test.extendRepeatedSint32List');
goog.require('proto.jspb.test.extendRepeatedSint64List');
goog.require('proto.jspb.test.extendRepeatedStringList');
goog.require('proto.jspb.test.extendRepeatedUint32List');
goog.require('proto.jspb.test.extendRepeatedUint64List');
var suite = {};
var BYTES = new Uint8Array([1, 2, 8, 9]);
var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
/**
* Helper: fill all fields on a TestAllTypes message.
* @param {proto.jspb.test.TestAllTypes} msg
*/
function fillAllFields(msg) {
msg.setOptionalInt32(-42);
// can be exactly represented by JS number (64-bit double, i.e., 52-bit
// mantissa).
msg.setOptionalInt64(-0x7fffffff00000000);
msg.setOptionalUint32(0x80000000);
msg.setOptionalUint64(0xf000000000000000);
msg.setOptionalSint32(-100);
msg.setOptionalSint64(-0x8000000000000000);
msg.setOptionalFixed32(1234);
msg.setOptionalFixed64(0x1234567800000000);
msg.setOptionalSfixed32(-1234);
msg.setOptionalSfixed64(-0x1234567800000000);
msg.setOptionalFloat(1.5);
msg.setOptionalDouble(-1.5);
msg.setOptionalBool(true);
msg.setOptionalString('hello world');
msg.setOptionalBytes(BYTES);
msg.setOptionalGroup(new proto.jspb.test.TestAllTypes.OptionalGroup());
msg.getOptionalGroup().setA(100);
var submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(16);
msg.setOptionalForeignMessage(submsg);
msg.setOptionalForeignEnum(proto.jspb.test.ForeignEnum.FOREIGN_FOO);
msg.setOneofString('oneof');
msg.setRepeatedInt32List([-42]);
msg.setRepeatedInt64List([-0x7fffffff00000000]);
msg.setRepeatedUint32List([0x80000000]);
msg.setRepeatedUint64List([0xf000000000000000]);
msg.setRepeatedSint32List([-100]);
msg.setRepeatedSint64List([-0x8000000000000000]);
msg.setRepeatedFixed32List([1234]);
msg.setRepeatedFixed64List([0x1234567800000000]);
msg.setRepeatedSfixed32List([-1234]);
msg.setRepeatedSfixed64List([-0x1234567800000000]);
msg.setRepeatedFloatList([1.5]);
msg.setRepeatedDoubleList([-1.5]);
msg.setRepeatedBoolList([true]);
msg.setRepeatedStringList(['hello world']);
msg.setRepeatedBytesList([BYTES, BYTES]);
msg.setRepeatedGroupList([new proto.jspb.test.TestAllTypes.RepeatedGroup()]);
msg.getRepeatedGroupList()[0].setA(100);
submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(1000);
msg.setRepeatedForeignMessageList([submsg]);
msg.setRepeatedForeignEnumList([proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
msg.setPackedRepeatedInt32List([-42]);
msg.setPackedRepeatedInt64List([-0x7fffffff00000000]);
msg.setPackedRepeatedUint32List([0x80000000]);
msg.setPackedRepeatedUint64List([0xf000000000000000]);
msg.setPackedRepeatedSint32List([-100]);
msg.setPackedRepeatedSint64List([-0x8000000000000000]);
msg.setPackedRepeatedFixed32List([1234]);
msg.setPackedRepeatedFixed64List([0x1234567800000000]);
msg.setPackedRepeatedSfixed32List([-1234]);
msg.setPackedRepeatedSfixed64List([-0x1234567800000000]);
msg.setPackedRepeatedFloatList([1.5]);
msg.setPackedRepeatedDoubleList([-1.5]);
msg.setPackedRepeatedBoolList([true]);
}
/**
* Helper: compare a bytes field to an expected value
* @param {Uint8Array|string} arr
* @param {Uint8Array} expected
* @return {boolean}
*/
function bytesCompare(arr, expected) {
if (typeof arr === 'string') {
arr = goog.crypt.base64.decodeStringToUint8Array(arr);
}
if (arr.length != expected.length) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] != expected[i]) {
return false;
}
}
return true;
}
/**
* Helper: verify contents of given TestAllTypes message as set by
* fillAllFields().
* @param {proto.jspb.test.TestAllTypes} original
* @param {proto.jspb.test.TestAllTypes} copy
*/
function checkAllFields(original, copy) {
assertTrue(jspb.Message.equals(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]);
}
/**
* Helper: verify that all expected extensions are present.
* @param {!proto.jspb.test.TestExtendable} msg
*/
function checkExtensions(msg) {
assertEquals(-42,
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,
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,
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]);
}
describe('protoBinaryTest', function() {
/**
* 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();
fillAllFields(msg);
var encoded = msg.serializeBinary();
var 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();
// 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));
// 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));
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));
});
/**
* Test that bytes setters will receive result of any of the getters.
*/
it('testBytesFieldsSettersInterop', function() {
var msg = new proto.jspb.test.TestAllTypes();
msg.setOptionalBytes(BYTES);
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes_asB64());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg.setOptionalBytes(msg.getOptionalBytes_asU8());
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
});
/**
* Test that bytes setters will receive result of any of the getters.
*/
it('testRepeatedBytesGetters', function() {
var 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));
}
msg.setRepeatedBytesList([BYTES, BYTES]);
assertGetters();
msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
assertGetters();
msg.setRepeatedBytesList([]);
assertEquals(0, msg.getRepeatedBytesList().length);
assertEquals(0, msg.getRepeatedBytesList_asB64().length);
assertEquals(0, msg.getRepeatedBytesList_asU8().length);
});
/**
* Helper: fill all extension values.
* @param {proto.jspb.test.TestExtendable} msg
*/
function fillExtensions(msg) {
msg.setExtension(
proto.jspb.test.extendOptionalInt32, -42);
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.extendOptionalBytes, BYTES);
var submsg = new proto.jspb.test.ExtendsWithMessage();
submsg.setFoo(16);
msg.setExtension(
proto.jspb.test.ExtendsWithMessage.optionalExtension, submsg);
msg.setExtension(
proto.jspb.test.extendOptionalForeignEnum,
proto.jspb.test.ForeignEnum.FOREIGN_FOO);
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.extendRepeatedUint64List, [0xf000000000000000]);
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.extendRepeatedFixed64List, [0x1234567800000000]);
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.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,
[proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
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.extendPackedRepeatedSint64List, [-0x8000000000000000]);
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.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.extendPackedRepeatedForeignEnumList,
[proto.jspb.test.ForeignEnum.FOREIGN_FOO]);
}
/**
* Tests extension serialization and deserialization.
*/
it('testExtensions', function() {
var msg = new proto.jspb.test.TestExtendable();
fillExtensions(msg);
var encoded = msg.serializeBinary();
var decoded = proto.jspb.test.TestExtendable.deserializeBinary(encoded);
checkExtensions(decoded);
});
});

View File

@ -1,946 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer reader.
*
* There are two particular magic numbers that need to be pointed out -
* 2^64-1025 is the largest number representable as both a double and an
* unsigned 64-bit integer, and 2^63-513 is the largest number representable as
* both a double and a signed 64-bit integer.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @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.requireType('jspb.BinaryMessage');
describe('binaryReaderTest', function() {
/**
* Tests the reader instance cache.
*/
it('testInstanceCaches', /** @suppress {visibility} */ function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
writer.writeMessage(1, dummyMessage, () => {});
writer.writeMessage(2, dummyMessage, () => {});
var buffer = writer.getResultBuffer();
// Empty the instance caches.
jspb.BinaryReader.instanceCache_ = [];
// 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();
decoder1.free();
decoder2.free();
decoder3.free();
assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// 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);
// Allocating a reader should remove a reader from the cache.
var reader = jspb.BinaryReader.alloc(buffer);
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// Processing the message reuses the current reader.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
});
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
});
assertEquals(false, reader.nextField());
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(0, jspb.BinaryReader.instanceCache_.length);
// Freeing the reader should put it back into the cache.
reader.free();
assertEquals(2, jspb.BinaryDecoder.instanceCache_.length);
assertEquals(1, jspb.BinaryReader.instanceCache_.length);
});
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var temp = new Float32Array(1);
temp[0] = x;
return temp[0];
}
/**
* 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() {
reader.nextField();
assertThrows(function() {
reader.readFixed32()
});
});
// Skipping an invalid field should trigger an assertion.
reader = jspb.BinaryReader.alloc([12, 1]);
reader.nextWireType_ = 1000;
assertThrows(function() {
reader.skipField()
});
// 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()
});
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()
});
assertThrows(function() {
reader.readString()
});
assertThrows(function() {
reader.readBytes()
});
});
/**
* Tests encoding and decoding of unsigned field types.
* @param {Function} readField
* @param {Function} writeField
* @param {number} epsilon
* @param {number} upperLimit
* @param {Function} filter
* @private
* @suppress {missingProperties}
*/
var doTestUnsignedField_ = function(
readField, writeField, epsilon, upperLimit, filter) {
assertNotNull(readField);
assertNotNull(writeField);
var writer = new jspb.BinaryWriter();
// Encode zero and limits.
writeField.call(writer, 1, filter(0));
writeField.call(writer, 2, filter(epsilon));
writeField.call(writer, 3, filter(upperLimit));
// Encode positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
writeField.call(writer, 4, filter(cursor));
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Check zero and limits.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(filter(0), readField.call(reader));
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(filter(epsilon), readField.call(reader));
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(filter(upperLimit), readField.call(reader));
// Check positive values.
for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
reader.nextField();
if (4 != reader.getFieldNumber()) throw 'fail!';
if (filter(cursor) != readField.call(reader)) throw 'fail!';
}
};
/**
* Tests encoding and decoding of signed field types.
* @param {Function} readField
* @param {Function} writeField
* @param {number} epsilon
* @param {number} lowerLimit
* @param {number} upperLimit
* @param {Function} filter
* @private
* @suppress {missingProperties}
*/
var doTestSignedField_ = function(
readField, writeField, epsilon, lowerLimit, upperLimit, filter) {
var writer = new jspb.BinaryWriter();
// Encode zero and limits.
writeField.call(writer, 1, filter(lowerLimit));
writeField.call(writer, 2, filter(-epsilon));
writeField.call(writer, 3, filter(0));
writeField.call(writer, 4, filter(epsilon));
writeField.call(writer, 5, filter(upperLimit));
var inputValues = [];
// Encode negative values.
for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
var 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);
writeField.call(writer, 7, val);
inputValues.push({fieldNumber: 7, value: val});
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Check zero and limits.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(filter(lowerLimit), readField.call(reader));
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(filter(-epsilon), readField.call(reader));
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(filter(0), readField.call(reader));
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(filter(epsilon), readField.call(reader));
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(filter(upperLimit), readField.call(reader));
for (var i = 0; i < inputValues.length; i++) {
var expected = inputValues[i];
reader.nextField();
assertEquals(expected.fieldNumber, reader.getFieldNumber());
assertEquals(expected.value, readField.call(reader));
}
};
/**
* 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);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readUint32,
jspb.BinaryWriter.prototype.writeUint32, 1, Math.pow(2, 32) - 1,
Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readUint64,
jspb.BinaryWriter.prototype.writeUint64, 1, Math.pow(2, 64) - 1025,
Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readInt32,
jspb.BinaryWriter.prototype.writeInt32, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readInt64,
jspb.BinaryWriter.prototype.writeInt64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readEnum,
jspb.BinaryWriter.prototype.writeEnum, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readBool,
jspb.BinaryWriter.prototype.writeBool, 1, 1, function(x) {
return !!x;
});
});
/**
* Tests reading a field from hexadecimal string (format: '08 BE EF').
* @param {Function} readField
* @param {number} expected
* @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++) {
bytes[i] = parseInt(hexString.substring(i * 3, i * 3 + 2), 16);
}
var reader = jspb.BinaryReader.alloc(bytes);
reader.nextField();
assertEquals(expected, readField.call(reader));
}
/**
* 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);
// uint32 and sint32 take no more than 5 bytes
// 08 - field prefix (type = 0 means varint)
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readUint32, 12, '08 8C 80 80 80 00');
// 11 stands for -6 in zigzag encoding
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readSint32, -6, '08 8B 80 80 80 00');
// uint64 and sint64 take no more than 10 bytes
// 08 - field prefix (type = 0 means varint)
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readUint64, 12,
'08 8C 80 80 80 80 80 80 80 80 00');
// 11 stands for -6 in zigzag encoding
doTestHexStringVarint_(
jspb.BinaryReader.prototype.readSint64, -6,
'08 8B 80 80 80 80 80 80 80 80 00');
});
/**
* Tests 64-bit fields that are handled as strings.
*/
it('testStringInt64Fields', function() {
var writer = new jspb.BinaryWriter();
var testSignedData = [
'2730538252207801776', '-2688470994844604560', '3398529779486536359',
'3568577411627971000', '272477188847484900', '-6649058714086158188',
'-7695254765712060806', '-4525541438037104029', '-4993706538836508568',
'4990160321893729138'
];
var testUnsignedData = [
'7822732630241694882', '6753602971916687352', '2399935075244442116',
'8724292567325338867', '16948784802625696584', '4136275908516066934',
'3575388346793700364', '5167142028379259461', '1557573948689737699',
'17100725280812548567'
];
for (var 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());
for (var i = 0; i < testSignedData.length; i++) {
reader.nextField();
assertEquals(2 * i + 1, reader.getFieldNumber());
assertEquals(testSignedData[i], reader.readInt64String());
reader.nextField();
assertEquals(2 * i + 2, reader.getFieldNumber());
assertEquals(testUnsignedData[i], reader.readUint64String());
}
});
/**
* Tests fields that use zigzag encoding.
*/
it('testZigzagFields', function() {
doTestSignedField_(
jspb.BinaryReader.prototype.readSint32,
jspb.BinaryWriter.prototype.writeSint32, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSint64,
jspb.BinaryWriter.prototype.writeSint64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, Math.round);
});
/**
* Tests fields that use fixed-length encoding.
*/
it('testFixedFields', function() {
doTestUnsignedField_(
jspb.BinaryReader.prototype.readFixed32,
jspb.BinaryWriter.prototype.writeFixed32, 1, Math.pow(2, 32) - 1,
Math.round);
doTestUnsignedField_(
jspb.BinaryReader.prototype.readFixed64,
jspb.BinaryWriter.prototype.writeFixed64, 1, Math.pow(2, 64) - 1025,
Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSfixed32,
jspb.BinaryWriter.prototype.writeSfixed32, 1, -Math.pow(2, 31),
Math.pow(2, 31) - 1, Math.round);
doTestSignedField_(
jspb.BinaryReader.prototype.readSfixed64,
jspb.BinaryWriter.prototype.writeSfixed64, 1, -Math.pow(2, 63),
Math.pow(2, 63) - 513, Math.round);
});
/**
* Tests floating point fields.
*/
it('testFloatFields', function() {
doTestSignedField_(
jspb.BinaryReader.prototype.readFloat,
jspb.BinaryWriter.prototype.writeFloat,
jspb.BinaryConstants.FLOAT32_MIN, -jspb.BinaryConstants.FLOAT32_MAX,
jspb.BinaryConstants.FLOAT32_MAX, truncate);
doTestSignedField_(
jspb.BinaryReader.prototype.readDouble,
jspb.BinaryWriter.prototype.writeDouble,
jspb.BinaryConstants.FLOAT64_EPS * 10,
-jspb.BinaryConstants.FLOAT64_MIN, jspb.BinaryConstants.FLOAT64_MIN,
function(x) {
return x;
});
});
/**
* Tests length-delimited string fields.
*/
it('testStringFields', function() {
var s1 = 'The quick brown fox jumps over the lazy dog.';
var s2 = '人人生而自由,在尊嚴和權利上一律平等。';
var writer = new jspb.BinaryWriter();
writer.writeString(1, s1);
writer.writeString(2, s2);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(s1, reader.readString());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(s2, reader.readString());
});
/**
* Tests length-delimited byte fields.
*/
it('testByteFields', function() {
var message = [];
var lowerLimit = 1;
var upperLimit = 256;
var scale = 1.1;
var 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);
writer.writeBytes(len, bytes);
}
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
for (var cursor = lowerLimit; reader.nextField(); cursor *= 1.1) {
var len = Math.round(cursor);
if (len != reader.getFieldNumber()) throw 'fail!';
var bytes = reader.readBytes();
if (len != bytes.length) throw 'fail!';
for (var i = 0; i < bytes.length; i++) {
if (i % 256 != bytes[i]) throw 'fail!';
}
}
});
/**
* Tests nested messages.
*/
it('testNesting', function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
writer.writeInt32(1, 100);
// Add one message with 3 int fields.
writer.writeMessage(2, dummyMessage, function() {
writer.writeInt32(3, 300);
writer.writeInt32(4, 400);
writer.writeInt32(5, 500);
});
// Add one empty message.
writer.writeMessage(6, dummyMessage, () => {});
writer.writeInt32(7, 700);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
// Validate outermost message.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(100, reader.readInt32());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Validate embedded message 1.
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(300, reader.readInt32());
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(400, reader.readInt32());
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(500, reader.readInt32());
assertEquals(false, reader.nextField());
});
reader.nextField();
assertEquals(6, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Validate embedded message 2.
assertEquals(false, reader.nextField());
});
reader.nextField();
assertEquals(7, reader.getFieldNumber());
assertEquals(700, reader.readInt32());
assertEquals(false, reader.nextField());
});
/**
* 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();
var sentinel = 123456789;
// Write varint fields of different sizes.
writer.writeInt32(1, sentinel);
writer.writeInt32(1, 1);
writer.writeInt32(1, 1000);
writer.writeInt32(1, 1000000);
writer.writeInt32(1, 1000000000);
// Write fixed 64-bit encoded fields.
writer.writeInt32(2, sentinel);
writer.writeDouble(2, 1);
writer.writeFixed64(2, 1);
writer.writeSfixed64(2, 1);
// Write fixed 32-bit encoded fields.
writer.writeInt32(3, sentinel);
writer.writeFloat(3, 1);
writer.writeFixed32(3, 1);
writer.writeSfixed32(3, 1);
// Write delimited fields.
writer.writeInt32(4, sentinel);
writer.writeBytes(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
writer.writeString(4, 'The quick brown fox jumps over the lazy dog');
// Write a group with a nested group inside.
writer.writeInt32(5, sentinel);
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
writer.writeGroup(5, dummyMessage, function() {
writer.writeInt64(42, 42);
writer.writeGroup(6, dummyMessage, function() {
writer.writeInt64(84, 42);
});
});
// Write final sentinel.
writer.writeInt32(6, sentinel);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
function skip(field, count) {
for (var i = 0; i < count; i++) {
reader.nextField();
if (field != reader.getFieldNumber()) throw 'fail!';
reader.skipField();
}
}
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(1, 4);
reader.nextField();
assertEquals(2, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(2, 3);
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(3, 3);
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(4, 2);
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
skip(5, 1);
reader.nextField();
assertEquals(6, reader.getFieldNumber());
assertEquals(sentinel, reader.readInt32());
});
/**
* Tests packed fields.
*/
it('testPackedFields', function() {
var writer = new jspb.BinaryWriter();
var 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];
for (var i = 0; i < floatData.length; i++) {
floatData[i] = truncate(floatData[i]);
}
writer.writeInt32(1, sentinel);
writer.writePackedInt32(2, signedData);
writer.writePackedInt64(2, signedData);
writer.writePackedUint32(2, unsignedData);
writer.writePackedUint64(2, unsignedData);
writer.writePackedSint32(2, signedData);
writer.writePackedSint64(2, signedData);
writer.writePackedFixed32(2, unsignedData);
writer.writePackedFixed64(2, unsignedData);
writer.writePackedSfixed32(2, signedData);
writer.writePackedSfixed64(2, signedData);
writer.writePackedFloat(2, floatData);
writer.writePackedDouble(2, doubleData);
writer.writePackedBool(2, boolData);
writer.writePackedEnum(2, unsignedData);
writer.writeInt32(3, sentinel);
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
reader.nextField();
assertEquals(sentinel, reader.readInt32());
reader.nextField();
assertElementsEquals(reader.readPackedInt32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedInt64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedUint32(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedUint64(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedSint32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedSint64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedFixed32(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedFixed64(), unsignedData);
reader.nextField();
assertElementsEquals(reader.readPackedSfixed32(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedSfixed64(), signedData);
reader.nextField();
assertElementsEquals(reader.readPackedFloat(), floatData);
reader.nextField();
assertElementsEquals(reader.readPackedDouble(), doubleData);
reader.nextField();
assertElementsEquals(reader.readPackedBool(), boolData);
reader.nextField();
assertElementsEquals(reader.readPackedEnum(), unsignedData);
reader.nextField();
assertEquals(sentinel, reader.readInt32());
});
/**
* Byte blobs inside nested messages should always have their byte offset set
* relative to the start of the outermost blob, not the start of their parent
* blob.
*/
it('testNestedBlobs', function() {
// 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} */ ({});
writer.writeMessage(1, dummyMessage, function() {
writer.writeMessage(1, dummyMessage, function() {
writer.writeBytes(1, blob);
});
});
// Peel off the outer two message layers. Each layer should have two bytes
// 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());
var decoder2 = new jspb.BinaryDecoder(decoder1.readBytes(blob.length + 4));
assertEquals(fieldTag, decoder2.readUnsignedVarint32());
assertEquals(blob.length + 2, decoder2.readUnsignedVarint32());
assertEquals(fieldTag, decoder2.readUnsignedVarint32());
assertEquals(blob.length, decoder2.readUnsignedVarint32());
var bytes = decoder2.readBytes(blob.length);
assertElementsEquals(bytes, blob);
});
/**
* Tests read callbacks.
*/
it('testReadCallbacks', function() {
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
// Add an int, a submessage, and another int.
writer.writeInt32(1, 100);
writer.writeMessage(2, dummyMessage, function() {
writer.writeInt32(3, 300);
writer.writeInt32(4, 400);
writer.writeInt32(5, 500);
});
writer.writeInt32(7, 700);
// Create the reader and register a custom read callback.
var reader = jspb.BinaryReader.alloc(writer.getResultBuffer());
/**
* @param {!jspb.BinaryReader} reader
* @return {*}
*/
function readCallback(reader) {
reader.nextField();
assertEquals(3, reader.getFieldNumber());
assertEquals(300, reader.readInt32());
reader.nextField();
assertEquals(4, reader.getFieldNumber());
assertEquals(400, reader.readInt32());
reader.nextField();
assertEquals(5, reader.getFieldNumber());
assertEquals(500, reader.readInt32());
assertEquals(false, reader.nextField());
};
reader.registerReadCallback('readCallback', readCallback);
// Read the container message.
reader.nextField();
assertEquals(1, reader.getFieldNumber());
assertEquals(100, reader.readInt32());
reader.nextField();
assertEquals(2, reader.getFieldNumber());
reader.readMessage(dummyMessage, function() {
// Decode the embedded message using the registered callback.
reader.runReadCallback('readCallback');
});
reader.nextField();
assertEquals(7, reader.getFieldNumber());
assertEquals(700, reader.readInt32());
assertEquals(false, reader.nextField());
});
});

View File

@ -1,668 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's helper functions.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryConstants');
goog.require('jspb.BinaryWriter');
goog.require('jspb.utils');
/**
* @param {number} x
* @return {number}
*/
function truncate(x) {
var temp = new Float32Array(1);
temp[0] = x;
return temp[0];
}
/**
* Converts an 64-bit integer in split representation to a 64-bit hash string
* (8 bits encoded per character).
* @param {number} bitsLow The low 32 bits of the split 64-bit integer.
* @param {number} bitsHigh The high 32 bits of the split 64-bit integer.
* @return {string} The encoded hash string, 8 bits per character.
*/
function toHashString(bitsLow, bitsHigh) {
return String.fromCharCode((bitsLow >>> 0) & 0xFF,
(bitsLow >>> 8) & 0xFF,
(bitsLow >>> 16) & 0xFF,
(bitsLow >>> 24) & 0xFF,
(bitsHigh >>> 0) & 0xFF,
(bitsHigh >>> 8) & 0xFF,
(bitsHigh >>> 16) & 0xFF,
(bitsHigh >>> 24) & 0xFF);
}
describe('binaryUtilsTest', function() {
/**
* Tests lossless binary-to-decimal conversion.
*/
it('testDecimalConversion', function() {
// Check some magic numbers.
var result =
jspb.utils.joinUnsignedDecimalString(0x89e80001, 0x8ac72304);
assertEquals('10000000000000000001', result);
result = jspb.utils.joinUnsignedDecimalString(0xacd05f15, 0x1b69b4b);
assertEquals('123456789123456789', result);
result = jspb.utils.joinUnsignedDecimalString(0xeb1f0ad2, 0xab54a98c);
assertEquals('12345678901234567890', result);
result = jspb.utils.joinUnsignedDecimalString(0xe3b70cb1, 0x891087b8);
assertEquals('9876543210987654321', result);
// Check limits.
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00000000);
assertEquals('0', result);
result = jspb.utils.joinUnsignedDecimalString(0xFFFFFFFF, 0xFFFFFFFF);
assertEquals('18446744073709551615', result);
// Check each bit of the low dword.
for (var i = 0; i < 32; i++) {
var low = (1 << i) >>> 0;
result = jspb.utils.joinUnsignedDecimalString(low, 0);
assertEquals('' + Math.pow(2, i), result);
}
// Check the first 20 bits of the high dword.
for (var i = 0; i < 20; i++) {
var high = (1 << i) >>> 0;
result = jspb.utils.joinUnsignedDecimalString(0, high);
assertEquals('' + Math.pow(2, 32 + i), result);
}
// V8's internal double-to-string conversion is inaccurate for values above
// 2^52, even if they're representable integers - check the rest of the bits
// manually against the correct string representations of 2^N.
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00100000);
assertEquals('4503599627370496', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00200000);
assertEquals('9007199254740992', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00400000);
assertEquals('18014398509481984', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00800000);
assertEquals('36028797018963968', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x01000000);
assertEquals('72057594037927936', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x02000000);
assertEquals('144115188075855872', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x04000000);
assertEquals('288230376151711744', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x08000000);
assertEquals('576460752303423488', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x10000000);
assertEquals('1152921504606846976', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x20000000);
assertEquals('2305843009213693952', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x40000000);
assertEquals('4611686018427387904', result);
result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x80000000);
assertEquals('9223372036854775808', result);
});
/**
* Going from hash strings to decimal strings should also be lossless.
*/
it('testHashToDecimalConversion', function() {
var result;
var convert = jspb.utils.hash64ToDecimalString;
result = convert(toHashString(0x00000000, 0x00000000), false);
assertEquals('0', result);
result = convert(toHashString(0x00000000, 0x00000000), true);
assertEquals('0', result);
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), false);
assertEquals('18446744073709551615', result);
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), true);
assertEquals('-1', result);
result = convert(toHashString(0x00000000, 0x80000000), false);
assertEquals('9223372036854775808', result);
result = convert(toHashString(0x00000000, 0x80000000), true);
assertEquals('-9223372036854775808', result);
result = convert(toHashString(0xacd05f15, 0x01b69b4b), false);
assertEquals('123456789123456789', result);
result = convert(toHashString(~0xacd05f15 + 1, ~0x01b69b4b), true);
assertEquals('-123456789123456789', result);
// And converting arrays of hashes should work the same way.
result = jspb.utils.hash64ArrayToDecimalStrings([
toHashString(0xFFFFFFFF, 0xFFFFFFFF),
toHashString(0x00000000, 0x80000000),
toHashString(0xacd05f15, 0x01b69b4b)], false);
assertEquals(3, result.length);
assertEquals('18446744073709551615', result[0]);
assertEquals('9223372036854775808', result[1]);
assertEquals('123456789123456789', result[2]);
});
/*
* Going from decimal strings to hash strings should be lossless.
*/
it('testDecimalToHashConversion', function() {
var result;
var convert = jspb.utils.decimalStringToHash64;
result = convert('0');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
result = convert('-1');
assertEquals(String.fromCharCode.apply(null,
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
result = convert('18446744073709551615');
assertEquals(String.fromCharCode.apply(null,
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
result = convert('9223372036854775808');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
result = convert('-9223372036854775808');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]), result);
result = convert('123456789123456789');
assertEquals(String.fromCharCode.apply(null,
[0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]), result);
result = convert('-123456789123456789');
assertEquals(String.fromCharCode.apply(null,
[0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]), result);
});
/**
* Going from hash strings to hex strings should be lossless.
*/
it('testHashToHexConversion', function() {
var result;
var convert = jspb.utils.hash64ToHexString;
result = convert(toHashString(0x00000000, 0x00000000));
assertEquals('0x0000000000000000', result);
result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF));
assertEquals('0xffffffffffffffff', result);
result = convert(toHashString(0x12345678, 0x9ABCDEF0));
assertEquals('0x9abcdef012345678', result);
});
/**
* Going from hex strings to hash strings should be lossless.
*/
it('testHexToHashConversion', function() {
var result;
var convert = jspb.utils.hexStringToHash64;
result = convert('0x0000000000000000');
assertEquals(String.fromCharCode.apply(null,
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), result);
result = convert('0xffffffffffffffff');
assertEquals(String.fromCharCode.apply(null,
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), result);
// Hex string is big-endian, hash string is little-endian.
result = convert('0x123456789ABCDEF0');
assertEquals(String.fromCharCode.apply(null,
[0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]), result);
// Capitalization should not matter.
result = convert('0x0000abcdefABCDEF');
assertEquals(String.fromCharCode.apply(null,
[0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]), result);
});
/**
* Going from numbers to hash strings should be lossless for up to 53 bits of
* precision.
*/
it('testNumberToHashConversion', function() {
var result;
var convert = jspb.utils.numberToHash64;
result = convert(0x0000000000000);
assertEquals('0x0000000000000000', jspb.utils.hash64ToHexString(result));
result = convert(0xFFFFFFFFFFFFF);
assertEquals('0x000fffffffffffff', jspb.utils.hash64ToHexString(result));
result = convert(0x123456789ABCD);
assertEquals('0x000123456789abcd', jspb.utils.hash64ToHexString(result));
result = convert(0xDCBA987654321);
assertEquals('0x000dcba987654321', jspb.utils.hash64ToHexString(result));
// 53 bits of precision should not be truncated.
result = convert(0x10000000000001);
assertEquals('0x0010000000000001', jspb.utils.hash64ToHexString(result));
// 54 bits of precision should be truncated.
result = convert(0x20000000000001);
assertNotEquals(
'0x0020000000000001', jspb.utils.hash64ToHexString(result));
});
/**
* Sanity check the behavior of Javascript's strings when doing funny things
* with unicode characters.
*/
it('sanityCheckUnicodeStrings', function() {
var strings = new Array(65536);
// All possible unsigned 16-bit values should be storable in a string, they
// shouldn't do weird things with the length of the string, and they should
// come back out of the string unchanged.
for (var i = 0; i < 65536; i++) {
strings[i] = 'a' + String.fromCharCode(i) + 'a';
if (3 != strings[i].length) throw 'fail!';
if (i != strings[i].charCodeAt(1)) throw 'fail!';
}
// Each unicode character should compare equal to itself and not equal to a
// different unicode character.
for (var i = 0; i < 65536; i++) {
if (strings[i] != strings[i]) throw 'fail!';
if (strings[i] == strings[(i + 1) % 65536]) throw 'fail!';
}
});
/**
* Tests conversion from 32-bit floating point numbers to split64 numbers.
*/
it('testFloat32ToSplit64', function() {
var f32_eps = jspb.BinaryConstants.FLOAT32_EPS;
var f32_min = jspb.BinaryConstants.FLOAT32_MIN;
var f32_max = jspb.BinaryConstants.FLOAT32_MAX;
// NaN.
jspb.utils.splitFloat32(NaN);
if (!isNaN(jspb.utils.joinFloat32(jspb.utils.split64Low,
jspb.utils.split64High))) {
throw 'fail!';
}
/**
* @param {number} x
* @param {number=} opt_bits
*/
function test(x, opt_bits) {
jspb.utils.splitFloat32(x);
if (opt_bits !== undefined) {
if (opt_bits != jspb.utils.split64Low) throw 'fail!';
}
if (truncate(x) != jspb.utils.joinFloat32(jspb.utils.split64Low,
jspb.utils.split64High)) {
throw 'fail!';
}
}
// Positive and negative infinity.
test(Infinity, 0x7f800000);
test(-Infinity, 0xff800000);
// Positive and negative zero.
test(0, 0x00000000);
test(-0, 0x80000000);
// Positive and negative epsilon.
test(f32_eps, 0x00000001);
test(-f32_eps, 0x80000001);
// Positive and negative min.
test(f32_min, 0x00800000);
test(-f32_min, 0x80800000);
// Positive and negative max.
test(f32_max, 0x7F7FFFFF);
test(-f32_max, 0xFF7FFFFF);
// Various positive values.
var cursor = f32_eps * 10;
while (cursor != Infinity) {
test(cursor);
cursor *= 1.1;
}
// Various negative values.
cursor = -f32_eps * 10;
while (cursor != -Infinity) {
test(cursor);
cursor *= 1.1;
}
});
/**
* Tests conversion from 64-bit floating point numbers to split64 numbers.
*/
it('testFloat64ToSplit64', function() {
var f64_eps = jspb.BinaryConstants.FLOAT64_EPS;
var f64_min = jspb.BinaryConstants.FLOAT64_MIN;
var f64_max = jspb.BinaryConstants.FLOAT64_MAX;
// NaN.
jspb.utils.splitFloat64(NaN);
if (!isNaN(jspb.utils.joinFloat64(jspb.utils.split64Low,
jspb.utils.split64High))) {
throw 'fail!';
}
/**
* @param {number} x
* @param {number=} opt_highBits
* @param {number=} opt_lowBits
*/
function test(x, opt_highBits, opt_lowBits) {
jspb.utils.splitFloat64(x);
if (opt_highBits !== undefined) {
if (opt_highBits != jspb.utils.split64High) throw 'fail!';
}
if (opt_lowBits !== undefined) {
if (opt_lowBits != jspb.utils.split64Low) throw 'fail!';
}
if (x != jspb.utils.joinFloat64(jspb.utils.split64Low,
jspb.utils.split64High)) {
throw 'fail!';
}
}
// Positive and negative infinity.
test(Infinity, 0x7ff00000, 0x00000000);
test(-Infinity, 0xfff00000, 0x00000000);
// Positive and negative zero.
test(0, 0x00000000, 0x00000000);
test(-0, 0x80000000, 0x00000000);
// Positive and negative epsilon.
test(f64_eps, 0x00000000, 0x00000001);
test(-f64_eps, 0x80000000, 0x00000001);
// Positive and negative min.
test(f64_min, 0x00100000, 0x00000000);
test(-f64_min, 0x80100000, 0x00000000);
// Positive and negative max.
test(f64_max, 0x7FEFFFFF, 0xFFFFFFFF);
test(-f64_max, 0xFFEFFFFF, 0xFFFFFFFF);
// Various positive values.
var cursor = f64_eps * 10;
while (cursor != Infinity) {
test(cursor);
cursor *= 1.1;
}
// Various negative values.
cursor = -f64_eps * 10;
while (cursor != -Infinity) {
test(cursor);
cursor *= 1.1;
}
});
/**
* Tests counting packed varints.
*/
it('testCountVarints', function() {
var values = [];
for (var i = 1; i < 1000000000; i *= 1.1) {
values.push(Math.floor(i));
}
var writer = new jspb.BinaryWriter();
writer.writePackedUint64(1, values);
var buffer = new Uint8Array(writer.getResultBuffer());
// We should have two more varints than we started with - one for the field
// tag, one for the packed length.
assertEquals(values.length + 2,
jspb.utils.countVarints(buffer, 0, buffer.length));
});
/**
* Tests counting matching varint fields.
*/
it('testCountVarintFields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeUint64(1, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countVarintFields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeUint64(123456789, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countVarintFields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests counting matching fixed32 fields.
*/
it('testCountFixed32Fields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeFixed32(1, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeFixed32(123456789, Math.floor(i));
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests counting matching fixed64 fields.
*/
it('testCountFixed64Fields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeDouble(1, i);
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000000000; i *= 1.1) {
writer.writeDouble(123456789, i);
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests counting matching delimited fields.
*/
it('testCountDelimitedFields', function() {
var writer = new jspb.BinaryWriter();
var count = 0;
for (var i = 1; i < 1000; i *= 1.1) {
writer.writeBytes(1, [Math.floor(i)]);
count++;
}
writer.writeString(2, 'terminator');
var buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 1));
writer = new jspb.BinaryWriter();
count = 0;
for (var i = 1; i < 1000; i *= 1.1) {
writer.writeBytes(123456789, [Math.floor(i)]);
count++;
}
writer.writeString(2, 'terminator');
buffer = new Uint8Array(writer.getResultBuffer());
assertEquals(count,
jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 123456789));
});
/**
* Tests byte format for debug strings.
*/
it('testDebugBytesToTextFormat', function() {
assertEquals('""', jspb.utils.debugBytesToTextFormat(null));
assertEquals('"\\x00\\x10\\xff"',
jspb.utils.debugBytesToTextFormat([0, 16, 255]));
});
/**
* Tests converting byte blob sources into byte blobs.
*/
it('testByteSourceToUint8Array', function() {
var convert = jspb.utils.byteSourceToUint8Array;
var sourceData = [];
for (var i = 0; i < 256; i++) {
sourceData.push(i);
}
var sourceBytes = new Uint8Array(sourceData);
var sourceBuffer = sourceBytes.buffer;
var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
var sourceString = String.fromCharCode.apply(null, sourceData);
function check(result) {
assertEquals(Uint8Array, result.constructor);
assertEquals(sourceData.length, result.length);
for (var i = 0; i < result.length; i++) {
assertEquals(sourceData[i], result[i]);
}
}
// Converting Uint8Arrays into Uint8Arrays should be a no-op.
assertEquals(sourceBytes, convert(sourceBytes));
// Converting Array.<numbers> into Uint8Arrays should work.
check(convert(sourceData));
// Converting ArrayBuffers into Uint8Arrays should work.
check(convert(sourceBuffer));
// Converting base64-encoded strings into Uint8Arrays should work.
check(convert(sourceBase64));
});
});

View File

@ -1,164 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Test cases for jspb's binary protocol buffer writer. In
* practice BinaryWriter is used to drive the Decoder and Reader test cases,
* so only writer-specific tests are here.
*
* Test suite is written using Jasmine -- see http://jasmine.github.io/
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.require('goog.crypt');
goog.require('goog.testing.asserts');
goog.require('jspb.BinaryWriter');
goog.requireType('jspb.BinaryMessage');
/**
* @param {function()} func This function should throw an error when run.
*/
function assertFails(func) {
var e = assertThrows(func);
// assertNotNull(e.toString().match(/Error/));
}
describe('binaryWriterTest', function() {
/**
* Verifies that misuse of the writer class triggers assertions.
*/
it('testWriteErrors', function() {
// Submessages with invalid field indices should assert.
var writer = new jspb.BinaryWriter();
var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({});
assertFails(function() {
writer.writeMessage(-1, dummyMessage, () => {});
});
// Writing invalid field indices should assert.
writer = new jspb.BinaryWriter();
assertFails(function() {
writer.writeUint64(-1, 1);
});
// Writing out-of-range field values should assert.
writer = new jspb.BinaryWriter();
assertFails(function() {
writer.writeInt32(1, -Infinity);
});
assertFails(function() {
writer.writeInt32(1, Infinity);
});
assertFails(function() {
writer.writeInt64(1, -Infinity);
});
assertFails(function() {
writer.writeInt64(1, Infinity);
});
assertFails(function() {
writer.writeUint32(1, -1);
});
assertFails(function() {
writer.writeUint32(1, Infinity);
});
assertFails(function() {
writer.writeUint64(1, -1);
});
assertFails(function() {
writer.writeUint64(1, Infinity);
});
assertFails(function() {
writer.writeSint32(1, -Infinity);
});
assertFails(function() {
writer.writeSint32(1, Infinity);
});
assertFails(function() {
writer.writeSint64(1, -Infinity);
});
assertFails(function() {
writer.writeSint64(1, Infinity);
});
assertFails(function() {
writer.writeFixed32(1, -1);
});
assertFails(function() {
writer.writeFixed32(1, Infinity);
});
assertFails(function() {
writer.writeFixed64(1, -1);
});
assertFails(function() {
writer.writeFixed64(1, Infinity);
});
assertFails(function() {
writer.writeSfixed32(1, -Infinity);
});
assertFails(function() {
writer.writeSfixed32(1, Infinity);
});
assertFails(function() {
writer.writeSfixed64(1, -Infinity);
});
assertFails(function() {
writer.writeSfixed64(1, Infinity);
});
});
/**
* Basic test of retrieving the result as a Uint8Array buffer
*/
it('testGetResultBuffer', function() {
var expected = '0864120b48656c6c6f20776f726c641a0301020320c801';
var writer = new jspb.BinaryWriter();
writer.writeUint32(1, 100);
writer.writeString(2, 'Hello world');
writer.writeBytes(3, new Uint8Array([1, 2, 3]));
writer.writeUint32(4, 200);
var buffer = writer.getResultBuffer();
assertEquals(expected, goog.crypt.byteArrayToHex(buffer));
});
});

View File

@ -1,40 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test.importing;
message ImportedMessage {
string string_value = 1;
}

View File

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2016 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test.framing;
import "test6/test6.proto";
message FramingMessage {
jspb.test.importing.ImportedMessage imported_message = 1;
}

View File

@ -1,51 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: mwr@google.com (Mark Rawling)
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test;
// legacy data, must be nested
message data {
message NestedData {
required string str = 1;
}
}
// new data, does not require nesting
message UnnestedData {
required string str = 1;
}

View File

@ -1,105 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.setTestOnly();
goog.require('goog.testing.asserts');
// CommonJS-LoadFromFile: google-protobuf
goog.require('jspb.debug');
// CommonJS-LoadFromFile: test_pb
goog.require('proto.jspb.test.HasExtensions');
goog.require('proto.jspb.test.IsExtension');
goog.require('proto.jspb.test.Simple1');
describe('debugTest', function() {
it('testSimple1', function() {
if (COMPILED) {
return;
}
var message = new proto.jspb.test.Simple1();
message.setAString('foo');
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': []
}, jspb.debug.dump(message));
message.setABoolean(true);
message.setARepeatedStringList(['1', '2']);
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
message.clearAString();
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
});
it('testExtensions', function() {
if (COMPILED) {
return;
}
var extension = new proto.jspb.test.IsExtension();
extension.setExt1('ext1field');
var extendable = new proto.jspb.test.HasExtensions();
extendable.setStr1('v1');
extendable.setStr2('v2');
extendable.setStr3('v3');
extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
assertObjectEquals({
'$name': 'proto.jspb.test.HasExtensions',
'str1': 'v1',
'str2': 'v2',
'str3': 'v3',
'$extensions': {
'extField': {
'$name': 'proto.jspb.test.IsExtension',
'ext1': 'ext1field'
},
'repeatedSimpleList': []
}
}, jspb.debug.dump(extendable));
});
});

View File

@ -1,284 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.require('goog.testing.asserts');
goog.require('goog.userAgent');
// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
goog.require('proto.jspb.test.MapValueEnum');
goog.require('proto.jspb.test.MapValueMessage');
goog.require('proto.jspb.test.TestMapFields');
// CommonJS-LoadFromFile: test_pb proto.jspb.test
goog.require('proto.jspb.test.MapValueMessageNoBinary');
goog.require('proto.jspb.test.TestMapFieldsNoBinary');
goog.requireType('jspb.Map');
/**
* Helper: check that the given map has exactly this set of (sorted) entries.
* @param {!jspb.Map} map
* @param {!Array<!Array<?>>} entries
*/
function checkMapEquals(map, entries) {
var arr = map.toArray();
assertEquals(arr.length, entries.length);
for (var i = 0; i < arr.length; i++) {
assertElementsEquals(arr[i], entries[i]);
}
}
/**
* Converts an ES6 iterator to an array.
* @template T
* @param {!Iterator<T>} iter an iterator
* @return {!Array<T>}
*/
function toArray(iter) {
var arr = [];
while (true) {
var val = iter.next();
if (val.done) {
break;
}
arr.push(val.value);
}
return arr;
}
/**
* Helper: generate test methods for this TestMapFields class.
* @param {?} msgInfo
* @param {?} submessageCtor
* @param {!string} suffix
*/
function makeTests(msgInfo, submessageCtor, suffix) {
/**
* Helper: fill all maps on a TestMapFields.
* @param {?} msg
*/
var fillMapFields = function(msg) {
msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world');
msg.getMapStringInt32Map().set('a', 1).set('b', -2);
msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000);
msg.getMapStringBoolMap().set('e', true).set('f', false);
msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828);
msg.getMapStringEnumMap()
.set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR)
.set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ);
msg.getMapStringMsgMap()
.set('k', new submessageCtor())
.set('l', new submessageCtor());
msg.getMapStringMsgMap().get('k').setFoo(42);
msg.getMapStringMsgMap().get('l').setFoo(84);
msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b');
msg.getMapInt64StringMap()
.set(0x123456789abc, 'c')
.set(0xcba987654321, 'd');
msg.getMapBoolStringMap().set(false, 'e').set(true, 'f');
};
/**
* Helper: check all maps on a TestMapFields.
* @param {?} msg
*/
var checkMapFields = function(msg) {
checkMapEquals(
msg.getMapStringStringMap(),
[['asdf', 'jkl;'], ['key 2', 'hello world']]);
checkMapEquals(msg.getMapStringInt32Map(), [['a', 1], ['b', -2]]);
checkMapEquals(
msg.getMapStringInt64Map(), [['c', 0x100000000], ['d', 0x200000000]]);
checkMapEquals(msg.getMapStringBoolMap(), [['e', true], ['f', false]]);
checkMapEquals(
msg.getMapStringDoubleMap(), [['g', 3.14159], ['h', 2.71828]]);
checkMapEquals(msg.getMapStringEnumMap(), [
['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR],
['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ]
]);
checkMapEquals(msg.getMapInt32StringMap(), [[-1, 'a'], [42, 'b']]);
checkMapEquals(
msg.getMapInt64StringMap(),
[[0x123456789abc, 'c'], [0xcba987654321, 'd']]);
checkMapEquals(msg.getMapBoolStringMap(), [[false, 'e'], [true, 'f']]);
assertEquals(msg.getMapStringMsgMap().getLength(), 2);
assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42);
assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84);
var entries = toArray(msg.getMapStringMsgMap().entries());
assertEquals(entries.length, 2);
entries.forEach(function(entry) {
var key = entry[0];
var val = entry[1];
assert(val === msg.getMapStringMsgMap().get(key));
});
msg.getMapStringMsgMap().forEach(function(val, key) {
assert(val === msg.getMapStringMsgMap().get(key));
});
};
it('testMapStringStringField' + suffix, function() {
var msg = new msgInfo.constructor();
assertEquals(msg.getMapStringStringMap().getLength(), 0);
assertEquals(msg.getMapStringInt32Map().getLength(), 0);
assertEquals(msg.getMapStringInt64Map().getLength(), 0);
assertEquals(msg.getMapStringBoolMap().getLength(), 0);
assertEquals(msg.getMapStringDoubleMap().getLength(), 0);
assertEquals(msg.getMapStringEnumMap().getLength(), 0);
assertEquals(msg.getMapStringMsgMap().getLength(), 0);
// Re-create to clear out any internally-cached wrappers, etc.
msg = new msgInfo.constructor();
var m = msg.getMapStringStringMap();
assertEquals(m.has('asdf'), false);
assertEquals(m.get('asdf'), undefined);
m.set('asdf', 'hello world');
assertEquals(m.has('asdf'), true);
assertEquals(m.get('asdf'), 'hello world');
m.set('jkl;', 'key 2');
assertEquals(m.has('jkl;'), true);
assertEquals(m.get('jkl;'), 'key 2');
assertEquals(m.getLength(), 2);
var it = m.entries();
assertElementsEquals(it.next().value, ['asdf', 'hello world']);
assertElementsEquals(it.next().value, ['jkl;', 'key 2']);
assertEquals(it.next().done, true);
checkMapEquals(m, [['asdf', 'hello world'], ['jkl;', 'key 2']]);
m.del('jkl;');
assertEquals(m.has('jkl;'), false);
assertEquals(m.get('jkl;'), undefined);
assertEquals(m.getLength(), 1);
it = m.keys();
assertEquals(it.next().value, 'asdf');
assertEquals(it.next().done, true);
it = m.values();
assertEquals(it.next().value, 'hello world');
assertEquals(it.next().done, true);
var count = 0;
m.forEach(function(value, key, map) {
assertEquals(map, m);
assertEquals(key, 'asdf');
assertEquals(value, 'hello world');
count++;
});
assertEquals(count, 1);
m.clear();
assertEquals(m.getLength(), 0);
});
/**
* Tests operations on maps with all key and value types.
*/
it('testAllMapTypes' + suffix, function() {
var msg = new msgInfo.constructor();
fillMapFields(msg);
checkMapFields(msg);
});
if (msgInfo.deserializeBinary) {
/**
* Tests serialization and deserialization in binary format.
*/
it('testBinaryFormat' + suffix, function() {
if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) {
// IE8/9 currently doesn't support binary format because they lack
// TypedArray.
return;
}
// Check that the format is correct.
var msg = new msgInfo.constructor();
msg.getMapStringStringMap().set('A', 'a');
var serialized = msg.serializeBinary();
var expectedSerialized = [
0x0a, 0x6, // field 1 (map_string_string), delimited, length 6
0x0a, 0x1, // field 1 in submessage (key), delimited, length 1
0x41, // ASCII 'A'
0x12, 0x1, // field 2 in submessage (value), delimited, length 1
0x61 // ASCII 'a'
];
assertEquals(serialized.length, expectedSerialized.length);
for (var i = 0; i < serialized.length; i++) {
assertEquals(serialized[i], expectedSerialized[i]);
}
// Check that all map fields successfully round-trip.
msg = new msgInfo.constructor();
fillMapFields(msg);
serialized = msg.serializeBinary();
var decoded = msgInfo.deserializeBinary(serialized);
checkMapFields(decoded);
});
}
/**
* Exercises the lazy map<->underlying array sync.
*/
it('testLazyMapSync' + suffix, function() {
// Start with a JSPB array containing a few map entries.
var entries = [['a', 'entry 1'], ['c', 'entry 2'], ['b', 'entry 3']];
var msg = new msgInfo.constructor([entries]);
assertEquals(entries.length, 3);
assertEquals(entries[0][0], 'a');
assertEquals(entries[1][0], 'c');
assertEquals(entries[2][0], 'b');
msg.getMapStringStringMap().del('a');
assertEquals(entries.length, 3); // not yet sync'd
msg.toArray(); // force a sync
assertEquals(entries.length, 2);
assertEquals(entries[0][0], 'b'); // now in sorted order
assertEquals(entries[1][0], 'c');
var a = msg.toArray();
assertEquals(a[0], entries); // retains original reference
});
}
describe('mapsTest', function() {
makeTests(
{
constructor: proto.jspb.test.TestMapFields,
deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary
},
proto.jspb.test.MapValueMessage, '_Binary');
makeTests(
{
constructor: proto.jspb.test.TestMapFieldsNoBinary,
deserializeBinary: null
},
proto.jspb.test.MapValueMessageNoBinary, '_NoBinary');
});

File diff suppressed because it is too large Load Diff

View File

@ -1,329 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.require('goog.crypt.base64');
goog.require('goog.testing.asserts');
// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
goog.require('proto.jspb.test.ForeignMessage');
// CommonJS-LoadFromFile: proto3_test_pb proto.jspb.test
goog.require('proto.jspb.test.Proto3Enum');
goog.require('proto.jspb.test.TestProto3');
var BYTES = new Uint8Array([1, 2, 8, 9]);
var BYTES_B64 = goog.crypt.base64.encodeByteArray(BYTES);
/**
* Helper: compare a bytes field to an expected value
* @param {Uint8Array|string} arr
* @param {Uint8Array} expected
* @return {boolean}
*/
function bytesCompare(arr, expected) {
if (typeof arr === 'string') {
arr = goog.crypt.base64.decodeStringToUint8Array(arr);
}
if (arr.length != expected.length) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] != expected[i]) {
return false;
}
}
return true;
}
describe('proto3Test', function() {
/**
* Test defaults for proto3 message fields.
*/
it('testProto3FieldDefaults', function() {
var msg = new proto.jspb.test.TestProto3();
assertEquals(msg.getOptionalInt32(), 0);
assertEquals(msg.getOptionalInt64(), 0);
assertEquals(msg.getOptionalUint32(), 0);
assertEquals(msg.getOptionalUint64(), 0);
assertEquals(msg.getOptionalSint32(), 0);
assertEquals(msg.getOptionalSint64(), 0);
assertEquals(msg.getOptionalFixed32(), 0);
assertEquals(msg.getOptionalFixed64(), 0);
assertEquals(msg.getOptionalSfixed32(), 0);
assertEquals(msg.getOptionalSfixed64(), 0);
assertEquals(msg.getOptionalFloat(), 0);
assertEquals(msg.getOptionalDouble(), 0);
assertEquals(msg.getOptionalString(), '');
// TODO(b/26173701): when we change bytes fields default getter to return
// Uint8Array, we'll want to switch this assertion to match the u8 case.
assertEquals(typeof msg.getOptionalBytes(), 'string');
assertEquals(msg.getOptionalBytes_asU8() instanceof Uint8Array, true);
assertEquals(typeof msg.getOptionalBytes_asB64(), 'string');
assertEquals(msg.getOptionalBytes().length, 0);
assertEquals(msg.getOptionalBytes_asU8().length, 0);
assertEquals(msg.getOptionalBytes_asB64(), '');
assertEquals(msg.getOptionalForeignEnum(),
proto.jspb.test.Proto3Enum.PROTO3_FOO);
assertEquals(msg.getOptionalForeignMessage(), undefined);
assertEquals(msg.getOptionalForeignMessage(), undefined);
assertEquals(msg.getRepeatedInt32List().length, 0);
assertEquals(msg.getRepeatedInt64List().length, 0);
assertEquals(msg.getRepeatedUint32List().length, 0);
assertEquals(msg.getRepeatedUint64List().length, 0);
assertEquals(msg.getRepeatedSint32List().length, 0);
assertEquals(msg.getRepeatedSint64List().length, 0);
assertEquals(msg.getRepeatedFixed32List().length, 0);
assertEquals(msg.getRepeatedFixed64List().length, 0);
assertEquals(msg.getRepeatedSfixed32List().length, 0);
assertEquals(msg.getRepeatedSfixed64List().length, 0);
assertEquals(msg.getRepeatedFloatList().length, 0);
assertEquals(msg.getRepeatedDoubleList().length, 0);
assertEquals(msg.getRepeatedStringList().length, 0);
assertEquals(msg.getRepeatedBytesList().length, 0);
assertEquals(msg.getRepeatedForeignEnumList().length, 0);
assertEquals(msg.getRepeatedForeignMessageList().length, 0);
});
/**
* Test that all fields can be set and read via a serialization roundtrip.
*/
it('testProto3FieldSetGet', function() {
var msg = new proto.jspb.test.TestProto3();
msg.setOptionalInt32(-42);
msg.setOptionalInt64(-0x7fffffff00000000);
msg.setOptionalUint32(0x80000000);
msg.setOptionalUint64(0xf000000000000000);
msg.setOptionalSint32(-100);
msg.setOptionalSint64(-0x8000000000000000);
msg.setOptionalFixed32(1234);
msg.setOptionalFixed64(0x1234567800000000);
msg.setOptionalSfixed32(-1234);
msg.setOptionalSfixed64(-0x1234567800000000);
msg.setOptionalFloat(1.5);
msg.setOptionalDouble(-1.5);
msg.setOptionalBool(true);
msg.setOptionalString('hello world');
msg.setOptionalBytes(BYTES);
var submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(16);
msg.setOptionalForeignMessage(submsg);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
msg.setRepeatedInt32List([-42]);
msg.setRepeatedInt64List([-0x7fffffff00000000]);
msg.setRepeatedUint32List([0x80000000]);
msg.setRepeatedUint64List([0xf000000000000000]);
msg.setRepeatedSint32List([-100]);
msg.setRepeatedSint64List([-0x8000000000000000]);
msg.setRepeatedFixed32List([1234]);
msg.setRepeatedFixed64List([0x1234567800000000]);
msg.setRepeatedSfixed32List([-1234]);
msg.setRepeatedSfixed64List([-0x1234567800000000]);
msg.setRepeatedFloatList([1.5]);
msg.setRepeatedDoubleList([-1.5]);
msg.setRepeatedBoolList([true]);
msg.setRepeatedStringList(['hello world']);
msg.setRepeatedBytesList([BYTES]);
submsg = new proto.jspb.test.ForeignMessage();
submsg.setC(1000);
msg.setRepeatedForeignMessageList([submsg]);
msg.setRepeatedForeignEnumList([proto.jspb.test.Proto3Enum.PROTO3_BAR]);
msg.setOneofString('asdf');
var serialized = msg.serializeBinary();
msg = proto.jspb.test.TestProto3.deserializeBinary(serialized);
assertEquals(msg.getOptionalInt32(), -42);
assertEquals(msg.getOptionalInt64(), -0x7fffffff00000000);
assertEquals(msg.getOptionalUint32(), 0x80000000);
assertEquals(msg.getOptionalUint64(), 0xf000000000000000);
assertEquals(msg.getOptionalSint32(), -100);
assertEquals(msg.getOptionalSint64(), -0x8000000000000000);
assertEquals(msg.getOptionalFixed32(), 1234);
assertEquals(msg.getOptionalFixed64(), 0x1234567800000000);
assertEquals(msg.getOptionalSfixed32(), -1234);
assertEquals(msg.getOptionalSfixed64(), -0x1234567800000000);
assertEquals(msg.getOptionalFloat(), 1.5);
assertEquals(msg.getOptionalDouble(), -1.5);
assertEquals(msg.getOptionalBool(), true);
assertEquals(msg.getOptionalString(), 'hello world');
assertEquals(true, bytesCompare(msg.getOptionalBytes(), BYTES));
assertEquals(msg.getOptionalForeignMessage().getC(), 16);
assertEquals(msg.getOptionalForeignEnum(),
proto.jspb.test.Proto3Enum.PROTO3_BAR);
assertElementsEquals(msg.getRepeatedInt32List(), [-42]);
assertElementsEquals(msg.getRepeatedInt64List(), [-0x7fffffff00000000]);
assertElementsEquals(msg.getRepeatedUint32List(), [0x80000000]);
assertElementsEquals(msg.getRepeatedUint64List(), [0xf000000000000000]);
assertElementsEquals(msg.getRepeatedSint32List(), [-100]);
assertElementsEquals(msg.getRepeatedSint64List(), [-0x8000000000000000]);
assertElementsEquals(msg.getRepeatedFixed32List(), [1234]);
assertElementsEquals(msg.getRepeatedFixed64List(), [0x1234567800000000]);
assertElementsEquals(msg.getRepeatedSfixed32List(), [-1234]);
assertElementsEquals(msg.getRepeatedSfixed64List(), [-0x1234567800000000]);
assertElementsEquals(msg.getRepeatedFloatList(), [1.5]);
assertElementsEquals(msg.getRepeatedDoubleList(), [-1.5]);
assertElementsEquals(msg.getRepeatedBoolList(), [true]);
assertElementsEquals(msg.getRepeatedStringList(), ['hello world']);
assertEquals(msg.getRepeatedBytesList().length, 1);
assertEquals(true, bytesCompare(msg.getRepeatedBytesList()[0], BYTES));
assertEquals(msg.getRepeatedForeignMessageList().length, 1);
assertEquals(msg.getRepeatedForeignMessageList()[0].getC(), 1000);
assertElementsEquals(msg.getRepeatedForeignEnumList(),
[proto.jspb.test.Proto3Enum.PROTO3_BAR]);
assertEquals(msg.getOneofString(), 'asdf');
});
/**
* Test that oneofs continue to have a notion of field presence.
*/
it('testOneofs', function() {
var msg = new proto.jspb.test.TestProto3();
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
assertFalse(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
msg.setOneofUint32(42);
assertEquals(msg.getOneofUint32(), 42);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
assertTrue(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
var submsg = new proto.jspb.test.ForeignMessage();
msg.setOneofForeignMessage(submsg);
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), submsg);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes(), '');
assertFalse(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
msg.setOneofString('hello');
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), 'hello');
assertEquals(msg.getOneofBytes(), '');
assertFalse(msg.hasOneofUint32());
assertTrue(msg.hasOneofString());
assertFalse(msg.hasOneofBytes());
msg.setOneofBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
assertEquals(msg.getOneofUint32(), 0);
assertEquals(msg.getOneofForeignMessage(), undefined);
assertEquals(msg.getOneofString(), '');
assertEquals(msg.getOneofBytes_asB64(),
goog.crypt.base64.encodeString('\u00FF\u00FF'));
assertFalse(msg.hasOneofUint32());
assertFalse(msg.hasOneofString());
assertTrue(msg.hasOneofBytes());
});
/**
* Test that "default"-valued primitive fields are not emitted on the wire.
*/
it('testNoSerializeDefaults', function() {
var msg = new proto.jspb.test.TestProto3();
// Set each primitive to a non-default value, then back to its default, to
// ensure that the serialization is actually checking the value and not just
// whether it has ever been set.
msg.setOptionalInt32(42);
msg.setOptionalInt32(0);
msg.setOptionalDouble(3.14);
msg.setOptionalDouble(0.0);
msg.setOptionalBool(true);
msg.setOptionalBool(false);
msg.setOptionalString('hello world');
msg.setOptionalString('');
msg.setOptionalBytes(goog.crypt.base64.encodeString('\u00FF\u00FF'));
msg.setOptionalBytes('');
msg.setOptionalForeignMessage(new proto.jspb.test.ForeignMessage());
msg.setOptionalForeignMessage(null);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO);
msg.setOneofUint32(32);
msg.clearOneofUint32();
var serialized = msg.serializeBinary();
assertEquals(0, serialized.length);
});
/**
* Test that base64 string and Uint8Array are interchangeable in bytes fields.
*/
it('testBytesFieldsInterop', function() {
var msg = new proto.jspb.test.TestProto3();
// Set as 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));
// Test binary serialize round trip doesn't break it.
msg = proto.jspb.test.TestProto3.deserializeBinary(msg.serializeBinary());
assertTrue(bytesCompare(msg.getOptionalBytes_asU8(), BYTES));
assertTrue(bytesCompare(msg.getOptionalBytes_asB64(), BYTES));
assertTrue(bytesCompare(msg.getOptionalBytes(), BYTES));
msg = new proto.jspb.test.TestProto3();
// Set as 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));
});
});

View File

@ -1,89 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto3";
import "testbinary.proto";
package jspb.test;
message TestProto3 {
int32 optional_int32 = 1;
int64 optional_int64 = 2;
uint32 optional_uint32 = 3;
uint64 optional_uint64 = 4;
sint32 optional_sint32 = 5;
sint64 optional_sint64 = 6;
fixed32 optional_fixed32 = 7;
fixed64 optional_fixed64 = 8;
sfixed32 optional_sfixed32 = 9;
sfixed64 optional_sfixed64 = 10;
float optional_float = 11;
double optional_double = 12;
bool optional_bool = 13;
string optional_string = 14;
bytes optional_bytes = 15;
ForeignMessage optional_foreign_message = 19;
Proto3Enum optional_foreign_enum = 22;
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated ForeignMessage repeated_foreign_message = 49;
repeated Proto3Enum repeated_foreign_enum = 52;
oneof oneof_field {
uint32 oneof_uint32 = 111;
ForeignMessage oneof_foreign_message = 112;
string oneof_string = 113;
bytes oneof_bytes = 114;
}
}
enum Proto3Enum {
PROTO3_FOO = 0;
PROTO3_BAR = 1;
PROTO3_BAZ = 2;
}

View File

@ -1,262 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: mwr@google.com (Mark Rawling)
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
import "google/protobuf/descriptor.proto";
package jspb.test;
message Empty {
}
enum OuterEnum {
FOO = 1;
BAR = 2;
}
message EnumContainer {
optional OuterEnum outer_enum = 1;
}
message Simple1 {
required string a_string = 1;
repeated string a_repeated_string = 2;
optional bool a_boolean = 3;
}
// A message that differs from Simple1 only by name
message Simple2 {
required string a_string = 1;
repeated string a_repeated_string = 2;
}
message SpecialCases {
required string normal = 1;
// Examples of Js reserved names that are converted to pb_<name>.
required string default = 2;
required string function = 3;
required string var = 4;
}
message OptionalFields {
message Nested {
optional int32 an_int = 1;
}
optional string a_string = 1;
required bool a_bool = 2;
optional Nested a_nested_message = 3;
repeated Nested a_repeated_message = 4;
repeated string a_repeated_string = 5;
}
message HasExtensions {
optional string str1 = 1;
optional string str2 = 2;
optional string str3 = 3;
extensions 10 to max;
}
message Complex {
message Nested {
required int32 an_int = 2;
}
required string a_string = 1;
required bool an_out_of_order_bool = 9;
optional Nested a_nested_message = 4;
repeated Nested a_repeated_message = 5;
repeated string a_repeated_string = 7;
}
message OuterMessage {
// Make sure this doesn't conflict with the other Complex message.
message Complex {
optional int32 inner_complex_field = 1;
}
}
message IsExtension {
extend HasExtensions {
optional IsExtension ext_field = 100;
}
optional string ext1 = 1;
// Extensions of proto2 Descriptor messages will be ignored.
extend google.protobuf.EnumOptions {
optional string simple_option = 42113038;
}
}
message IndirectExtension {
extend HasExtensions {
optional Simple1 simple = 101;
optional string str = 102;
repeated string repeated_str = 103;
repeated Simple1 repeated_simple = 104;
}
}
extend HasExtensions {
optional Simple1 simple1 = 105;
}
message DefaultValues {
enum Enum {
E1 = 13;
E2 = 77;
}
optional string string_field = 1 [default="default<>\'\"abc"];
optional bool bool_field = 2 [default=true];
optional int64 int_field = 3 [default=11];
optional Enum enum_field = 4 [default=E1];
optional string empty_field = 6 [default=""];
optional bytes bytes_field = 8 [default="moo"]; // Base64 encoding is "bW9v"
}
message FloatingPointFields {
optional float optional_float_field = 1;
required float required_float_field = 2;
repeated float repeated_float_field = 3;
optional float default_float_field = 4 [default = 2.0];
optional double optional_double_field = 5;
required double required_double_field = 6;
repeated double repeated_double_field = 7;
optional double default_double_field = 8 [default = 2.0];
}
message TestClone {
optional string str = 1;
optional Simple1 simple1 = 3;
repeated Simple1 simple2 = 5;
optional bytes bytes_field = 6;
optional string unused = 7;
extensions 10 to max;
}
message CloneExtension {
extend TestClone {
optional CloneExtension ext_field = 100;
}
optional string ext = 2;
}
message TestGroup {
repeated group RepeatedGroup = 1 {
required string id = 1;
repeated bool some_bool = 2;
}
required group RequiredGroup = 2 {
required string id = 1;
}
optional group OptionalGroup = 3 {
required string id = 1;
}
optional string id = 4;
required Simple2 required_simple = 5;
optional Simple2 optional_simple = 6;
}
message TestGroup1 {
optional TestGroup.RepeatedGroup group = 1;
}
message TestReservedNames {
optional int32 extension = 1;
extensions 10 to max;
}
message TestReservedNamesExtension {
extend TestReservedNames {
optional int32 foo = 10;
}
}
message TestMessageWithOneof {
oneof partial_oneof {
string pone = 3;
string pthree = 5;
}
oneof recursive_oneof {
TestMessageWithOneof rone = 6;
string rtwo = 7;
}
optional bool normal_field = 8;
repeated string repeated_field = 9;
oneof default_oneof_a {
int32 aone = 10 [default = 1234];
int32 atwo = 11;
}
oneof default_oneof_b {
int32 bone = 12;
int32 btwo = 13 [default = 1234];
}
}
message TestEndsWithBytes {
optional int32 value = 1;
optional bytes data = 2;
}
message TestMapFieldsNoBinary {
map<string, string> map_string_string = 1;
map<string, int32> map_string_int32 = 2;
map<string, int64> map_string_int64 = 3;
map<string, bool> map_string_bool = 4;
map<string, double> map_string_double = 5;
map<string, MapValueEnumNoBinary> map_string_enum = 6;
map<string, MapValueMessageNoBinary> map_string_msg = 7;
map<int32, string> map_int32_string = 8;
map<int64, string> map_int64_string = 9;
map<bool, string> map_bool_string = 10;
optional TestMapFieldsNoBinary test_map_fields = 11;
map<string, TestMapFieldsNoBinary> map_string_testmapfields = 12;
}
enum MapValueEnumNoBinary {
MAP_VALUE_FOO_NOBINARY = 0;
MAP_VALUE_BAR_NOBINARY = 1;
MAP_VALUE_BAZ_NOBINARY = 2;
}
message MapValueMessageNoBinary {
optional int32 foo = 1;
}

View File

@ -1,54 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.test;
message TestExtensionsMessage {
optional int32 intfield = 1;
extensions 100 to max;
}
message ExtensionMessage {
extend TestExtensionsMessage {
optional ExtensionMessage ext_field = 100;
}
optional string ext1 = 1;
}
// Floating extensions are only supported when generating a _lib.js library.
extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field = 101;
optional string floating_str_field = 102;
}

View File

@ -1,53 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.exttest;
message TestExtensionsMessage {
optional int32 intfield = 1;
extensions 100 to max;
}
message ExtensionMessage {
extend TestExtensionsMessage {
optional ExtensionMessage ext_field = 100;
}
optional string ext1 = 1;
}
extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field = 101;
optional string floating_str_field = 102;
}

View File

@ -1,42 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.exttest;
import "test3.proto";
extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field_two = 103;
}

View File

@ -1,44 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
package jspb.exttest.beta;
message TestBetaExtensionsMessage {
extensions 100 to max;
}
extend TestBetaExtensionsMessage {
optional string floating_str_field = 101;
}

View File

@ -1,212 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// LINT: ALLOW_GROUPS
syntax = "proto2";
package jspb.test;
// These types are borrowed from `unittest.proto` in the protobuf tree. We want
// to ensure that the binary-format support will handle all field types
// properly.
message TestAllTypes {
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional ForeignMessage optional_foreign_message = 19;
optional ForeignEnum optional_foreign_enum = 22;
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated ForeignMessage repeated_foreign_message = 49;
repeated ForeignEnum repeated_foreign_enum = 52;
// Packed repeated
repeated int32 packed_repeated_int32 = 61 [packed=true];
repeated int64 packed_repeated_int64 = 62 [packed=true];
repeated uint32 packed_repeated_uint32 = 63 [packed=true];
repeated uint64 packed_repeated_uint64 = 64 [packed=true];
repeated sint32 packed_repeated_sint32 = 65 [packed=true];
repeated sint64 packed_repeated_sint64 = 66 [packed=true];
repeated fixed32 packed_repeated_fixed32 = 67 [packed=true];
repeated fixed64 packed_repeated_fixed64 = 68 [packed=true];
repeated sfixed32 packed_repeated_sfixed32 = 69 [packed=true];
repeated sfixed64 packed_repeated_sfixed64 = 70 [packed=true];
repeated float packed_repeated_float = 71 [packed=true];
repeated double packed_repeated_double = 72 [packed=true];
repeated bool packed_repeated_bool = 73 [packed=true];
oneof oneof_field {
uint32 oneof_uint32 = 111;
ForeignMessage oneof_foreign_message = 112;
string oneof_string = 113;
bytes oneof_bytes = 114;
}
}
message ForeignMessage {
optional int32 c = 1;
}
enum ForeignEnum {
FOREIGN_FOO = 4;
FOREIGN_BAR = 5;
FOREIGN_BAZ = 6;
}
message TestExtendable {
extensions 1 to max;
}
message ExtendsWithMessage {
extend TestExtendable {
optional ExtendsWithMessage optional_extension = 19;
repeated ExtendsWithMessage repeated_extension = 49;
}
optional int32 foo = 1;
}
extend TestExtendable {
optional int32 extend_optional_int32 = 1;
optional int64 extend_optional_int64 = 2;
optional uint32 extend_optional_uint32 = 3;
optional uint64 extend_optional_uint64 = 4;
optional sint32 extend_optional_sint32 = 5;
optional sint64 extend_optional_sint64 = 6;
optional fixed32 extend_optional_fixed32 = 7;
optional fixed64 extend_optional_fixed64 = 8;
optional sfixed32 extend_optional_sfixed32 = 9;
optional sfixed64 extend_optional_sfixed64 = 10;
optional float extend_optional_float = 11;
optional double extend_optional_double = 12;
optional bool extend_optional_bool = 13;
optional string extend_optional_string = 14;
optional bytes extend_optional_bytes = 15;
optional ForeignEnum extend_optional_foreign_enum = 22;
repeated int32 extend_repeated_int32 = 31;
repeated int64 extend_repeated_int64 = 32;
repeated uint32 extend_repeated_uint32 = 33;
repeated uint64 extend_repeated_uint64 = 34;
repeated sint32 extend_repeated_sint32 = 35;
repeated sint64 extend_repeated_sint64 = 36;
repeated fixed32 extend_repeated_fixed32 = 37;
repeated fixed64 extend_repeated_fixed64 = 38;
repeated sfixed32 extend_repeated_sfixed32 = 39;
repeated sfixed64 extend_repeated_sfixed64 = 40;
repeated float extend_repeated_float = 41;
repeated double extend_repeated_double = 42;
repeated bool extend_repeated_bool = 43;
repeated string extend_repeated_string = 44;
repeated bytes extend_repeated_bytes = 45;
repeated ForeignEnum extend_repeated_foreign_enum = 52;
repeated int32 extend_packed_repeated_int32 = 61 [packed=true];
repeated int64 extend_packed_repeated_int64 = 62 [packed=true];
repeated uint32 extend_packed_repeated_uint32 = 63 [packed=true];
repeated uint64 extend_packed_repeated_uint64 = 64 [packed=true];
repeated sint32 extend_packed_repeated_sint32 = 65 [packed=true];
repeated sint64 extend_packed_repeated_sint64 = 66 [packed=true];
repeated fixed32 extend_packed_repeated_fixed32 = 67 [packed=true];
repeated fixed64 extend_packed_repeated_fixed64 = 68 [packed=true];
repeated sfixed32 extend_packed_repeated_sfixed32 = 69 [packed=true];
repeated sfixed64 extend_packed_repeated_sfixed64 = 70 [packed=true];
repeated float extend_packed_repeated_float = 71 [packed=true];
repeated double extend_packed_repeated_double = 72 [packed=true];
repeated bool extend_packed_repeated_bool = 73 [packed=true];
repeated ForeignEnum extend_packed_repeated_foreign_enum = 82
[packed=true];
}
message TestMapFields {
map<string, string> map_string_string = 1;
map<string, int32> map_string_int32 = 2;
map<string, int64> map_string_int64 = 3;
map<string, bool> map_string_bool = 4;
map<string, double> map_string_double = 5;
map<string, MapValueEnum> map_string_enum = 6;
map<string, MapValueMessage> map_string_msg = 7;
map<int32, string> map_int32_string = 8;
map<int64, string> map_int64_string = 9;
map<bool, string> map_bool_string = 10;
optional TestMapFields test_map_fields = 11;
map<string, TestMapFields> map_string_testmapfields = 12;
}
enum MapValueEnum {
MAP_VALUE_FOO = 0;
MAP_VALUE_BAR = 1;
MAP_VALUE_BAZ = 2;
}
message MapValueMessage {
optional int32 foo = 1;
}

View File

@ -1,34 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
syntax = "proto2";
package javatests.com.google.apps.jspb;

View File

@ -1,50 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: mwr@google.com (Mark Rawling)
syntax = "proto2";
package jspb.test;
option java_package = "com.google.apps.jspb.proto";
option java_multiple_files = true;
// legacy data, must be nested
message data {
message NestedData {
required string str = 1;
}
}
// new data, does not require nesting
message UnnestedData {
required string str = 1;
}

View File

@ -1,159 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Utilities to debug JSPB based proto objects.
*/
goog.provide('jspb.debug');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.object');
goog.require('jspb.Map');
goog.require('jspb.Message');
/**
* Turns a proto into a human readable object that can i.e. be written to the
* console: `console.log(jspb.debug.dump(myProto))`.
* This function makes a best effort and may not work in all cases. It will not
* work in obfuscated and or optimized code.
* Use this in environments where {@see jspb.Message.prototype.toObject} is
* not available for code size reasons.
* @param {jspb.Message} message A jspb.Message.
* @return {Object}
*/
jspb.debug.dump = function(message) {
if (!goog.DEBUG) {
return null;
}
goog.asserts.assert(message instanceof jspb.Message,
'jspb.Message instance expected');
/** @type {Object} */
var object = message;
goog.asserts.assert(object['getExtension'],
'Only unobfuscated and unoptimized compilation modes supported.');
return /** @type {Object} */ (jspb.debug.dump_(message));
};
/**
* Recursively introspects a message and the values its getters return to
* make a best effort in creating a human readable representation of the
* message.
* @param {?} thing A jspb.Message, Array or primitive type to dump.
* @return {*}
* @private
*/
jspb.debug.dump_ = function(thing) {
var type = goog.typeOf(thing);
var message = thing; // Copy because we don't want type inference on thing.
if (type == 'number' || type == 'string' || type == 'boolean' ||
type == 'null' || type == 'undefined') {
return thing;
}
if (typeof Uint8Array !== 'undefined') {
// Will fail on IE9, where Uint8Array doesn't exist.
if (message instanceof Uint8Array) {
return thing;
}
}
if (type == 'array') {
goog.asserts.assertArray(thing);
return goog.array.map(thing, jspb.debug.dump_);
}
if (message instanceof jspb.Map) {
var mapObject = {};
var entries = message.entries();
for (var entry = entries.next(); !entry.done; entry = entries.next()) {
mapObject[entry.value[0]] = jspb.debug.dump_(entry.value[1]);
}
return mapObject;
}
goog.asserts.assert(message instanceof jspb.Message,
'Only messages expected: ' + thing);
var ctor = message.constructor;
var messageName = ctor.name || ctor.displayName;
var object = {
'$name': messageName
};
for (var name in ctor.prototype) {
var match = /^get([A-Z]\w*)/.exec(name);
if (match && name != 'getExtension' &&
name != 'getJsPbMessageId') {
var has = 'has' + match[1];
if (!thing[has] || thing[has]()) {
var val = thing[name]();
object[jspb.debug.formatFieldName_(match[1])] = jspb.debug.dump_(val);
}
}
}
if (COMPILED && thing['extensionObject_']) {
object['$extensions'] = 'Recursive dumping of extensions not supported ' +
'in compiled code. Switch to uncompiled or dump extension object ' +
'directly';
return object;
}
var extensionsObject;
for (var id in ctor['extensions']) {
if (/^\d+$/.test(id)) {
var ext = ctor['extensions'][id];
var extVal = thing.getExtension(ext);
var fieldName = goog.object.getKeys(ext.fieldName)[0];
if (extVal != null) {
if (!extensionsObject) {
extensionsObject = object['$extensions'] = {};
}
extensionsObject[jspb.debug.formatFieldName_(fieldName)] =
jspb.debug.dump_(extVal);
}
}
}
return object;
};
/**
* Formats a field name for output as camelCase.
*
* @param {string} name Name of the field.
* @return {string}
* @private
*/
jspb.debug.formatFieldName_ = function(name) {
// Name may be in TitleCase.
return name.replace(/^[A-Z]/, function(c) {
return c.toLowerCase();
});
};

View File

@ -1,188 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
goog.setTestOnly();
goog.require('goog.testing.asserts');
// CommonJS-LoadFromFile: google-protobuf
goog.require('jspb.debug');
// CommonJS-LoadFromFile: test_pb
goog.require('proto.jspb.test.HasExtensions');
goog.require('proto.jspb.test.IsExtension');
goog.require('proto.jspb.test.MapValueMessageNoBinary');
goog.require('proto.jspb.test.Simple1');
goog.require('proto.jspb.test.TestMapFieldsNoBinary');
// CommonJS-LoadFromFile: testbinary_pb
goog.require('proto.jspb.test.TestAllTypes');
describe('debugTest', function() {
it('testSimple1', function() {
if (COMPILED) {
return;
}
var message = new proto.jspb.test.Simple1();
message.setAString('foo');
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': []
}, jspb.debug.dump(message));
message.setABoolean(true);
message.setARepeatedStringList(['1', '2']);
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
message.clearAString();
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
});
it('testBytes', function() {
if (COMPILED || typeof Uint8Array == 'undefined') {
return;
}
var message = new proto.jspb.test.TestAllTypes();
var bytes = new Uint8Array(4);
message.setOptionalBytes(bytes);
assertEquals(jspb.debug.dump(message)['optionalBytes'], bytes);
});
it('testExtensions', function() {
if (COMPILED) {
return;
}
var extension = new proto.jspb.test.IsExtension();
extension.setExt1('ext1field');
var extendable = new proto.jspb.test.HasExtensions();
extendable.setStr1('v1');
extendable.setStr2('v2');
extendable.setStr3('v3');
extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
assertObjectEquals({
'$name': 'proto.jspb.test.HasExtensions',
'str1': 'v1',
'str2': 'v2',
'str3': 'v3',
'$extensions': {
'extField': {
'$name': 'proto.jspb.test.IsExtension',
'ext1': 'ext1field'
},
'repeatedSimpleList': []
}
}, jspb.debug.dump(extendable));
});
it('testMapsBasicTypes', function() {
if (COMPILED) {
return;
}
var message = new proto.jspb.test.TestMapFieldsNoBinary();
message.getMapBoolStringMap().set(true, 'bool_string_value1');
message.getMapBoolStringMap().set(false, 'bool_string_value2');
message.getMapStringInt32Map().set('key', 111);
assertObjectEquals({
'$name': 'proto.jspb.test.TestMapFieldsNoBinary',
'mapBoolStringMap': {
true: 'bool_string_value1',
false: 'bool_string_value2'
},
'mapInt32StringMap': {},
'mapInt64StringMap': {},
'mapStringBoolMap': {},
'mapStringDoubleMap': {},
'mapStringEnumMap': {},
'mapStringInt32Map': {
'key': 111
},
'mapStringInt64Map': {},
'mapStringMsgMap': {},
'mapStringStringMap': {},
'mapStringTestmapfieldsMap': {}
}, jspb.debug.dump(message));
});
it('testMapsMessageValues', function() {
if (COMPILED) {
return;
}
var value1 = new proto.jspb.test.MapValueMessageNoBinary();
value1.setFoo(1111);
var value2 = new proto.jspb.test.MapValueMessageNoBinary();
value2.setFoo(2222);
var message = new proto.jspb.test.TestMapFieldsNoBinary();
message.getMapStringMsgMap().set('key1', value1);
message.getMapStringMsgMap().set('key2', value2);
assertObjectEquals({
'$name': 'proto.jspb.test.TestMapFieldsNoBinary',
'mapBoolStringMap': {},
'mapInt32StringMap': {},
'mapInt64StringMap': {},
'mapStringBoolMap': {},
'mapStringDoubleMap': {},
'mapStringEnumMap': {},
'mapStringInt32Map': {},
'mapStringInt64Map': {},
'mapStringMsgMap': {
'key1': {
'$name': 'proto.jspb.test.MapValueMessageNoBinary',
'foo': 1111
},
'key2': {
'$name': 'proto.jspb.test.MapValueMessageNoBinary',
'foo': 2222
}
},
'mapStringStringMap': {},
'mapStringTestmapfieldsMap': {}
}, jspb.debug.dump(message));
});
});

View File

@ -1,312 +0,0 @@
/**
* @fileoverview The code size benchmark of apps JSPB for proto2 all types
*/
goog.module('protobuf.benchmark.code_size.apps_jspb.AllTypesProto2');
// const ForeignEnum = goog.require('proto.proto2_unittest.ForeignEnum');
const ForeignMessage = goog.require('proto.proto2_unittest.ForeignMessage');
const TestAllTypes = goog.require('proto.proto2_unittest.TestAllTypes');
const TestPackedTypes = goog.require('proto.proto2_unittest.TestPackedTypes');
const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
ensureCommonBaseLine();
/**
* The testing scenario is the same as kernel one.
* We have
* 1) add element to repeated fields
* 2) add element list to repeated fields
* 3) set fields
* 4) set repeated fields element
* 5) get fields
* 6) get repeated fields element
* 7) get repeated fields length
* @return {string}
*/
function accessAllTypes() {
const msgAllTypes = TestAllTypes.deserialize('');
const msgPackedTypes = TestPackedTypes.deserialize('');
msgPackedTypes.addPackedBool(true);
[true].forEach((e) => msgPackedTypes.addPackedBool(e));
msgAllTypes.addRepeatedBool(true, 1);
[true].forEach((e) => msgAllTypes.addRepeatedBool(e));
msgAllTypes.addRepeatedBytes('1', 1);
['1'].forEach((e) => msgAllTypes.addRepeatedBytes(e));
msgPackedTypes.addPackedDouble(1.0);
[1.0].forEach((e) => msgPackedTypes.addPackedDouble(e));
msgAllTypes.addRepeatedDouble(1.0, 1);
[1.0].forEach((e) => msgAllTypes.addRepeatedDouble(e));
msgPackedTypes.addPackedFixed32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedFixed32(e));
msgAllTypes.addRepeatedFixed32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedFixed32(e));
msgPackedTypes.addPackedFixed64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedFixed64(e));
msgAllTypes.addRepeatedFixed64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedFixed64(e));
msgPackedTypes.addPackedFloat(1.0, 1);
[1.0].forEach((e) => msgPackedTypes.addPackedFloat(e));
msgAllTypes.addRepeatedFloat(1.0, 1);
[1.0].forEach((e) => msgAllTypes.addRepeatedFloat(e));
msgPackedTypes.addPackedInt32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedInt32(e));
msgAllTypes.addRepeatedInt32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedInt32(e));
msgPackedTypes.addPackedInt64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedInt64(e));
msgAllTypes.addRepeatedInt64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedInt64(e));
// msgPackedTypes.addPackedEnum(ForeignEnum.FOREIGN_BAR);
// [ForeignEnum.FOREIGN_BAR].forEach((e) => msgPackedTypes.addPackedEnum(e));
// msgAllTypes.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
// [ForeignEnum.FOREIGN_BAR].forEach(
// (e) => msgAllTypes.addRepeatedForeignEnum(e));
msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
[ForeignMessage.deserialize('')].forEach(
(e) => msgAllTypes.addRepeatedForeignMessage(e));
msgPackedTypes.addPackedSfixed32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSfixed32(e));
msgAllTypes.addRepeatedSfixed32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSfixed32(e));
msgPackedTypes.addPackedSfixed64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSfixed64(e));
msgAllTypes.addRepeatedSfixed64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSfixed64(e));
msgPackedTypes.addPackedSint32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSint32(e));
msgAllTypes.addRepeatedSint32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSint32(e));
msgPackedTypes.addPackedSint64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSint64(e));
msgAllTypes.addRepeatedSint64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSint64(e));
msgAllTypes.addRepeatedString('', 1);
[''].forEach((e) => msgAllTypes.addRepeatedString(e));
msgPackedTypes.addPackedUint32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedUint32(e));
msgAllTypes.addRepeatedUint32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedUint32(e));
msgPackedTypes.addPackedUint64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedUint64(e));
msgAllTypes.addRepeatedUint64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedUint64(e));
msgAllTypes.setOptionalBool(true);
msgAllTypes.setOptionalBytes('');
msgAllTypes.setOptionalDouble(1.0);
msgAllTypes.setOptionalFixed32(1);
msgAllTypes.setOptionalFixed64(1);
msgAllTypes.setOptionalFloat(1.0);
msgAllTypes.setOptionalInt32(1);
msgAllTypes.setOptionalInt64(1);
// msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
msgAllTypes.setOptionalSfixed32(1);
msgAllTypes.setOptionalSfixed64(1);
msgAllTypes.setOptionalSint32(1);
msgAllTypes.setOptionalSint64(1);
msgAllTypes.setOptionalString('');
msgAllTypes.setOptionalUint32(1);
msgAllTypes.setOptionalUint64(1);
msgPackedTypes.setPackedBoolList([true]);
let arrayVal;
arrayVal = msgPackedTypes.getPackedBoolList();
arrayVal[0] = true;
msgPackedTypes.setPackedBoolList(arrayVal);
msgAllTypes.setRepeatedBoolList([true]);
arrayVal = msgAllTypes.getRepeatedBoolList();
arrayVal[0] = true;
msgAllTypes.setRepeatedBoolList(arrayVal);
msgAllTypes.setRepeatedBytesList(['']);
arrayVal = msgAllTypes.getRepeatedBytesList_asB64();
arrayVal[0] = '';
msgAllTypes.setRepeatedBytesList(arrayVal);
msgPackedTypes.setPackedDoubleList([1.0]);
arrayVal = msgPackedTypes.getPackedDoubleList();
arrayVal[0] = 1.0;
msgPackedTypes.setPackedDoubleList(arrayVal);
msgAllTypes.setRepeatedDoubleList([1.0]);
arrayVal = msgAllTypes.getRepeatedDoubleList();
arrayVal[0] = 1.0;
msgAllTypes.setRepeatedDoubleList(arrayVal);
msgPackedTypes.setPackedFixed32List([1]);
arrayVal = msgPackedTypes.getPackedFixed32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedFixed32List(arrayVal);
msgAllTypes.setRepeatedFixed32List([1]);
arrayVal = msgAllTypes.getRepeatedFixed32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedFixed32List(arrayVal);
msgPackedTypes.setPackedFixed64List([1]);
arrayVal = msgPackedTypes.getPackedFixed64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedFixed64List(arrayVal);
msgAllTypes.setRepeatedFixed64List([1]);
arrayVal = msgAllTypes.getRepeatedFixed64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedFixed64List(arrayVal);
msgPackedTypes.setPackedFloatList([1.0]);
arrayVal = msgPackedTypes.getPackedFloatList();
arrayVal[0] = 1.0;
msgPackedTypes.setPackedFloatList(arrayVal);
msgAllTypes.setRepeatedFloatList([1.0]);
arrayVal = msgAllTypes.getRepeatedFloatList();
arrayVal[0] = 1.0;
msgAllTypes.setRepeatedFloatList(arrayVal);
msgPackedTypes.setPackedInt32List([1]);
arrayVal = msgPackedTypes.getPackedInt32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedInt32List(arrayVal);
msgAllTypes.setRepeatedInt32List([1]);
arrayVal = msgAllTypes.getRepeatedInt32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedInt32List(arrayVal);
msgPackedTypes.setPackedInt64List([1]);
arrayVal = msgPackedTypes.getPackedInt64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedInt64List(arrayVal);
msgAllTypes.setRepeatedInt64List([1]);
arrayVal = msgAllTypes.getRepeatedInt64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedInt64List(arrayVal);
// msgPackedTypes.setPackedEnumList([ForeignEnum.FOREIGN_BAR]);
// arrayVal = msgPackedTypes.getPackedEnumList();
// arrayVal[0] = ForeignEnum.FOREIGN_BAR;
// msgPackedTypes.setPackedEnumList(arrayVal);
// msgAllTypes.setRepeatedForeignEnumList([ForeignEnum.FOREIGN_BAR]);
// arrayVal = msgAllTypes.getRepeatedForeignEnumList();
// arrayVal[0] = ForeignEnum.FOREIGN_BAR;
// msgAllTypes.setRepeatedForeignEnumList(arrayVal);
msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
arrayVal = msgAllTypes.getRepeatedForeignMessageList();
arrayVal[0] = ForeignMessage.deserialize('');
msgAllTypes.setRepeatedForeignMessageList(arrayVal);
msgPackedTypes.setPackedSfixed32List([1]);
arrayVal = msgPackedTypes.getPackedSfixed32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSfixed32List(arrayVal);
msgAllTypes.setRepeatedSfixed32List([1]);
arrayVal = msgAllTypes.getRepeatedSfixed32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSfixed32List(arrayVal);
msgPackedTypes.setPackedSfixed64List([1]);
arrayVal = msgPackedTypes.getPackedSfixed64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSfixed64List(arrayVal);
msgAllTypes.setRepeatedSfixed64List([1]);
arrayVal = msgAllTypes.getRepeatedSfixed64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSfixed64List(arrayVal);
msgPackedTypes.setPackedSint32List([1]);
arrayVal = msgPackedTypes.getPackedSint32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSint32List(arrayVal);
msgAllTypes.setRepeatedSint32List([1]);
arrayVal = msgAllTypes.getRepeatedSint32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSint32List(arrayVal);
msgPackedTypes.setPackedSint64List([1]);
arrayVal = msgPackedTypes.getPackedSint64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSint64List(arrayVal);
msgAllTypes.setRepeatedSint64List([1]);
arrayVal = msgAllTypes.getRepeatedSint64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSint64List(arrayVal);
msgPackedTypes.setPackedUint32List([1]);
arrayVal = msgPackedTypes.getPackedUint32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedUint32List(arrayVal);
msgAllTypes.setRepeatedUint32List([1]);
arrayVal = msgAllTypes.getRepeatedUint32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedUint32List(arrayVal);
msgPackedTypes.setPackedUint64List([1]);
arrayVal = msgPackedTypes.getPackedUint64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedUint64List(arrayVal);
msgAllTypes.setRepeatedUint64List([1]);
arrayVal = msgAllTypes.getRepeatedUint64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedUint64List(arrayVal);
let s = '';
s += msgAllTypes.getOptionalBool() || false;
s += msgAllTypes.getOptionalBytes_asB64() || '';
// s += msgAllTypes.getOptionalBytes_asU8() || new Uint8Array([]);
s += msgAllTypes.getOptionalDouble() || 0.0;
s += msgAllTypes.getOptionalFixed32() || 0;
s += msgAllTypes.getOptionalFixed64() || 0;
s += msgAllTypes.getOptionalFloat() || 0.0;
s += msgAllTypes.getOptionalInt32() || 0;
s += msgAllTypes.getOptionalInt64() || 0;
// s += msgAllTypes.getOptionalForeignEnum() || ForeignEnum.FOREIGN_BAR;
s += msgAllTypes.getOptionalForeignMessage();
s += msgAllTypes.getOptionalSfixed32() || 0;
s += msgAllTypes.getOptionalSfixed64() || 0;
s += msgAllTypes.getOptionalSint32() || 0;
s += msgAllTypes.getOptionalSint64() || 0;
s += msgAllTypes.getOptionalString() || '';
s += msgAllTypes.getOptionalUint32() || 0;
s += msgAllTypes.getOptionalUint64() || 0;
s += msgAllTypes.getRepeatedBoolList();
s += msgAllTypes.getRepeatedBoolList()[0];
s += msgAllTypes.getRepeatedBoolList().length;
s += msgAllTypes.getRepeatedBytesList_asB64();
s += msgAllTypes.getRepeatedBytesList_asB64()[0];
s += msgAllTypes.getRepeatedBytesList_asB64().length;
s += msgAllTypes.getRepeatedBytesList_asU8();
s += msgAllTypes.getRepeatedDoubleList();
s += msgAllTypes.getRepeatedDoubleList()[0];
s += msgAllTypes.getRepeatedDoubleList().length;
s += msgAllTypes.getRepeatedFixed32List();
s += msgAllTypes.getRepeatedFixed32List()[0];
s += msgAllTypes.getRepeatedFixed32List().length;
s += msgAllTypes.getRepeatedFixed64List();
s += msgAllTypes.getRepeatedFixed64List()[0];
s += msgAllTypes.getRepeatedFixed64List().length;
s += msgAllTypes.getRepeatedFloatList();
s += msgAllTypes.getRepeatedFloatList()[0];
s += msgAllTypes.getRepeatedFloatList().length;
s += msgAllTypes.getRepeatedInt32List();
s += msgAllTypes.getRepeatedInt32List()[0];
s += msgAllTypes.getRepeatedInt32List().length;
s += msgAllTypes.getRepeatedInt64List();
s += msgAllTypes.getRepeatedInt64List()[0];
s += msgAllTypes.getRepeatedInt64List().length;
// s += msgAllTypes.getRepeatedForeignEnumList();
// s += msgAllTypes.getRepeatedForeignEnumList()[0];
// s += msgAllTypes.getRepeatedForeignEnumList().length;
s += msgAllTypes.getRepeatedForeignMessageList();
s += msgAllTypes.getRepeatedForeignMessageList()[0];
s += msgAllTypes.getRepeatedForeignMessageList().length;
s += msgAllTypes.getRepeatedSfixed32List();
s += msgAllTypes.getRepeatedSfixed32List()[0];
s += msgAllTypes.getRepeatedSfixed32List().length;
s += msgAllTypes.getRepeatedSfixed64List();
s += msgAllTypes.getRepeatedSfixed64List()[0];
s += msgAllTypes.getRepeatedSfixed64List().length;
s += msgAllTypes.getRepeatedSint32List();
s += msgAllTypes.getRepeatedSint32List()[0];
s += msgAllTypes.getRepeatedSint32List().length;
s += msgAllTypes.getRepeatedSint64List();
s += msgAllTypes.getRepeatedSint64List()[0];
s += msgAllTypes.getRepeatedSint64List().length;
s += msgAllTypes.getRepeatedStringList();
s += msgAllTypes.getRepeatedStringList()[0];
s += msgAllTypes.getRepeatedStringList().length;
s += msgAllTypes.getRepeatedUint32List();
s += msgAllTypes.getRepeatedUint32List()[0];
s += msgAllTypes.getRepeatedUint32List().length;
s += msgAllTypes.getRepeatedUint64List();
s += msgAllTypes.getRepeatedUint64List()[0];
s += msgAllTypes.getRepeatedUint64List().length;
s += msgAllTypes.serialize();
s += msgPackedTypes.serialize();
return s;
}
goog.global['__hiddenTest'] += accessAllTypes();

View File

@ -1,312 +0,0 @@
/**
* @fileoverview The code size benchmark of apps JSPB for proto3 all types
*/
goog.module('protobuf.benchmark.code_size.apps_jspb.AllTypesProto3');
// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum');
const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage');
const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes');
const TestPackedTypes = goog.require('proto.proto3_unittest.TestPackedTypes');
const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
ensureCommonBaseLine();
/**
* The testing scenario is the same as kernel one.
* We have
* 1) add element to repeated fields
* 2) add element list to repeated fields
* 3) set fields
* 4) set repeated fields element
* 5) get fields
* 6) get repeated fields element
* 7) get repeated fields length
* @return {string}
*/
function accessAllTypes() {
const msgAllTypes = TestAllTypes.deserialize('');
const msgPackedTypes = TestPackedTypes.deserialize('');
msgPackedTypes.addPackedBool(true);
[true].forEach((e) => msgPackedTypes.addPackedBool(e));
msgAllTypes.addRepeatedBool(true, 1);
[true].forEach((e) => msgAllTypes.addRepeatedBool(e));
msgAllTypes.addRepeatedBytes('1', 1);
['1'].forEach((e) => msgAllTypes.addRepeatedBytes(e));
msgPackedTypes.addPackedDouble(1.0);
[1.0].forEach((e) => msgPackedTypes.addPackedDouble(e));
msgAllTypes.addRepeatedDouble(1.0, 1);
[1.0].forEach((e) => msgAllTypes.addRepeatedDouble(e));
msgPackedTypes.addPackedFixed32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedFixed32(e));
msgAllTypes.addRepeatedFixed32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedFixed32(e));
msgPackedTypes.addPackedFixed64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedFixed64(e));
msgAllTypes.addRepeatedFixed64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedFixed64(e));
msgPackedTypes.addPackedFloat(1.0, 1);
[1.0].forEach((e) => msgPackedTypes.addPackedFloat(e));
msgAllTypes.addRepeatedFloat(1.0, 1);
[1.0].forEach((e) => msgAllTypes.addRepeatedFloat(e));
msgPackedTypes.addPackedInt32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedInt32(e));
msgAllTypes.addRepeatedInt32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedInt32(e));
msgPackedTypes.addPackedInt64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedInt64(e));
msgAllTypes.addRepeatedInt64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedInt64(e));
// msgPackedTypes.addPackedEnum(ForeignEnum.FOREIGN_BAR);
// [ForeignEnum.FOREIGN_BAR].forEach((e) => msgPackedTypes.addPackedEnum(e));
// msgAllTypes.addRepeatedForeignEnum(ForeignEnum.FOREIGN_BAR);
// [ForeignEnum.FOREIGN_BAR].forEach(
// (e) => msgAllTypes.addRepeatedForeignEnum(e));
msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
[ForeignMessage.deserialize('')].forEach(
(e) => msgAllTypes.addRepeatedForeignMessage(e));
msgPackedTypes.addPackedSfixed32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSfixed32(e));
msgAllTypes.addRepeatedSfixed32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSfixed32(e));
msgPackedTypes.addPackedSfixed64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSfixed64(e));
msgAllTypes.addRepeatedSfixed64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSfixed64(e));
msgPackedTypes.addPackedSint32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSint32(e));
msgAllTypes.addRepeatedSint32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSint32(e));
msgPackedTypes.addPackedSint64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedSint64(e));
msgAllTypes.addRepeatedSint64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedSint64(e));
msgAllTypes.addRepeatedString('', 1);
[''].forEach((e) => msgAllTypes.addRepeatedString(e));
msgPackedTypes.addPackedUint32(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedUint32(e));
msgAllTypes.addRepeatedUint32(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedUint32(e));
msgPackedTypes.addPackedUint64(1, 1);
[1].forEach((e) => msgPackedTypes.addPackedUint64(e));
msgAllTypes.addRepeatedUint64(1, 1);
[1].forEach((e) => msgAllTypes.addRepeatedUint64(e));
msgAllTypes.setOptionalBool(true);
msgAllTypes.setOptionalBytes('');
msgAllTypes.setOptionalDouble(1.0);
msgAllTypes.setOptionalFixed32(1);
msgAllTypes.setOptionalFixed64(1);
msgAllTypes.setOptionalFloat(1.0);
msgAllTypes.setOptionalInt32(1);
msgAllTypes.setOptionalInt64(1);
// msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
msgAllTypes.setOptionalSfixed32(1);
msgAllTypes.setOptionalSfixed64(1);
msgAllTypes.setOptionalSint32(1);
msgAllTypes.setOptionalSint64(1);
msgAllTypes.setOptionalString('');
msgAllTypes.setOptionalUint32(1);
msgAllTypes.setOptionalUint64(1);
msgPackedTypes.setPackedBoolList([true]);
let arrayVal;
arrayVal = msgPackedTypes.getPackedBoolList();
arrayVal[0] = true;
msgPackedTypes.setPackedBoolList(arrayVal);
msgAllTypes.setRepeatedBoolList([true]);
arrayVal = msgAllTypes.getRepeatedBoolList();
arrayVal[0] = true;
msgAllTypes.setRepeatedBoolList(arrayVal);
msgAllTypes.setRepeatedBytesList(['']);
arrayVal = msgAllTypes.getRepeatedBytesList_asB64();
arrayVal[0] = '';
msgAllTypes.setRepeatedBytesList(arrayVal);
msgPackedTypes.setPackedDoubleList([1.0]);
arrayVal = msgPackedTypes.getPackedDoubleList();
arrayVal[0] = 1.0;
msgPackedTypes.setPackedDoubleList(arrayVal);
msgAllTypes.setRepeatedDoubleList([1.0]);
arrayVal = msgAllTypes.getRepeatedDoubleList();
arrayVal[0] = 1.0;
msgAllTypes.setRepeatedDoubleList(arrayVal);
msgPackedTypes.setPackedFixed32List([1]);
arrayVal = msgPackedTypes.getPackedFixed32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedFixed32List(arrayVal);
msgAllTypes.setRepeatedFixed32List([1]);
arrayVal = msgAllTypes.getRepeatedFixed32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedFixed32List(arrayVal);
msgPackedTypes.setPackedFixed64List([1]);
arrayVal = msgPackedTypes.getPackedFixed64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedFixed64List(arrayVal);
msgAllTypes.setRepeatedFixed64List([1]);
arrayVal = msgAllTypes.getRepeatedFixed64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedFixed64List(arrayVal);
msgPackedTypes.setPackedFloatList([1.0]);
arrayVal = msgPackedTypes.getPackedFloatList();
arrayVal[0] = 1.0;
msgPackedTypes.setPackedFloatList(arrayVal);
msgAllTypes.setRepeatedFloatList([1.0]);
arrayVal = msgAllTypes.getRepeatedFloatList();
arrayVal[0] = 1.0;
msgAllTypes.setRepeatedFloatList(arrayVal);
msgPackedTypes.setPackedInt32List([1]);
arrayVal = msgPackedTypes.getPackedInt32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedInt32List(arrayVal);
msgAllTypes.setRepeatedInt32List([1]);
arrayVal = msgAllTypes.getRepeatedInt32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedInt32List(arrayVal);
msgPackedTypes.setPackedInt64List([1]);
arrayVal = msgPackedTypes.getPackedInt64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedInt64List(arrayVal);
msgAllTypes.setRepeatedInt64List([1]);
arrayVal = msgAllTypes.getRepeatedInt64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedInt64List(arrayVal);
// msgPackedTypes.setPackedEnumList([ForeignEnum.FOREIGN_BAR]);
// arrayVal = msgPackedTypes.getPackedEnumList();
// arrayVal[0] = ForeignEnum.FOREIGN_BAR;
// msgPackedTypes.setPackedEnumList(arrayVal);
// msgAllTypes.setRepeatedForeignEnumList([ForeignEnum.FOREIGN_BAR]);
// arrayVal = msgAllTypes.getRepeatedForeignEnumList();
// arrayVal[0] = ForeignEnum.FOREIGN_BAR;
// msgAllTypes.setRepeatedForeignEnumList(arrayVal);
msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
arrayVal = msgAllTypes.getRepeatedForeignMessageList();
arrayVal[0] = ForeignMessage.deserialize('');
msgAllTypes.setRepeatedForeignMessageList(arrayVal);
msgPackedTypes.setPackedSfixed32List([1]);
arrayVal = msgPackedTypes.getPackedSfixed32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSfixed32List(arrayVal);
msgAllTypes.setRepeatedSfixed32List([1]);
arrayVal = msgAllTypes.getRepeatedSfixed32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSfixed32List(arrayVal);
msgPackedTypes.setPackedSfixed64List([1]);
arrayVal = msgPackedTypes.getPackedSfixed64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSfixed64List(arrayVal);
msgAllTypes.setRepeatedSfixed64List([1]);
arrayVal = msgAllTypes.getRepeatedSfixed64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSfixed64List(arrayVal);
msgPackedTypes.setPackedSint32List([1]);
arrayVal = msgPackedTypes.getPackedSint32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSint32List(arrayVal);
msgAllTypes.setRepeatedSint32List([1]);
arrayVal = msgAllTypes.getRepeatedSint32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSint32List(arrayVal);
msgPackedTypes.setPackedSint64List([1]);
arrayVal = msgPackedTypes.getPackedSint64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedSint64List(arrayVal);
msgAllTypes.setRepeatedSint64List([1]);
arrayVal = msgAllTypes.getRepeatedSint64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedSint64List(arrayVal);
msgPackedTypes.setPackedUint32List([1]);
arrayVal = msgPackedTypes.getPackedUint32List();
arrayVal[0] = 1;
msgPackedTypes.setPackedUint32List(arrayVal);
msgAllTypes.setRepeatedUint32List([1]);
arrayVal = msgAllTypes.getRepeatedUint32List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedUint32List(arrayVal);
msgPackedTypes.setPackedUint64List([1]);
arrayVal = msgPackedTypes.getPackedUint64List();
arrayVal[0] = 1;
msgPackedTypes.setPackedUint64List(arrayVal);
msgAllTypes.setRepeatedUint64List([1]);
arrayVal = msgAllTypes.getRepeatedUint64List();
arrayVal[0] = 1;
msgAllTypes.setRepeatedUint64List(arrayVal);
let s = '';
s += msgAllTypes.getOptionalBool() || false;
s += msgAllTypes.getOptionalBytes_asB64() || '';
// s += msgAllTypes.getOptionalBytes_asU8() || new Uint8Array([]);
s += msgAllTypes.getOptionalDouble() || 0.0;
s += msgAllTypes.getOptionalFixed32() || 0;
s += msgAllTypes.getOptionalFixed64() || 0;
s += msgAllTypes.getOptionalFloat() || 0.0;
s += msgAllTypes.getOptionalInt32() || 0;
s += msgAllTypes.getOptionalInt64() || 0;
// s += msgAllTypes.getOptionalForeignEnum() || ForeignEnum.FOREIGN_BAR;
s += msgAllTypes.getOptionalForeignMessage();
s += msgAllTypes.getOptionalSfixed32() || 0;
s += msgAllTypes.getOptionalSfixed64() || 0;
s += msgAllTypes.getOptionalSint32() || 0;
s += msgAllTypes.getOptionalSint64() || 0;
s += msgAllTypes.getOptionalString() || '';
s += msgAllTypes.getOptionalUint32() || 0;
s += msgAllTypes.getOptionalUint64() || 0;
s += msgAllTypes.getRepeatedBoolList();
s += msgAllTypes.getRepeatedBoolList()[0];
s += msgAllTypes.getRepeatedBoolList().length;
s += msgAllTypes.getRepeatedBytesList_asB64();
s += msgAllTypes.getRepeatedBytesList_asB64()[0];
s += msgAllTypes.getRepeatedBytesList_asB64().length;
s += msgAllTypes.getRepeatedBytesList_asU8();
s += msgAllTypes.getRepeatedDoubleList();
s += msgAllTypes.getRepeatedDoubleList()[0];
s += msgAllTypes.getRepeatedDoubleList().length;
s += msgAllTypes.getRepeatedFixed32List();
s += msgAllTypes.getRepeatedFixed32List()[0];
s += msgAllTypes.getRepeatedFixed32List().length;
s += msgAllTypes.getRepeatedFixed64List();
s += msgAllTypes.getRepeatedFixed64List()[0];
s += msgAllTypes.getRepeatedFixed64List().length;
s += msgAllTypes.getRepeatedFloatList();
s += msgAllTypes.getRepeatedFloatList()[0];
s += msgAllTypes.getRepeatedFloatList().length;
s += msgAllTypes.getRepeatedInt32List();
s += msgAllTypes.getRepeatedInt32List()[0];
s += msgAllTypes.getRepeatedInt32List().length;
s += msgAllTypes.getRepeatedInt64List();
s += msgAllTypes.getRepeatedInt64List()[0];
s += msgAllTypes.getRepeatedInt64List().length;
// s += msgAllTypes.getRepeatedForeignEnumList();
// s += msgAllTypes.getRepeatedForeignEnumList()[0];
// s += msgAllTypes.getRepeatedForeignEnumList().length;
s += msgAllTypes.getRepeatedForeignMessageList();
s += msgAllTypes.getRepeatedForeignMessageList()[0];
s += msgAllTypes.getRepeatedForeignMessageList().length;
s += msgAllTypes.getRepeatedSfixed32List();
s += msgAllTypes.getRepeatedSfixed32List()[0];
s += msgAllTypes.getRepeatedSfixed32List().length;
s += msgAllTypes.getRepeatedSfixed64List();
s += msgAllTypes.getRepeatedSfixed64List()[0];
s += msgAllTypes.getRepeatedSfixed64List().length;
s += msgAllTypes.getRepeatedSint32List();
s += msgAllTypes.getRepeatedSint32List()[0];
s += msgAllTypes.getRepeatedSint32List().length;
s += msgAllTypes.getRepeatedSint64List();
s += msgAllTypes.getRepeatedSint64List()[0];
s += msgAllTypes.getRepeatedSint64List().length;
s += msgAllTypes.getRepeatedStringList();
s += msgAllTypes.getRepeatedStringList()[0];
s += msgAllTypes.getRepeatedStringList().length;
s += msgAllTypes.getRepeatedUint32List();
s += msgAllTypes.getRepeatedUint32List()[0];
s += msgAllTypes.getRepeatedUint32List().length;
s += msgAllTypes.getRepeatedUint64List();
s += msgAllTypes.getRepeatedUint64List()[0];
s += msgAllTypes.getRepeatedUint64List().length;
s += msgAllTypes.serialize();
s += msgPackedTypes.serialize();
return s;
}
goog.global['__hiddenTest'] += accessAllTypes();

View File

@ -1,53 +0,0 @@
/**
* @fileoverview The code size benchmark of apps JSPB for proto2 popular types.
*/
goog.module('protobuf.benchmark.code_size.apps_jspb.PopularTypesProto2');
// const ForeignEnum = goog.require('proto.proto2_unittest.ForeignEnum');
const ForeignMessage = goog.require('proto.proto2_unittest.ForeignMessage');
const TestAllTypes = goog.require('proto.proto2_unittest.TestAllTypes');
const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
ensureCommonBaseLine();
/**
* @return {string}
*/
function accessPopularTypes() {
const msgAllTypes = TestAllTypes.deserialize('');
msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
[ForeignMessage.deserialize('')].forEach(
(e) => msgAllTypes.addRepeatedForeignMessage(e));
msgAllTypes.setOptionalString('');
msgAllTypes.setOptionalInt32(1);
msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
msgAllTypes.setOptionalBool(true);
// msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
msgAllTypes.setOptionalInt64(1);
msgAllTypes.setOptionalDouble(1.0);
msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
let arrayVal = msgAllTypes.getRepeatedForeignMessageList();
arrayVal[0] = ForeignMessage.deserialize('');
msgAllTypes.setRepeatedForeignMessageList(arrayVal);
msgAllTypes.setOptionalUint64(1);
let s = '';
s += msgAllTypes.getOptionalString();
s += msgAllTypes.getOptionalInt32();
s += msgAllTypes.getOptionalForeignMessage();
s += msgAllTypes.getOptionalBool();
// s += msgAllTypes.getOptionalForeignEnum();
s += msgAllTypes.getOptionalInt64();
s += msgAllTypes.getOptionalDouble();
s += msgAllTypes.getRepeatedForeignMessageList();
s += msgAllTypes.getRepeatedForeignMessageList()[0];
s += msgAllTypes.getRepeatedForeignMessageList().length;
s += msgAllTypes.getOptionalUint64();
s += msgAllTypes.serialize();
return s;
}
goog.global['__hiddenTest'] += accessPopularTypes();

View File

@ -1,53 +0,0 @@
/**
* @fileoverview The code size benchmark of apps JSPB for proto3 popular types.
*/
goog.module('protobuf.benchmark.code_size.apps_jspb.PopularTypesProto3');
// const ForeignEnum = goog.require('proto.proto3_unittest.ForeignEnum');
const ForeignMessage = goog.require('proto.proto3_unittest.ForeignMessage');
const TestAllTypes = goog.require('proto.proto3_unittest.TestAllTypes');
const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
ensureCommonBaseLine();
/**
* @return {string}
*/
function accessPopularTypes() {
const msgAllTypes = TestAllTypes.deserialize('');
msgAllTypes.addRepeatedForeignMessage(ForeignMessage.deserialize(''), 1);
[ForeignMessage.deserialize('')].forEach(
(e) => msgAllTypes.addRepeatedForeignMessage(e));
msgAllTypes.setOptionalString('');
msgAllTypes.setOptionalInt32(1);
msgAllTypes.setOptionalForeignMessage(ForeignMessage.deserialize(''));
msgAllTypes.setOptionalBool(true);
// msgAllTypes.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
msgAllTypes.setOptionalInt64(1);
msgAllTypes.setOptionalDouble(1.0);
msgAllTypes.setRepeatedForeignMessageList([ForeignMessage.deserialize('')]);
let arrayVal = msgAllTypes.getRepeatedForeignMessageList();
arrayVal[0] = ForeignMessage.deserialize('');
msgAllTypes.setRepeatedForeignMessageList(arrayVal);
msgAllTypes.setOptionalUint64(1);
let s = '';
s += msgAllTypes.getOptionalString();
s += msgAllTypes.getOptionalInt32();
s += msgAllTypes.getOptionalForeignMessage();
s += msgAllTypes.getOptionalBool();
// s += msgAllTypes.getOptionalForeignEnum();
s += msgAllTypes.getOptionalInt64();
s += msgAllTypes.getOptionalDouble();
s += msgAllTypes.getRepeatedForeignMessageList();
s += msgAllTypes.getRepeatedForeignMessageList()[0];
s += msgAllTypes.getRepeatedForeignMessageList().length;
s += msgAllTypes.getOptionalUint64();
s += msgAllTypes.serialize();
return s;
}
goog.global['__hiddenTest'] += accessPopularTypes();

View File

@ -1,57 +0,0 @@
/**
* @fileoverview Ensures types are live that would be live in a typical g3
* JS program.
*
* Making certain constructs live ensures that we compare against the same
* baseline for all code size benchmarks. This increases the size
* of our benchmarks, but note that this size in a regular app would be
* attributes to other places.
*/
goog.module('protobuf.benchmark.codeSize.codeSizeBase');
/**
* Ensures that the array iterator polyfill is live.
* @return {string}
*/
function useArrayIterator() {
let a = [];
let s = '';
for (let value of a) {
s += value;
}
return s;
}
/**
* Ensures that the symbol iterator polyfill is live.
* @return {string}
*/
function useSymbolIterator() {
/**
* @implements {Iterable}
*/
class Foo {
/** @return {!Iterator} */
[Symbol.iterator]() {}
}
let foo = new Foo();
let s = '';
for (let value of foo) {
s += value;
}
return s;
}
/**
* Ensures certain base libs are live so we can have an apples to apples
* comparison for code size of different implementations
*/
function ensureCommonBaseLine() {
goog.global['__hiddenTest'] += useArrayIterator();
goog.global['__hiddenTest'] += useSymbolIterator();
}
exports = {ensureCommonBaseLine};

View File

@ -1,227 +0,0 @@
/**
* @fileoverview The code size benchmark of binary kernel for accessing all
* types setter and getter.
*/
goog.module('protobuf.benchmark.KernelCodeSizeBenchmarkAllTypes');
const ByteString = goog.require('protobuf.ByteString');
const Int64 = goog.require('protobuf.Int64');
const Kernel = goog.require('protobuf.runtime.Kernel');
const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
ensureCommonBaseLine();
/**
* @return {string}
*/
function accessAllTypes() {
const message = new TestMessage(Kernel.createEmpty());
message.addPackedBoolElement(1, true);
message.addPackedBoolIterable(1, [true]);
message.addUnpackedBoolElement(1, true);
message.addUnpackedBoolIterable(1, [true]);
message.addRepeatedBytesElement(1, ByteString.EMPTY);
message.addRepeatedBytesIterable(1, [ByteString.EMPTY]);
message.addPackedDoubleElement(1, 1.0);
message.addPackedDoubleIterable(1, [1.0]);
message.addUnpackedDoubleElement(1, 1.0);
message.addUnpackedDoubleIterable(1, [1.0]);
message.addPackedFixed32Element(1, 1);
message.addPackedFixed32Iterable(1, [1]);
message.addUnpackedFixed32Element(1, 1);
message.addUnpackedFixed32Iterable(1, [1]);
message.addPackedFixed64Element(1, Int64.fromBits(0, 1));
message.addPackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.addUnpackedFixed64Element(1, Int64.fromBits(0, 1));
message.addUnpackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.addPackedFloatElement(1, 1.0);
message.addPackedFloatIterable(1, [1.0]);
message.addUnpackedFloatElement(1, 1.0);
message.addUnpackedFloatIterable(1, [1.0]);
message.addPackedInt32Element(1, 1);
message.addPackedInt32Iterable(1, [1]);
message.addUnpackedInt32Element(1, 1);
message.addUnpackedInt32Iterable(1, [1]);
message.addPackedInt64Element(1, Int64.fromBits(0, 1));
message.addPackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
message.addUnpackedInt64Element(1, Int64.fromBits(0, 1));
message.addUnpackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
message.addRepeatedMessageElement(1, message, TestMessage.instanceCreator);
message.addRepeatedMessageIterable(1, [message], TestMessage.instanceCreator);
message.addPackedSfixed32Element(1, 1);
message.addPackedSfixed32Iterable(1, [1]);
message.addUnpackedSfixed32Element(1, 1);
message.addUnpackedSfixed32Iterable(1, [1]);
message.addPackedSfixed64Element(1, Int64.fromBits(0, 1));
message.addPackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.addUnpackedSfixed64Element(1, Int64.fromBits(0, 1));
message.addUnpackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.addPackedSint32Element(1, 1);
message.addPackedSint32Iterable(1, [1]);
message.addUnpackedSint32Element(1, 1);
message.addUnpackedSint32Iterable(1, [1]);
message.addPackedSint64Element(1, Int64.fromBits(0, 1));
message.addPackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
message.addUnpackedSint64Element(1, Int64.fromBits(0, 1));
message.addUnpackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
message.addRepeatedStringElement(1, '');
message.addRepeatedStringIterable(1, ['']);
message.addPackedUint32Element(1, 1);
message.addPackedUint32Iterable(1, [1]);
message.addUnpackedUint32Element(1, 1);
message.addUnpackedUint32Iterable(1, [1]);
message.addPackedUint64Element(1, Int64.fromBits(0, 1));
message.addPackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
message.addUnpackedUint64Element(1, Int64.fromBits(0, 1));
message.addUnpackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
message.setBool(1, true);
message.setBytes(1, ByteString.EMPTY);
message.setDouble(1, 1.0);
message.setFixed32(1, 1);
message.setFixed64(1, Int64.fromBits(0, 1));
message.setFloat(1, 1.0);
message.setInt32(1, 1);
message.setInt64(1, Int64.fromBits(0, 1));
message.setMessage(1, message);
message.setSfixed32(1, 1);
message.setSfixed64(1, Int64.fromBits(0, 1));
message.setSint32(1, 1);
message.setSint64(1, Int64.fromBits(0, 1));
message.setString(1, 'abc');
message.setUint32(1, 1);
message.setUint64(1, Int64.fromBits(0, 1));
message.setPackedBoolElement(1, 0, true);
message.setPackedBoolIterable(1, [true]);
message.setUnpackedBoolElement(1, 0, true);
message.setUnpackedBoolIterable(1, [true]);
message.setRepeatedBytesElement(1, 0, ByteString.EMPTY);
message.setRepeatedBytesIterable(1, [ByteString.EMPTY]);
message.setPackedDoubleElement(1, 0, 1.0);
message.setPackedDoubleIterable(1, [1.0]);
message.setUnpackedDoubleElement(1, 0, 1.0);
message.setUnpackedDoubleIterable(1, [1.0]);
message.setPackedFixed32Element(1, 0, 1);
message.setPackedFixed32Iterable(1, [1]);
message.setUnpackedFixed32Element(1, 0, 1);
message.setUnpackedFixed32Iterable(1, [1]);
message.setPackedFixed64Element(1, 0, Int64.fromBits(0, 1));
message.setPackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.setUnpackedFixed64Element(1, 0, Int64.fromBits(0, 1));
message.setUnpackedFixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.setPackedFloatElement(1, 0, 1.0);
message.setPackedFloatIterable(1, [1.0]);
message.setUnpackedFloatElement(1, 0, 1.0);
message.setUnpackedFloatIterable(1, [1.0]);
message.setPackedInt32Element(1, 0, 1);
message.setPackedInt32Iterable(1, [1]);
message.setUnpackedInt32Element(1, 0, 1);
message.setUnpackedInt32Iterable(1, [1]);
message.setPackedInt64Element(1, 0, Int64.fromBits(0, 1));
message.setPackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
message.setUnpackedInt64Element(1, 0, Int64.fromBits(0, 1));
message.setUnpackedInt64Iterable(1, [Int64.fromBits(0, 1)]);
message.setRepeatedMessageElement(1, message, TestMessage.instanceCreator, 0);
message.setRepeatedMessageIterable(1, [message]);
message.setPackedSfixed32Element(1, 0, 1);
message.setPackedSfixed32Iterable(1, [1]);
message.setUnpackedSfixed32Element(1, 0, 1);
message.setUnpackedSfixed32Iterable(1, [1]);
message.setPackedSfixed64Element(1, 0, Int64.fromBits(0, 1));
message.setPackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.setUnpackedSfixed64Element(1, 0, Int64.fromBits(0, 1));
message.setUnpackedSfixed64Iterable(1, [Int64.fromBits(0, 1)]);
message.setRepeatedStringElement(1, 0, '');
message.setRepeatedStringIterable(1, ['']);
message.setPackedSint32Element(1, 0, 1);
message.setPackedSint32Iterable(1, [1]);
message.setUnpackedSint32Element(1, 0, 1);
message.setUnpackedSint32Iterable(1, [1]);
message.setPackedSint64Element(1, 0, Int64.fromBits(0, 1));
message.setPackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
message.setUnpackedSint64Element(1, 0, Int64.fromBits(0, 1));
message.setUnpackedSint64Iterable(1, [Int64.fromBits(0, 1)]);
message.setPackedUint32Element(1, 0, 1);
message.setPackedUint32Iterable(1, [1]);
message.setUnpackedUint32Element(1, 0, 1);
message.setUnpackedUint32Iterable(1, [1]);
message.setPackedUint64Element(1, 0, Int64.fromBits(0, 1));
message.setPackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
message.setUnpackedUint64Element(1, 0, Int64.fromBits(0, 1));
message.setUnpackedUint64Iterable(1, [Int64.fromBits(0, 1)]);
let s = '';
s += message.getBoolWithDefault(1);
s += message.getBytesWithDefault(1);
s += message.getDoubleWithDefault(1);
s += message.getFixed32WithDefault(1);
s += message.getFixed64WithDefault(1);
s += message.getFloatWithDefault(1);
s += message.getInt32WithDefault(1);
s += message.getInt64WithDefault(1);
s += message.getMessage(1, TestMessage.instanceCreator);
s += message.getSfixed32WithDefault(1);
s += message.getSfixed64WithDefault(1);
s += message.getSint32WithDefault(1);
s += message.getSint64WithDefault(1);
s += message.getStringWithDefault(1);
s += message.getUint32WithDefault(1);
s += message.getUint64WithDefault(1);
s += message.getRepeatedBoolElement(1, 0);
s += message.getRepeatedBoolIterable(1);
s += message.getRepeatedBoolSize(1);
s += message.getRepeatedBytesElement(1, 0);
s += message.getRepeatedBytesIterable(1);
s += message.getRepeatedBytesSize(1);
s += message.getRepeatedDoubleElement(1, 0);
s += message.getRepeatedDoubleIterable(1);
s += message.getRepeatedDoubleSize(1);
s += message.getRepeatedFixed32Element(1, 0);
s += message.getRepeatedFixed32Iterable(1);
s += message.getRepeatedFixed32Size(1);
s += message.getRepeatedFixed64Element(1, 0);
s += message.getRepeatedFixed64Iterable(1);
s += message.getRepeatedFixed64Size(1);
s += message.getRepeatedFloatElement(1, 0);
s += message.getRepeatedFloatIterable(1);
s += message.getRepeatedFloatSize(1);
s += message.getRepeatedInt32Element(1, 0);
s += message.getRepeatedInt32Iterable(1);
s += message.getRepeatedInt32Size(1);
s += message.getRepeatedInt64Element(1, 0);
s += message.getRepeatedInt64Iterable(1);
s += message.getRepeatedInt64Size(1);
s += message.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0);
s += message.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
s += message.getRepeatedMessageSize(1, TestMessage.instanceCreator);
s += message.getRepeatedSfixed32Element(1, 0);
s += message.getRepeatedSfixed32Iterable(1);
s += message.getRepeatedSfixed32Size(1);
s += message.getRepeatedSfixed64Element(1, 0);
s += message.getRepeatedSfixed64Iterable(1);
s += message.getRepeatedSfixed64Size(1);
s += message.getRepeatedSint32Element(1, 0);
s += message.getRepeatedSint32Iterable(1);
s += message.getRepeatedSint32Size(1);
s += message.getRepeatedSint64Element(1, 0);
s += message.getRepeatedSint64Iterable(1);
s += message.getRepeatedSint64Size(1);
s += message.getRepeatedStringElement(1, 0);
s += message.getRepeatedStringIterable(1);
s += message.getRepeatedStringSize(1);
s += message.getRepeatedUint32Element(1, 0);
s += message.getRepeatedUint32Iterable(1);
s += message.getRepeatedUint32Size(1);
s += message.getRepeatedUint64Element(1, 0);
s += message.getRepeatedUint64Iterable(1);
s += message.getRepeatedUint64Size(1);
s += message.serialize();
return s;
}
goog.global['__hiddenTest'] += accessAllTypes();

View File

@ -1,68 +0,0 @@
/**
* @fileoverview The code size benchmark of binary kernel for accessing all
* popular types setter and getter.
*
* The types are those whose usage are more than 1%:
*
* ('STRING__LABEL_OPTIONAL', '29.7214%')
* ('INT32__LABEL_OPTIONAL', '17.7277%')
* ('MESSAGE__LABEL_OPTIONAL', '15.6462%')
* ('BOOL__LABEL_OPTIONAL', '13.0038%')
* ('ENUM__LABEL_OPTIONAL', '11.4466%')
* ('INT64__LABEL_OPTIONAL', '3.2198%')
* ('DOUBLE__LABEL_OPTIONAL', '1.357%')
* ('MESSAGE__LABEL_REPEATED', '1.2775%')
* ('FIXED32__LABEL_REQUIRED', '1.2%')
* ('UINT64__LABEL_OPTIONAL', '1.1771%')
* ('STRING__LABEL_REQUIRED', '1.0785%')
*
*/
goog.module('protobuf.benchmark.KernelCodeSizeBenchmarkPopularTypes');
const Int64 = goog.require('protobuf.Int64');
const Kernel = goog.require('protobuf.runtime.Kernel');
const TestMessage = goog.require('protobuf.testing.binary.TestMessage');
const {ensureCommonBaseLine} = goog.require('protobuf.benchmark.codeSize.codeSizeBase');
ensureCommonBaseLine();
/**
* @return {string}
*/
function accessAllTypes() {
const message = new TestMessage(Kernel.createEmpty());
message.addRepeatedMessageElement(1, message, TestMessage.instanceCreator);
message.addRepeatedMessageIterable(1, [message], TestMessage.instanceCreator);
message.setString(1, 'abc');
message.setInt32(1, 1);
message.setMessage(1, message);
message.setBool(1, true);
message.setInt64(1, Int64.fromBits(0, 1));
message.setDouble(1, 1.0);
message.setRepeatedMessageElement(1, message, TestMessage.instanceCreator, 0);
message.setRepeatedMessageIterable(1, [message]);
message.setUint64(1, Int64.fromBits(0, 1));
let s = '';
s += message.getStringWithDefault(1);
s += message.getInt32WithDefault(1);
s += message.getMessage(1, TestMessage.instanceCreator);
s += message.getMessageOrNull(1, TestMessage.instanceCreator);
s += message.getBoolWithDefault(1);
s += message.getInt64WithDefault(1);
s += message.getDoubleWithDefault(1);
s += message.getRepeatedMessageElement(1, TestMessage.instanceCreator, 0);
s += message.getRepeatedMessageIterable(1, TestMessage.instanceCreator);
s += message.getRepeatedMessageSize(1, TestMessage.instanceCreator);
s += message.getUint64WithDefault(1);
s += message.serialize();
return s;
}
goog.global['__hiddenTest'] += accessAllTypes();

View File

@ -1,183 +0,0 @@
/**
* @fileoverview Provides ByteString as a basic data type for protos.
*/
goog.module('protobuf.ByteString');
const base64 = goog.require('goog.crypt.base64');
const {arrayBufferSlice, cloneArrayBufferView, hashUint8Array, uint8ArrayEqual} = goog.require('protobuf.binary.typedArrays');
/**
* Immutable sequence of bytes.
*
* Bytes can be obtained as an ArrayBuffer or a base64 encoded string.
* @final
*/
class ByteString {
/**
* @param {?Uint8Array} bytes
* @param {?string} base64
* @private
*/
constructor(bytes, base64) {
/** @private {?Uint8Array}*/
this.bytes_ = bytes;
/** @private {?string} */
this.base64_ = base64;
/** @private {number} */
this.hashCode_ = 0;
}
/**
* Constructs a ByteString instance from a base64 string.
* @param {string} value
* @return {!ByteString}
*/
static fromBase64String(value) {
if (value == null) {
throw new Error('value must not be null');
}
return new ByteString(/* bytes */ null, value);
}
/**
* Constructs a ByteString from an array buffer.
* @param {!ArrayBuffer} bytes
* @param {number=} start
* @param {number=} end
* @return {!ByteString}
*/
static fromArrayBuffer(bytes, start = 0, end = undefined) {
return new ByteString(
new Uint8Array(arrayBufferSlice(bytes, start, end)), /* base64 */ null);
}
/**
* Constructs a ByteString from any ArrayBufferView (e.g. DataView,
* TypedArray, Uint8Array, etc.).
* @param {!ArrayBufferView} bytes
* @return {!ByteString}
*/
static fromArrayBufferView(bytes) {
return new ByteString(cloneArrayBufferView(bytes), /* base64 */ null);
}
/**
* Constructs a ByteString from an Uint8Array. DON'T MODIFY the underlying
* ArrayBuffer, since the ByteString directly uses it without making a copy.
*
* This method exists so that internal APIs can construct a ByteString without
* paying the penalty of copying an ArrayBuffer when that ArrayBuffer is not
* supposed to change. It is exposed to a limited number of internal classes
* through bytestring_internal.js.
*
* @param {!Uint8Array} bytes
* @return {!ByteString}
* @package
*/
static fromUint8ArrayUnsafe(bytes) {
return new ByteString(bytes, /* base64 */ null);
}
/**
* Returns this ByteString as an ArrayBuffer.
* @return {!ArrayBuffer}
*/
toArrayBuffer() {
const bytes = this.ensureBytes_();
return arrayBufferSlice(
bytes.buffer, bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
}
/**
* Returns this ByteString as an Uint8Array. DON'T MODIFY the returned array,
* since the ByteString holds the reference to the same array.
*
* This method exists so that internal APIs can get contents of a ByteString
* without paying the penalty of copying an ArrayBuffer. It is exposed to a
* limited number of internal classes through bytestring_internal.js.
* @return {!Uint8Array}
* @package
*/
toUint8ArrayUnsafe() {
return this.ensureBytes_();
}
/**
* Returns this ByteString as a base64 encoded string.
* @return {string}
*/
toBase64String() {
return this.ensureBase64String_();
}
/**
* Returns true for Bytestrings that contain identical values.
* @param {*} other
* @return {boolean}
*/
equals(other) {
if (this === other) {
return true;
}
if (!(other instanceof ByteString)) {
return false;
}
const otherByteString = /** @type {!ByteString} */ (other);
return uint8ArrayEqual(this.ensureBytes_(), otherByteString.ensureBytes_());
}
/**
* Returns a number (int32) that is suitable for using in hashed structures.
* @return {number}
*/
hashCode() {
if (this.hashCode_ == 0) {
this.hashCode_ = hashUint8Array(this.ensureBytes_());
}
return this.hashCode_;
}
/**
* Returns true if the bytestring is empty.
* @return {boolean}
*/
isEmpty() {
if (this.bytes_ != null && this.bytes_.byteLength == 0) {
return true;
}
if (this.base64_ != null && this.base64_.length == 0) {
return true;
}
return false;
}
/**
* @return {!Uint8Array}
* @private
*/
ensureBytes_() {
if (this.bytes_) {
return this.bytes_;
}
return this.bytes_ = base64.decodeStringToUint8Array(
/** @type {string} */ (this.base64_));
}
/**
* @return {string}
* @private
*/
ensureBase64String_() {
if (this.base64_ == null) {
this.base64_ = base64.encodeByteArray(this.bytes_);
}
return this.base64_;
}
}
/** @const {!ByteString} */
ByteString.EMPTY = new ByteString(new Uint8Array(0), null);
exports = ByteString;

View File

@ -1,33 +0,0 @@
/**
* @fileoverview Exposes internal only functions for ByteString. The
* corresponding BUILD rule restricts access to this file to only the binary
* kernel and APIs directly using the binary kernel.
*/
goog.module('protobuf.byteStringInternal');
const ByteString = goog.require('protobuf.ByteString');
/**
* Constructs a ByteString from an Uint8Array. DON'T MODIFY the underlying
* ArrayBuffer, since the ByteString directly uses it without making a copy.
* @param {!Uint8Array} bytes
* @return {!ByteString}
*/
function byteStringFromUint8ArrayUnsafe(bytes) {
return ByteString.fromUint8ArrayUnsafe(bytes);
}
/**
* Returns this ByteString as an Uint8Array. DON'T MODIFY the returned array,
* since the ByteString holds the reference to the same array.
* @param {!ByteString} bytes
* @return {!Uint8Array}
*/
function byteStringToUint8ArrayUnsafe(bytes) {
return bytes.toUint8ArrayUnsafe();
}
exports = {
byteStringFromUint8ArrayUnsafe,
byteStringToUint8ArrayUnsafe,
};

View File

@ -1,277 +0,0 @@
goog.module('proto.im.integration.ByteStringFieldsTest');
goog.setTestOnly();
const ByteString = goog.require('protobuf.ByteString');
const {arrayBufferSlice} = goog.require('protobuf.binary.typedArrays');
const /** !ArrayBuffer */ TEST_BYTES = new Uint8Array([1, 2, 3, 4]).buffer;
const /** !ByteString */ TEST_STRING = ByteString.fromArrayBuffer(TEST_BYTES);
const /** !ArrayBuffer */ PREFIXED_TEST_BYTES =
new Uint8Array([0, 1, 2, 3, 4]).buffer;
const /** string */ HALLO_IN_BASE64 = 'aGFsbG8=';
const /** string */ HALLO_IN_BASE64_WITH_SPACES = 'a G F s b G 8=';
const /** !ArrayBufferView */ BYTES_WITH_HALLO = new Uint8Array([
'h'.charCodeAt(0),
'a'.charCodeAt(0),
'l'.charCodeAt(0),
'l'.charCodeAt(0),
'o'.charCodeAt(0),
]);
describe('ByteString does', () => {
it('create bytestring from buffer', () => {
const byteString =
ByteString.fromArrayBuffer(arrayBufferSlice(TEST_BYTES, 0));
expect(byteString.toArrayBuffer()).toEqual(TEST_BYTES);
expect(byteString.toUint8ArrayUnsafe()).toEqual(new Uint8Array(TEST_BYTES));
});
it('create bytestring from ArrayBufferView', () => {
const byteString =
ByteString.fromArrayBufferView(new Uint8Array(TEST_BYTES));
expect(byteString.toArrayBuffer()).toEqual(TEST_BYTES);
expect(byteString.toUint8ArrayUnsafe()).toEqual(new Uint8Array(TEST_BYTES));
});
it('create bytestring from subarray', () => {
const byteString = ByteString.fromArrayBufferView(
new Uint8Array(TEST_BYTES, /* offset */ 1, /* length */ 2));
const expected = new Uint8Array([2, 3]);
expect(new Uint8Array(byteString.toArrayBuffer())).toEqual(expected);
expect(byteString.toUint8ArrayUnsafe()).toEqual(expected);
});
it('create bytestring from Uint8Array (unsafe)', () => {
const array = new Uint8Array(TEST_BYTES);
const byteString = ByteString.fromUint8ArrayUnsafe(array);
expect(byteString.toArrayBuffer()).toEqual(array.buffer);
expect(byteString.toUint8ArrayUnsafe()).toBe(array);
});
it('create bytestring from base64 string', () => {
const byteString = ByteString.fromBase64String(HALLO_IN_BASE64);
expect(byteString.toBase64String()).toEqual(HALLO_IN_BASE64);
expect(byteString.toArrayBuffer()).toEqual(BYTES_WITH_HALLO.buffer);
expect(byteString.toUint8ArrayUnsafe()).toEqual(BYTES_WITH_HALLO);
});
it('preserve immutability if underlying buffer changes: from buffer', () => {
const buffer = new ArrayBuffer(4);
const array = new Uint8Array(buffer);
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
const byteString = ByteString.fromArrayBuffer(buffer);
const otherBuffer = byteString.toArrayBuffer();
expect(otherBuffer).not.toBe(buffer);
expect(new Uint8Array(otherBuffer)).toEqual(array);
// modify the original buffer
array[0] = 5;
// Are we still returning the original bytes?
expect(new Uint8Array(byteString.toArrayBuffer())).toEqual(new Uint8Array([
1, 2, 3, 4
]));
});
it('preserve immutability if underlying buffer changes: from ArrayBufferView',
() => {
const buffer = new ArrayBuffer(4);
const array = new Uint8Array(buffer);
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
const byteString = ByteString.fromArrayBufferView(array);
const otherBuffer = byteString.toArrayBuffer();
expect(otherBuffer).not.toBe(buffer);
expect(new Uint8Array(otherBuffer)).toEqual(array);
// modify the original buffer
array[0] = 5;
// Are we still returning the original bytes?
expect(new Uint8Array(byteString.toArrayBuffer()))
.toEqual(new Uint8Array([1, 2, 3, 4]));
});
it('mutate if underlying buffer changes: from Uint8Array (unsafe)', () => {
const buffer = new ArrayBuffer(4);
const array = new Uint8Array(buffer);
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
const byteString = ByteString.fromUint8ArrayUnsafe(array);
const otherBuffer = byteString.toArrayBuffer();
expect(otherBuffer).not.toBe(buffer);
expect(new Uint8Array(otherBuffer)).toEqual(array);
// modify the original buffer
array[0] = 5;
// We are no longer returning the original bytes
expect(new Uint8Array(byteString.toArrayBuffer())).toEqual(new Uint8Array([
5, 2, 3, 4
]));
});
it('preserve immutability for returned buffers: toArrayBuffer', () => {
const byteString = ByteString.fromArrayBufferView(new Uint8Array(4));
const buffer1 = byteString.toArrayBuffer();
const buffer2 = byteString.toArrayBuffer();
expect(buffer1).toEqual(buffer2);
const array1 = new Uint8Array(buffer1);
array1[0] = 1;
expect(buffer1).not.toEqual(buffer2);
});
it('does not preserve immutability for returned buffers: toUint8ArrayUnsafe',
() => {
const byteString = ByteString.fromUint8ArrayUnsafe(new Uint8Array(4));
const array1 = byteString.toUint8ArrayUnsafe();
const array2 = byteString.toUint8ArrayUnsafe();
expect(array1).toEqual(array2);
array1[0] = 1;
expect(array1).toEqual(array2);
});
it('throws when created with null ArrayBufferView', () => {
expect(
() => ByteString.fromArrayBufferView(
/** @type {!ArrayBufferView} */ (/** @type{*} */ (null))))
.toThrow();
});
it('throws when created with null buffer', () => {
expect(
() => ByteString.fromBase64String(
/** @type {string} */ (/** @type{*} */ (null))))
.toThrow();
});
it('convert base64 to ArrayBuffer', () => {
const other = ByteString.fromBase64String(HALLO_IN_BASE64);
expect(BYTES_WITH_HALLO).toEqual(new Uint8Array(other.toArrayBuffer()));
});
it('convert base64 with spaces to ArrayBuffer', () => {
const other = ByteString.fromBase64String(HALLO_IN_BASE64_WITH_SPACES);
expect(new Uint8Array(other.toArrayBuffer())).toEqual(BYTES_WITH_HALLO);
});
it('convert bytes to base64', () => {
const other = ByteString.fromArrayBufferView(BYTES_WITH_HALLO);
expect(HALLO_IN_BASE64).toEqual(other.toBase64String());
});
it('equal empty bytetring', () => {
const empty = ByteString.fromArrayBuffer(new ArrayBuffer(0));
expect(ByteString.EMPTY.equals(empty)).toEqual(true);
});
it('equal empty bytestring constructed from ArrayBufferView', () => {
const empty = ByteString.fromArrayBufferView(new Uint8Array(0));
expect(ByteString.EMPTY.equals(empty)).toEqual(true);
});
it('equal empty bytestring constructed from Uint8Array (unsafe)', () => {
const empty = ByteString.fromUint8ArrayUnsafe(new Uint8Array(0));
expect(ByteString.EMPTY.equals(empty)).toEqual(true);
});
it('equal empty bytestring constructed from base64', () => {
const empty = ByteString.fromBase64String('');
expect(ByteString.EMPTY.equals(empty)).toEqual(true);
});
it('equal other instance', () => {
const other = ByteString.fromArrayBuffer(arrayBufferSlice(TEST_BYTES, 0));
expect(TEST_STRING.equals(other)).toEqual(true);
});
it('not equal different instance', () => {
const other =
ByteString.fromArrayBuffer(new Uint8Array([1, 2, 3, 4, 5]).buffer);
expect(TEST_STRING.equals(other)).toEqual(false);
});
it('equal other instance constructed from ArrayBufferView', () => {
const other =
ByteString.fromArrayBufferView(new Uint8Array(PREFIXED_TEST_BYTES, 1));
expect(TEST_STRING.equals(other)).toEqual(true);
});
it('not equal different instance constructed from ArrayBufferView', () => {
const other =
ByteString.fromArrayBufferView(new Uint8Array([1, 2, 3, 4, 5]));
expect(TEST_STRING.equals(other)).toEqual(false);
});
it('equal other instance constructed from Uint8Array (unsafe)', () => {
const other =
ByteString.fromUint8ArrayUnsafe(new Uint8Array(PREFIXED_TEST_BYTES, 1));
expect(TEST_STRING.equals(other)).toEqual(true);
});
it('not equal different instance constructed from Uint8Array (unsafe)',
() => {
const other =
ByteString.fromUint8ArrayUnsafe(new Uint8Array([1, 2, 3, 4, 5]));
expect(TEST_STRING.equals(other)).toEqual(false);
});
it('have same hashcode for empty bytes', () => {
const empty = ByteString.fromArrayBuffer(new ArrayBuffer(0));
expect(ByteString.EMPTY.hashCode()).toEqual(empty.hashCode());
});
it('have same hashcode for test bytes', () => {
const other = ByteString.fromArrayBuffer(arrayBufferSlice(TEST_BYTES, 0));
expect(TEST_STRING.hashCode()).toEqual(other.hashCode());
});
it('have same hashcode for test bytes', () => {
const other = ByteString.fromArrayBufferView(
new Uint8Array(arrayBufferSlice(TEST_BYTES, 0)));
expect(TEST_STRING.hashCode()).toEqual(other.hashCode());
});
it('have same hashcode for different instance constructed with base64',
() => {
const other = ByteString.fromBase64String(HALLO_IN_BASE64);
expect(ByteString.fromArrayBufferView(BYTES_WITH_HALLO).hashCode())
.toEqual(other.hashCode());
});
it('preserves the length of a Uint8Array', () => {
const original = new Uint8Array([105, 183, 51, 251, 253, 118, 247]);
const afterByteString = new Uint8Array(
ByteString.fromArrayBufferView(original).toArrayBuffer());
expect(afterByteString).toEqual(original);
});
it('preserves the length of a base64 value', () => {
const expected = new Uint8Array([105, 183, 51, 251, 253, 118, 247]);
const afterByteString = new Uint8Array(
ByteString.fromBase64String('abcz+/129w').toArrayBuffer());
expect(afterByteString).toEqual(expected);
});
it('preserves the length of a base64 value with padding', () => {
const expected = new Uint8Array([105, 183, 51, 251, 253, 118, 247]);
const afterByteString = new Uint8Array(
ByteString.fromBase64String('abcz+/129w==').toArrayBuffer());
expect(afterByteString).toEqual(expected);
});
});

View File

@ -1,403 +0,0 @@
/**
* @fileoverview Protobufs Int64 representation.
*/
goog.module('protobuf.Int64');
const Long = goog.require('goog.math.Long');
const {assert} = goog.require('goog.asserts');
/**
* A container for protobufs Int64/Uint64 data type.
* @final
*/
class Int64 {
/** @return {!Int64} */
static getZero() {
return ZERO;
}
/** @return {!Int64} */
static getMinValue() {
return MIN_VALUE;
}
/** @return {!Int64} */
static getMaxValue() {
return MAX_VALUE;
}
/**
* Constructs a Int64 given two 32 bit numbers
* @param {number} lowBits
* @param {number} highBits
* @return {!Int64}
*/
static fromBits(lowBits, highBits) {
return new Int64(lowBits, highBits);
}
/**
* Constructs an Int64 from a signed 32 bit number.
* @param {number} value
* @return {!Int64}
*/
static fromInt(value) {
// TODO: Use our own checking system here.
assert(value === (value | 0), 'value should be a 32-bit integer');
// Right shift 31 bits so all high bits are equal to the sign bit.
// Note: cannot use >> 32, because (1 >> 32) = 1 (!).
const signExtendedHighBits = value >> 31;
return new Int64(value, signExtendedHighBits);
}
/**
* Constructs an Int64 from a number (over 32 bits).
* @param {number} value
* @return {!Int64}
*/
static fromNumber(value) {
if (value > 0) {
return new Int64(value, value / TWO_PWR_32_DBL);
} else if (value < 0) {
return negate(-value, -value / TWO_PWR_32_DBL);
}
return ZERO;
}
/**
* Construct an Int64 from a signed decimal string.
* @param {string} value
* @return {!Int64}
*/
static fromDecimalString(value) {
// TODO: Use our own checking system here.
assert(value.length > 0);
// The basic Number conversion loses precision, but we can use it for
// a quick validation that the format is correct and it is an integer.
assert(Math.floor(Number(value)).toString().length == value.length);
return decimalStringToInt64(value);
}
/**
* Construct an Int64 from a signed hexadecimal string.
* @param {string} value
* @return {!Int64}
*/
static fromHexString(value) {
// TODO: Use our own checking system here.
assert(value.length > 0);
assert(value.slice(0, 2) == '0x' || value.slice(0, 3) == '-0x');
const minus = value[0] === '-';
// Strip the 0x or -0x prefix.
value = value.slice(minus ? 3 : 2);
const lowBits = parseInt(value.slice(-8), 16);
const highBits = parseInt(value.slice(-16, -8) || '', 16);
return (minus ? negate : Int64.fromBits)(lowBits, highBits);
}
// Note to the reader:
// goog.math.Long suffers from a code size issue. JsCompiler almost always
// considers toString methods to be alive in a program. So if you are
// constructing a Long instance the toString method is assumed to be live.
// Unfortunately Long's toString method makes a large chunk of code alive
// of the entire class adding 1.3kB (gzip) of extra code size.
// Callers that are sensitive to code size and are not using Long already
// should avoid calling this method.
/**
* Creates an Int64 instance from a Long value.
* @param {!Long} value
* @return {!Int64}
*/
static fromLong(value) {
return new Int64(value.getLowBits(), value.getHighBits());
}
/**
* @param {number} lowBits
* @param {number} highBits
* @private
*/
constructor(lowBits, highBits) {
/** @const @private {number} */
this.lowBits_ = lowBits | 0;
/** @const @private {number} */
this.highBits_ = highBits | 0;
}
/**
* Returns the int64 value as a JavaScript number. This will lose precision
* if the number is outside of the safe range for JavaScript of 53 bits
* precision.
* @return {number}
*/
asNumber() {
const result = this.highBits_ * TWO_PWR_32_DBL + this.getLowBitsUnsigned();
// TODO: Use our own checking system here.
assert(
Number.isSafeInteger(result), 'conversion to number loses precision.');
return result;
}
// Note to the reader:
// goog.math.Long suffers from a code size issue. JsCompiler almost always
// considers toString methods to be alive in a program. So if you are
// constructing a Long instance the toString method is assumed to be live.
// Unfortunately Long's toString method makes a large chunk of code alive
// of the entire class adding 1.3kB (gzip) of extra code size.
// Callers that are sensitive to code size and are not using Long already
// should avoid calling this method.
/** @return {!Long} */
asLong() {
return Long.fromBits(this.lowBits_, this.highBits_);
}
/** @return {number} Signed 32-bit integer value. */
getLowBits() {
return this.lowBits_;
}
/** @return {number} Signed 32-bit integer value. */
getHighBits() {
return this.highBits_;
}
/** @return {number} Unsigned 32-bit integer. */
getLowBitsUnsigned() {
return this.lowBits_ >>> 0;
}
/** @return {number} Unsigned 32-bit integer. */
getHighBitsUnsigned() {
return this.highBits_ >>> 0;
}
/** @return {string} */
toSignedDecimalString() {
return joinSignedDecimalString(this);
}
/** @return {string} */
toUnsignedDecimalString() {
return joinUnsignedDecimalString(this);
}
/**
* Returns an unsigned hexadecimal string representation of the Int64.
* @return {string}
*/
toHexString() {
let nibbles = new Array(16);
let lowBits = this.lowBits_;
let highBits = this.highBits_;
for (let highIndex = 7, lowIndex = 15; lowIndex > 7;
highIndex--, lowIndex--) {
nibbles[highIndex] = HEX_DIGITS[highBits & 0xF];
nibbles[lowIndex] = HEX_DIGITS[lowBits & 0xF];
highBits = highBits >>> 4;
lowBits = lowBits >>> 4;
}
// Always leave the least significant hex digit.
while (nibbles.length > 1 && nibbles[0] == '0') {
nibbles.shift();
}
return `0x${nibbles.join('')}`;
}
/**
* @param {*} other object to compare against.
* @return {boolean} Whether this Int64 equals the other.
*/
equals(other) {
if (this === other) {
return true;
}
if (!(other instanceof Int64)) {
return false;
}
// Compare low parts first as there is higher chance they are different.
const otherInt64 = /** @type{!Int64} */ (other);
return (this.lowBits_ === otherInt64.lowBits_) &&
(this.highBits_ === otherInt64.highBits_);
}
/**
* Returns a number (int32) that is suitable for using in hashed structures.
* @return {number}
*/
hashCode() {
return (31 * this.lowBits_ + 17 * this.highBits_) | 0;
}
}
/**
* Losslessly converts a 64-bit unsigned integer in 32:32 split representation
* into a decimal string.
* @param {!Int64} int64
* @return {string} The binary number represented as a string.
*/
const joinUnsignedDecimalString = (int64) => {
const lowBits = int64.getLowBitsUnsigned();
const highBits = int64.getHighBitsUnsigned();
// Skip the expensive conversion if the number is small enough to use the
// built-in conversions.
// Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with
// highBits <= 0x1FFFFF can be safely expressed with a double and retain
// integer precision.
// Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.
if (highBits <= 0x1FFFFF) {
return String(TWO_PWR_32_DBL * highBits + lowBits);
}
// What this code is doing is essentially converting the input number from
// base-2 to base-1e7, which allows us to represent the 64-bit range with
// only 3 (very large) digits. Those digits are then trivial to convert to
// a base-10 string.
// The magic numbers used here are -
// 2^24 = 16777216 = (1,6777216) in base-1e7.
// 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
// Split 32:32 representation into 16:24:24 representation so our
// intermediate digits don't overflow.
const low = lowBits & LOW_24_BITS;
const mid = ((lowBits >>> 24) | (highBits << 8)) & LOW_24_BITS;
const high = (highBits >> 16) & LOW_16_BITS;
// Assemble our three base-1e7 digits, ignoring carries. The maximum
// value in a digit at this step is representable as a 48-bit integer, which
// can be stored in a 64-bit floating point number.
let digitA = low + (mid * 6777216) + (high * 6710656);
let digitB = mid + (high * 8147497);
let digitC = (high * 2);
// Apply carries from A to B and from B to C.
const base = 10000000;
if (digitA >= base) {
digitB += Math.floor(digitA / base);
digitA %= base;
}
if (digitB >= base) {
digitC += Math.floor(digitB / base);
digitB %= base;
}
// If digitC is 0, then we should have returned in the trivial code path
// at the top for non-safe integers. Given this, we can assume both digitB
// and digitA need leading zeros.
// TODO: Use our own checking system here.
assert(digitC);
return digitC + decimalFrom1e7WithLeadingZeros(digitB) +
decimalFrom1e7WithLeadingZeros(digitA);
};
/**
* @param {number} digit1e7 Number < 1e7
* @return {string} Decimal representation of digit1e7 with leading zeros.
*/
const decimalFrom1e7WithLeadingZeros = (digit1e7) => {
const partial = String(digit1e7);
return '0000000'.slice(partial.length) + partial;
};
/**
* Losslessly converts a 64-bit signed integer in 32:32 split representation
* into a decimal string.
* @param {!Int64} int64
* @return {string} The binary number represented as a string.
*/
const joinSignedDecimalString = (int64) => {
// If we're treating the input as a signed value and the high bit is set, do
// a manual two's complement conversion before the decimal conversion.
const negative = (int64.getHighBits() & 0x80000000);
if (negative) {
int64 = negate(int64.getLowBits(), int64.getHighBits());
}
const result = joinUnsignedDecimalString(int64);
return negative ? '-' + result : result;
};
/**
* @param {string} dec
* @return {!Int64}
*/
const decimalStringToInt64 = (dec) => {
// Check for minus sign.
const minus = dec[0] === '-';
if (minus) {
dec = dec.slice(1);
}
// Work 6 decimal digits at a time, acting like we're converting base 1e6
// digits to binary. This is safe to do with floating point math because
// Number.isSafeInteger(ALL_32_BITS * 1e6) == true.
const base = 1e6;
let lowBits = 0;
let highBits = 0;
function add1e6digit(begin, end = undefined) {
// Note: Number('') is 0.
const digit1e6 = Number(dec.slice(begin, end));
highBits *= base;
lowBits = lowBits * base + digit1e6;
// Carry bits from lowBits to
if (lowBits >= TWO_PWR_32_DBL) {
highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);
lowBits = lowBits % TWO_PWR_32_DBL;
}
}
add1e6digit(-24, -18);
add1e6digit(-18, -12);
add1e6digit(-12, -6);
add1e6digit(-6);
return (minus ? negate : Int64.fromBits)(lowBits, highBits);
};
/**
* @param {number} lowBits
* @param {number} highBits
* @return {!Int64} Two's compliment negation of input.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
*/
const negate = (lowBits, highBits) => {
highBits = ~highBits;
if (lowBits) {
lowBits = ~lowBits + 1;
} else {
// If lowBits is 0, then bitwise-not is 0xFFFFFFFF,
// adding 1 to that, results in 0x100000000, which leaves
// the low bits 0x0 and simply adds one to the high bits.
highBits += 1;
}
return Int64.fromBits(lowBits, highBits);
};
/** @const {!Int64} */
const ZERO = new Int64(0, 0);
/** @const @private {number} */
const LOW_16_BITS = 0xFFFF;
/** @const @private {number} */
const LOW_24_BITS = 0xFFFFFF;
/** @const @private {number} */
const LOW_31_BITS = 0x7FFFFFFF;
/** @const @private {number} */
const ALL_32_BITS = 0xFFFFFFFF;
/** @const {!Int64} */
const MAX_VALUE = Int64.fromBits(ALL_32_BITS, LOW_31_BITS);
/** @const {!Int64} */
const MIN_VALUE = Int64.fromBits(0, 0x80000000);
/** @const {number} */
const TWO_PWR_32_DBL = 0x100000000;
/** @const {string} */
const HEX_DIGITS = '0123456789abcdef';
exports = Int64;

View File

@ -1,213 +0,0 @@
/**
* @fileoverview Tests for Int64.
*/
goog.module('protobuf.Int64Test');
goog.setTestOnly();
const Int64 = goog.require('protobuf.Int64');
const Long = goog.require('goog.math.Long');
describe('Int64', () => {
it('can be constructed from bits', () => {
const int64 = Int64.fromBits(0, 1);
expect(int64.getLowBits()).toEqual(0);
expect(int64.getHighBits()).toEqual(1);
});
it('zero is defined', () => {
const int64 = Int64.getZero();
expect(int64.getLowBits()).toEqual(0);
expect(int64.getHighBits()).toEqual(0);
});
it('max value is defined', () => {
const int64 = Int64.getMaxValue();
expect(int64).toEqual(Int64.fromBits(0xFFFFFFFF, 0x7FFFFFFF));
expect(int64.asLong()).toEqual(Long.getMaxValue());
});
it('min value is defined', () => {
const int64 = Int64.getMinValue();
expect(int64).toEqual(Int64.fromBits(0, 0x80000000));
expect(int64.asLong()).toEqual(Long.getMinValue());
});
it('Can be converted to long', () => {
const int64 = Int64.fromInt(1);
expect(int64.asLong()).toEqual(Long.fromInt(1));
});
it('Negative value can be converted to long', () => {
const int64 = Int64.fromInt(-1);
expect(int64.getLowBits()).toEqual(0xFFFFFFFF | 0);
expect(int64.getHighBits()).toEqual(0xFFFFFFFF | 0);
expect(int64.asLong()).toEqual(Long.fromInt(-1));
});
it('Can be converted to number', () => {
const int64 = Int64.fromInt(1);
expect(int64.asNumber()).toEqual(1);
});
it('Can convert negative value to number', () => {
const int64 = Int64.fromInt(-1);
expect(int64.asNumber()).toEqual(-1);
});
it('MAX_SAFE_INTEGER can be used.', () => {
const int64 = Int64.fromNumber(Number.MAX_SAFE_INTEGER);
expect(int64.getLowBitsUnsigned()).toEqual(0xFFFFFFFF);
expect(int64.getHighBits()).toEqual(0x1FFFFF);
expect(int64.asNumber()).toEqual(Number.MAX_SAFE_INTEGER);
});
it('MIN_SAFE_INTEGER can be used.', () => {
const int64 = Int64.fromNumber(Number.MIN_SAFE_INTEGER);
expect(int64.asNumber()).toEqual(Number.MIN_SAFE_INTEGER);
});
it('constructs fromInt', () => {
const int64 = Int64.fromInt(1);
expect(int64.getLowBits()).toEqual(1);
expect(int64.getHighBits()).toEqual(0);
});
it('constructs fromLong', () => {
const int64 = Int64.fromLong(Long.fromInt(1));
expect(int64.getLowBits()).toEqual(1);
expect(int64.getHighBits()).toEqual(0);
});
// TODO: Use our own checking system here.
if (goog.DEBUG) {
it('asNumber throws for MAX_SAFE_INTEGER + 1', () => {
expect(() => Int64.fromNumber(Number.MAX_SAFE_INTEGER + 1).asNumber())
.toThrow();
});
it('fromInt(MAX_SAFE_INTEGER) throws', () => {
expect(() => Int64.fromInt(Number.MAX_SAFE_INTEGER)).toThrow();
});
it('fromInt(1.5) throws', () => {
expect(() => Int64.fromInt(1.5)).toThrow();
});
}
const decimalHexPairs = {
'0x0000000000000000': {signed: '0'},
'0x0000000000000001': {signed: '1'},
'0x00000000ffffffff': {signed: '4294967295'},
'0x0000000100000000': {signed: '4294967296'},
'0xffffffffffffffff': {signed: '-1', unsigned: '18446744073709551615'},
'0x8000000000000000':
{signed: '-9223372036854775808', unsigned: '9223372036854775808'},
'0x8000000080000000':
{signed: '-9223372034707292160', unsigned: '9223372039002259456'},
'0x01b69b4bacd05f15': {signed: '123456789123456789'},
'0xfe4964b4532fa0eb':
{signed: '-123456789123456789', unsigned: '18323287284586094827'},
'0xa5a5a5a5a5a5a5a5':
{signed: '-6510615555426900571', unsigned: '11936128518282651045'},
'0x5a5a5a5a5a5a5a5a': {signed: '6510615555426900570'},
'0xffffffff00000000':
{signed: '-4294967296', unsigned: '18446744069414584320'},
};
it('serializes to signed decimal strings', () => {
for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
const int64 = hexToInt64(hex);
expect(int64.toSignedDecimalString()).toEqual(decimals.signed);
}
});
it('serializes to unsigned decimal strings', () => {
for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
const int64 = hexToInt64(hex);
expect(int64.toUnsignedDecimalString())
.toEqual(decimals.unsigned || decimals.signed);
}
});
it('serializes to unsigned hex strings', () => {
for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
const int64 = hexToInt64(hex);
let shortHex = hex.replace(/0x0*/, '0x');
if (shortHex == '0x') {
shortHex = '0x0';
}
expect(int64.toHexString()).toEqual(shortHex);
}
});
it('parses decimal strings', () => {
for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
const signed = Int64.fromDecimalString(decimals.signed);
expect(int64ToHex(signed)).toEqual(hex);
if (decimals.unsigned) {
const unsigned = Int64.fromDecimalString(decimals.unsigned);
expect(int64ToHex(unsigned)).toEqual(hex);
}
}
});
it('parses hex strings', () => {
for (const [hex, decimals] of Object.entries(decimalHexPairs)) {
expect(int64ToHex(Int64.fromHexString(hex))).toEqual(hex);
}
expect(int64ToHex(Int64.fromHexString('-0x1')))
.toEqual('0xffffffffffffffff');
});
// TODO: Use our own checking system here.
if (goog.DEBUG) {
it('throws when parsing empty string', () => {
expect(() => Int64.fromDecimalString('')).toThrow();
});
it('throws when parsing float string', () => {
expect(() => Int64.fromDecimalString('1.5')).toThrow();
});
it('throws when parsing non-numeric string', () => {
expect(() => Int64.fromDecimalString('0xa')).toThrow();
});
}
it('checks if equal', () => {
const low = Int64.fromInt(1);
const high = Int64.getMaxValue();
expect(low.equals(Int64.fromInt(1))).toEqual(true);
expect(low.equals(high)).toEqual(false);
expect(high.equals(Int64.getMaxValue())).toEqual(true);
});
it('returns unique hashcode', () => {
expect(Int64.fromInt(1).hashCode()).toEqual(Int64.fromInt(1).hashCode());
expect(Int64.fromInt(1).hashCode())
.not.toEqual(Int64.fromInt(2).hashCode());
});
});
/**
* @param {string} hexString
* @return {!Int64}
*/
function hexToInt64(hexString) {
const high = hexString.slice(2, 10);
const low = hexString.slice(10);
return Int64.fromBits(parseInt(low, 16), parseInt(high, 16));
}
/**
* @param {!Int64} int64
* @return {string}
*/
function int64ToHex(int64) {
const ZEROS_32_BIT = '00000000';
const highPartialHex = int64.getHighBitsUnsigned().toString(16);
const lowPartialHex = int64.getLowBitsUnsigned().toString(16);
const highHex = ZEROS_32_BIT.slice(highPartialHex.length) + highPartialHex;
const lowHex = ZEROS_32_BIT.slice(lowPartialHex.length) + lowPartialHex;
return `0x${highHex}${lowHex}`;
}

View File

@ -1,708 +0,0 @@
/**
* @fileoverview Proto internal runtime checks.
*
* Checks are grouped into different severity, see:
* http://g3doc/third_party/protobuf/javascript/README.md#configurable-check-support-in-protocol-buffers
*
* Checks are also grouped into different sections:
* - CHECK_BOUNDS:
* Checks that ensure that indexed access is within bounds
* (e.g. an array being accessed past its size).
* - CHECK_STATE
* Checks related to the state of an object
* (e.g. a parser hitting an invalid case).
* - CHECK_TYPE:
* Checks that relate to type errors (e.g. code receives a number instead
* of a string).
*/
goog.module('protobuf.internal.checks');
const ByteString = goog.require('protobuf.ByteString');
const Int64 = goog.require('protobuf.Int64');
const WireType = goog.require('protobuf.binary.WireType');
//
// See
// http://g3doc/third_party/protobuf/javascript/README.md#configurable-check-support-in-protocol-buffers
//
/** @define{string} */
const CHECK_LEVEL_DEFINE = goog.define('protobuf.defines.CHECK_LEVEL', '');
/** @define{boolean} */
const POLYFILL_TEXT_ENCODING =
goog.define('protobuf.defines.POLYFILL_TEXT_ENCODING', true);
/**
* @const {number}
*/
const MAX_FIELD_NUMBER = Math.pow(2, 29) - 1;
/**
* The largest finite float32 value.
* @const {number}
*/
const FLOAT32_MAX = 3.4028234663852886e+38;
/** @enum {number} */
const CheckLevel = {
DEBUG: 0,
CRITICAL: 1,
OFF: 2
};
/** @return {!CheckLevel} */
function calculateCheckLevel() {
const definedLevel = CHECK_LEVEL_DEFINE.toUpperCase();
if (definedLevel === '') {
// user did not set a value, value now just depends on goog.DEBUG
return goog.DEBUG ? CheckLevel.DEBUG : CheckLevel.CRITICAL;
}
if (definedLevel === 'CRITICAL') {
return CheckLevel.CRITICAL;
}
if (definedLevel === 'OFF') {
return CheckLevel.OFF;
}
if (definedLevel === 'DEBUG') {
return CheckLevel.DEBUG;
}
throw new Error(`Unknown value for CHECK_LEVEL: ${CHECK_LEVEL_DEFINE}`);
}
const /** !CheckLevel */ CHECK_LEVEL = calculateCheckLevel();
const /** boolean */ CHECK_STATE = CHECK_LEVEL === CheckLevel.DEBUG;
const /** boolean */ CHECK_CRITICAL_STATE =
CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG;
const /** boolean */ CHECK_BOUNDS = CHECK_LEVEL === CheckLevel.DEBUG;
const /** boolean */ CHECK_CRITICAL_BOUNDS =
CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG;
const /** boolean */ CHECK_TYPE = CHECK_LEVEL === CheckLevel.DEBUG;
const /** boolean */ CHECK_CRITICAL_TYPE =
CHECK_LEVEL === CheckLevel.CRITICAL || CHECK_LEVEL === CheckLevel.DEBUG;
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* For cases where failing fast is pretty important and not failing early could
* cause bugs that are much harder to debug.
* @param {boolean} state
* @param {string=} message
* @throws {!Error} If the state is false and the check state is critical.
*/
function checkCriticalState(state, message = '') {
if (!CHECK_CRITICAL_STATE) {
return;
}
if (!state) {
throw new Error(message);
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param {boolean} state
* @param {string=} message
* @throws {!Error} If the state is false and the check state is debug.
*/
function checkState(state, message = '') {
if (!CHECK_STATE) {
return;
}
checkCriticalState(state, message);
}
/**
* Ensures that `index` specifies a valid position in an indexable object of
* size `size`. A position index may range from zero to size, inclusive.
* @param {number} index
* @param {number} size
* @throws {!Error} If the index is out of range and the check state is debug.
*/
function checkPositionIndex(index, size) {
if (!CHECK_BOUNDS) {
return;
}
checkCriticalPositionIndex(index, size);
}
/**
* Ensures that `index` specifies a valid position in an indexable object of
* size `size`. A position index may range from zero to size, inclusive.
* @param {number} index
* @param {number} size
* @throws {!Error} If the index is out of range and the check state is
* critical.
*/
function checkCriticalPositionIndex(index, size) {
if (!CHECK_CRITICAL_BOUNDS) {
return;
}
if (index < 0 || index > size) {
throw new Error(`Index out of bounds: index: ${index} size: ${size}`);
}
}
/**
* Ensures that `index` specifies a valid element in an indexable object of
* size `size`. A element index may range from zero to size, exclusive.
* @param {number} index
* @param {number} size
* @throws {!Error} If the index is out of range and the check state is
* debug.
*/
function checkElementIndex(index, size) {
if (!CHECK_BOUNDS) {
return;
}
checkCriticalElementIndex(index, size);
}
/**
* Ensures that `index` specifies a valid element in an indexable object of
* size `size`. A element index may range from zero to size, exclusive.
* @param {number} index
* @param {number} size
* @throws {!Error} If the index is out of range and the check state is
* critical.
*/
function checkCriticalElementIndex(index, size) {
if (!CHECK_CRITICAL_BOUNDS) {
return;
}
if (index < 0 || index >= size) {
throw new Error(`Index out of bounds: index: ${index} size: ${size}`);
}
}
/**
* Ensures the range of [start, end) is with the range of [0, size).
* @param {number} start
* @param {number} end
* @param {number} size
* @throws {!Error} If start and end are out of range and the check state is
* debug.
*/
function checkRange(start, end, size) {
if (!CHECK_BOUNDS) {
return;
}
checkCriticalRange(start, end, size);
}
/**
* Ensures the range of [start, end) is with the range of [0, size).
* @param {number} start
* @param {number} end
* @param {number} size
* @throws {!Error} If start and end are out of range and the check state is
* critical.
*/
function checkCriticalRange(start, end, size) {
if (!CHECK_CRITICAL_BOUNDS) {
return;
}
if (start < 0 || end < 0 || start > size || end > size) {
throw new Error(`Range error: start: ${start} end: ${end} size: ${size}`);
}
if (start > end) {
throw new Error(`Start > end: ${start} > ${end}`);
}
}
/**
* Ensures that field number is an integer and within the range of
* [1, MAX_FIELD_NUMBER].
* @param {number} fieldNumber
* @throws {!Error} If the field number is out of range and the check state is
* debug.
*/
function checkFieldNumber(fieldNumber) {
if (!CHECK_TYPE) {
return;
}
checkCriticalFieldNumber(fieldNumber);
}
/**
* Ensures that the value is neither null nor undefined.
*
* @param {T} value
* @return {R}
*
* @template T
* @template R :=
* mapunion(T, (V) =>
* cond(eq(V, 'null'),
* none(),
* cond(eq(V, 'undefined'),
* none(),
* V)))
* =:
*/
function checkDefAndNotNull(value) {
if (CHECK_TYPE) {
// Note that undefined == null.
if (value == null) {
throw new Error(`Value can't be null`);
}
}
return value;
}
/**
* Ensures that the value exists and is a function.
*
* @param {function(?): ?} func
*/
function checkFunctionExists(func) {
if (CHECK_TYPE) {
if (typeof func !== 'function') {
throw new Error(`${func} is not a function`);
}
}
}
/**
* Ensures that field number is an integer and within the range of
* [1, MAX_FIELD_NUMBER].
* @param {number} fieldNumber
* @throws {!Error} If the field number is out of range and the check state is
* critical.
*/
function checkCriticalFieldNumber(fieldNumber) {
if (!CHECK_CRITICAL_TYPE) {
return;
}
if (fieldNumber <= 0 || fieldNumber > MAX_FIELD_NUMBER) {
throw new Error(`Field number is out of range: ${fieldNumber}`);
}
}
/**
* Ensures that wire type is valid.
* @param {!WireType} wireType
* @throws {!Error} If the wire type is invalid and the check state is debug.
*/
function checkWireType(wireType) {
if (!CHECK_TYPE) {
return;
}
checkCriticalWireType(wireType);
}
/**
* Ensures that wire type is valid.
* @param {!WireType} wireType
* @throws {!Error} If the wire type is invalid and the check state is critical.
*/
function checkCriticalWireType(wireType) {
if (!CHECK_CRITICAL_TYPE) {
return;
}
if (wireType < WireType.VARINT || wireType > WireType.FIXED32) {
throw new Error(`Invalid wire type: ${wireType}`);
}
}
/**
* Ensures the given value has the correct type.
* @param {boolean} expression
* @param {string} errorMsg
* @throws {!Error} If the value has the wrong type and the check state is
* critical.
*/
function checkCriticalType(expression, errorMsg) {
if (!CHECK_CRITICAL_TYPE) {
return;
}
if (!expression) {
throw new Error(errorMsg);
}
}
/**
* Checks whether a given object is an array.
* @param {*} value
* @return {!Array<*>}
*/
function checkCriticalTypeArray(value) {
checkCriticalType(
Array.isArray(value), `Must be an array, but got: ${value}`);
return /** @type {!Array<*>} */ (value);
}
/**
* Checks whether a given object is an iterable.
* @param {*} value
* @return {!Iterable<*>}
*/
function checkCriticalTypeIterable(value) {
checkCriticalType(
!!value[Symbol.iterator], `Must be an iterable, but got: ${value}`);
return /** @type {!Iterable<*>} */ (value);
}
/**
* Checks whether a given object is a boolean.
* @param {*} value
*/
function checkCriticalTypeBool(value) {
checkCriticalType(
typeof value === 'boolean', `Must be a boolean, but got: ${value}`);
}
/**
* Checks whether a given object is an array of boolean.
* @param {*} values
*/
function checkCriticalTypeBoolArray(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeBool(value);
}
}
/**
* Checks whether a given object is a ByteString.
* @param {*} value
*/
function checkCriticalTypeByteString(value) {
checkCriticalType(
value instanceof ByteString, `Must be a ByteString, but got: ${value}`);
}
/**
* Checks whether a given object is an array of ByteString.
* @param {*} values
*/
function checkCriticalTypeByteStringArray(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeByteString(value);
}
}
/**
* Checks whether a given object is a number.
* @param {*} value
* @throws {!Error} If the value is not float and the check state is debug.
*/
function checkTypeDouble(value) {
if (!CHECK_TYPE) {
return;
}
checkCriticalTypeDouble(value);
}
/**
* Checks whether a given object is a number.
* @param {*} value
* @throws {!Error} If the value is not float and the check state is critical.
*/
function checkCriticalTypeDouble(value) {
checkCriticalType(
typeof value === 'number', `Must be a number, but got: ${value}`);
}
/**
* Checks whether a given object is an array of double.
* @param {*} values
*/
function checkCriticalTypeDoubleArray(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeDouble(value);
}
}
/**
* Checks whether a given object is a number.
* @param {*} value
* @throws {!Error} If the value is not signed int32 and the check state is
* debug.
*/
function checkTypeSignedInt32(value) {
if (!CHECK_TYPE) {
return;
}
checkCriticalTypeSignedInt32(value);
}
/**
* Checks whether a given object is a number.
* @param {*} value
* @throws {!Error} If the value is not signed int32 and the check state is
* critical.
*/
function checkCriticalTypeSignedInt32(value) {
checkCriticalTypeDouble(value);
const valueAsNumber = /** @type {number} */ (value);
if (CHECK_CRITICAL_TYPE) {
if (valueAsNumber < -Math.pow(2, 31) || valueAsNumber > Math.pow(2, 31) ||
!Number.isInteger(valueAsNumber)) {
throw new Error(`Must be int32, but got: ${valueAsNumber}`);
}
}
}
/**
* Checks whether a given object is an array of numbers.
* @param {*} values
*/
function checkCriticalTypeSignedInt32Array(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeSignedInt32(value);
}
}
/**
* Ensures that value is a long instance.
* @param {*} value
* @throws {!Error} If the value is not a long instance and check state is
* debug.
*/
function checkTypeSignedInt64(value) {
if (!CHECK_TYPE) {
return;
}
checkCriticalTypeSignedInt64(value);
}
/**
* Ensures that value is a long instance.
* @param {*} value
* @throws {!Error} If the value is not a long instance and check state is
* critical.
*/
function checkCriticalTypeSignedInt64(value) {
if (!CHECK_CRITICAL_TYPE) {
return;
}
if (!(value instanceof Int64)) {
throw new Error(`Must be Int64 instance, but got: ${value}`);
}
}
/**
* Checks whether a given object is an array of long instances.
* @param {*} values
* @throws {!Error} If values is not an array of long instances.
*/
function checkCriticalTypeSignedInt64Array(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeSignedInt64(value);
}
}
/**
* Checks whether a given object is a number and within float32 precision.
* @param {*} value
* @throws {!Error} If the value is not float and the check state is debug.
*/
function checkTypeFloat(value) {
if (!CHECK_TYPE) {
return;
}
checkCriticalTypeFloat(value);
}
/**
* Checks whether a given object is a number and within float32 precision.
* @param {*} value
* @throws {!Error} If the value is not float and the check state is critical.
*/
function checkCriticalTypeFloat(value) {
checkCriticalTypeDouble(value);
if (CHECK_CRITICAL_TYPE) {
const valueAsNumber = /** @type {number} */ (value);
if (Number.isFinite(valueAsNumber) &&
(valueAsNumber > FLOAT32_MAX || valueAsNumber < -FLOAT32_MAX)) {
throw new Error(
`Given number does not fit into float precision: ${value}`);
}
}
}
/**
* Checks whether a given object is an iterable of floats.
* @param {*} values
*/
function checkCriticalTypeFloatIterable(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const iterable = checkCriticalTypeIterable(values);
for (const value of iterable) {
checkCriticalTypeFloat(value);
}
}
/**
* Checks whether a given object is a string.
* @param {*} value
*/
function checkCriticalTypeString(value) {
checkCriticalType(
typeof value === 'string', `Must be string, but got: ${value}`);
}
/**
* Checks whether a given object is an array of string.
* @param {*} values
*/
function checkCriticalTypeStringArray(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeString(value);
}
}
/**
* Ensures that value is a valid unsigned int32.
* @param {*} value
* @throws {!Error} If the value is out of range and the check state is debug.
*/
function checkTypeUnsignedInt32(value) {
if (!CHECK_TYPE) {
return;
}
checkCriticalTypeUnsignedInt32(value);
}
/**
* Ensures that value is a valid unsigned int32.
* @param {*} value
* @throws {!Error} If the value is out of range and the check state
* is critical.
*/
function checkCriticalTypeUnsignedInt32(value) {
if (!CHECK_CRITICAL_TYPE) {
return;
}
checkCriticalTypeDouble(value);
const valueAsNumber = /** @type {number} */ (value);
if (valueAsNumber < 0 || valueAsNumber > Math.pow(2, 32) - 1 ||
!Number.isInteger(valueAsNumber)) {
throw new Error(`Must be uint32, but got: ${value}`);
}
}
/**
* Checks whether a given object is an array of unsigned int32.
* @param {*} values
*/
function checkCriticalTypeUnsignedInt32Array(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalTypeUnsignedInt32(value);
}
}
/**
* Checks whether a given object is an array of message.
* @param {*} values
*/
function checkCriticalTypeMessageArray(values) {
// TODO(b/134765672)
if (!CHECK_CRITICAL_TYPE) {
return;
}
const array = checkCriticalTypeArray(values);
for (const value of array) {
checkCriticalType(
value !== null, 'Given value is not a message instance: null');
}
}
exports = {
checkDefAndNotNull,
checkCriticalElementIndex,
checkCriticalFieldNumber,
checkCriticalPositionIndex,
checkCriticalRange,
checkCriticalState,
checkCriticalTypeBool,
checkCriticalTypeBoolArray,
checkCriticalTypeByteString,
checkCriticalTypeByteStringArray,
checkCriticalTypeDouble,
checkTypeDouble,
checkCriticalTypeDoubleArray,
checkTypeFloat,
checkCriticalTypeFloat,
checkCriticalTypeFloatIterable,
checkCriticalTypeMessageArray,
checkCriticalTypeSignedInt32,
checkCriticalTypeSignedInt32Array,
checkCriticalTypeSignedInt64,
checkTypeSignedInt64,
checkCriticalTypeSignedInt64Array,
checkCriticalTypeString,
checkCriticalTypeStringArray,
checkCriticalTypeUnsignedInt32,
checkCriticalTypeUnsignedInt32Array,
checkCriticalType,
checkCriticalWireType,
checkElementIndex,
checkFieldNumber,
checkFunctionExists,
checkPositionIndex,
checkRange,
checkState,
checkTypeUnsignedInt32,
checkTypeSignedInt32,
checkWireType,
CHECK_BOUNDS,
CHECK_CRITICAL_BOUNDS,
CHECK_STATE,
CHECK_CRITICAL_STATE,
CHECK_TYPE,
CHECK_CRITICAL_TYPE,
MAX_FIELD_NUMBER,
POLYFILL_TEXT_ENCODING,
};

Some files were not shown because too many files have changed in this diff Show More