You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by ch...@apache.org on 2026/07/02 15:46:30 UTC
(fory) branch main updated: chore(javascript): add javascript code format (#3813)
This is an automated email from the ASF dual-hosted git repository.
chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git
The following commit(s) were added to refs/heads/main by this push:
new 99b9553dd chore(javascript): add javascript code format (#3813)
99b9553dd is described below
commit 99b9553dd0c59f507a3a371614867ef2598c4a16
Author: Shawn Yang <sh...@gmail.com>
AuthorDate: Thu Jul 2 21:16:26 2026 +0530
chore(javascript): add javascript code format (#3813)
## Why?
## What does this PR do?
## Related issues
## AI Contribution Checklist
- [ ] Substantial AI assistance was used in this PR: `yes` / `no`
- [ ] If `yes`, I included a completed [AI Contribution
Checklist](https://github.com/apache/fory/blob/main/AI_POLICY.md#9-contributor-checklist-for-ai-assisted-prs)
in this PR description and the required `AI Usage Disclosure`.
- [ ] If `yes`, my PR description includes the required `ai_review`
summary and screenshot evidence or equivalent persisted links of the
final clean AI review results from both fresh reviewers described in
`AI_POLICY.md`, the Fory-guided reviewer and the independent general
reviewer, on the current PR diff or current HEAD after the latest code
changes.
## Does this PR introduce any user-facing change?
- [ ] Does this PR introduce any public API change?
- [ ] Does this PR introduce any binary protocol compatibility change?
## Benchmark
---
.agents/languages/javascript.md | 7 +-
.gitattributes | 5 +
ci/run_ci.sh | 4 +-
ci/tasks/javascript.py | 1 +
javascript/.eslintrc.cjs | 25 +-
javascript/.npmrc | 2 +-
javascript/.prettierignore | 6 +
javascript/.prettierrc | 8 +
javascript/package-lock.json | 262 +------
javascript/package.json | 9 +-
javascript/packages/core/index.ts | 6 +-
javascript/packages/core/lib/compatible/scalar.ts | 60 +-
javascript/packages/core/lib/context.ts | 381 +++-------
javascript/packages/core/lib/fory.ts | 60 +-
javascript/packages/core/lib/gen/builder.ts | 35 +-
javascript/packages/core/lib/gen/collection.ts | 94 +--
javascript/packages/core/lib/gen/datetime.ts | 4 +-
javascript/packages/core/lib/gen/enum.ts | 83 ++-
javascript/packages/core/lib/gen/ext.ts | 116 +--
javascript/packages/core/lib/gen/index.ts | 28 +-
javascript/packages/core/lib/gen/map.ts | 136 ++--
javascript/packages/core/lib/gen/number.ts | 131 ++--
javascript/packages/core/lib/gen/router.ts | 10 +-
javascript/packages/core/lib/gen/scope.ts | 8 +-
javascript/packages/core/lib/gen/serializer.ts | 34 +-
javascript/packages/core/lib/gen/struct.ts | 436 +++++------
javascript/packages/core/lib/gen/typedArray.ts | 11 +-
javascript/packages/core/lib/gen/union.ts | 47 +-
javascript/packages/core/lib/meta/MetaString.ts | 112 ++-
javascript/packages/core/lib/meta/TypeMeta.ts | 228 ++----
javascript/packages/core/lib/murmurHash3.ts | 164 ++---
javascript/packages/core/lib/platformBuffer.ts | 24 +-
javascript/packages/core/lib/reader/index.ts | 38 +-
javascript/packages/core/lib/reader/string.ts | 152 +++-
javascript/packages/core/lib/type.ts | 15 +-
javascript/packages/core/lib/typeInfo.ts | 778 ++++++++++----------
javascript/packages/core/lib/typeResolver.ts | 18 +-
javascript/packages/core/lib/types/boolArray.ts | 8 +-
javascript/packages/core/lib/types/decimal.ts | 6 +-
javascript/packages/core/lib/types/float16.ts | 19 +-
javascript/packages/core/lib/util.ts | 10 +-
javascript/packages/core/lib/writer/index.ts | 55 +-
javascript/test/any.test.ts | 167 ++---
javascript/test/array.test.ts | 277 ++++---
javascript/test/binary.test.ts | 36 +-
javascript/test/bool.test.ts | 25 +-
javascript/test/crossLanguage.test.ts | 44 +-
javascript/test/decimal.test.ts | 22 +-
javascript/test/depthLimit.test.ts | 285 +++----
javascript/test/enum.test.ts | 86 +--
javascript/test/fory.test.ts | 120 ++-
javascript/test/hps.test.ts | 39 +-
javascript/test/io.test.ts | 858 ++++++++++++----------
javascript/test/map.test.ts | 51 +-
javascript/test/number.test.ts | 430 ++++++-----
javascript/test/object.test.ts | 183 +++--
javascript/test/platformBuffer.test.ts | 142 ++--
javascript/test/protocol/struct.test.ts | 132 ++--
javascript/test/reader.test.ts | 87 ++-
javascript/test/set.test.ts | 51 +-
javascript/test/string.test.ts | 48 +-
javascript/test/typemeta.test.ts | 378 +++-------
javascript/test/union.test.ts | 198 +++--
javascript/test/writer.test.ts | 90 +--
64 files changed, 3586 insertions(+), 3799 deletions(-)
diff --git a/.agents/languages/javascript.md b/.agents/languages/javascript.md
index 9ebf99d3b..e6d62fa49 100644
--- a/.agents/languages/javascript.md
+++ b/.agents/languages/javascript.md
@@ -27,6 +27,9 @@ npm install
# Run tests
node ./node_modules/.bin/jest --ci --reporters=default --reporters=jest-junit
-# Lint TypeScript
-git ls-files -- '*.ts' | xargs -P 5 node ./node_modules/.bin/eslint
+# Check TypeScript formatting and lint rules
+npm run format-check
+
+# Format TypeScript, then apply ESLint fixes
+npm run format
```
diff --git a/.gitattributes b/.gitattributes
index b100d82b6..a0d8395fc 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,2 +1,7 @@
benchmarks export-ignore
integration_tests export-ignore
+
+javascript/**/*.cjs text eol=lf
+javascript/**/*.js text eol=lf
+javascript/**/*.json text eol=lf
+javascript/**/*.ts text eol=lf
diff --git a/ci/run_ci.sh b/ci/run_ci.sh
index 4081aecf2..443e751be 100755
--- a/ci/run_ci.sh
+++ b/ci/run_ci.sh
@@ -348,7 +348,9 @@ case $1 in
echo "Executing fory javascript tests"
cd "$ROOT/javascript"
npm install
- node ./node_modules/.bin/jest --ci --reporters=default --reporters=jest-junit
+ npm run format-check \
+ && npm run build \
+ && node ./node_modules/.bin/jest --ci --reporters=default --reporters=jest-junit
testcode=$?
if [[ $testcode -ne 0 ]]; then
echo "Executing fory javascript tests failed"
diff --git a/ci/tasks/javascript.py b/ci/tasks/javascript.py
index 5b4031988..28450fd4d 100644
--- a/ci/tasks/javascript.py
+++ b/ci/tasks/javascript.py
@@ -24,6 +24,7 @@ def run():
logging.info("Executing fory javascript tests.")
common.cd_project_subdir("javascript")
common.exec_cmd("npm install")
+ common.exec_cmd("npm run format-check")
common.exec_cmd("npm run test")
logging.info("Executing fory javascript tests succeeds.")
diff --git a/javascript/.eslintrc.cjs b/javascript/.eslintrc.cjs
index 16291aee4..161ac18b4 100644
--- a/javascript/.eslintrc.cjs
+++ b/javascript/.eslintrc.cjs
@@ -17,26 +17,23 @@
* under the License.
*/
-const stylistic = require("@stylistic/eslint-plugin");
-
-const customized = stylistic.configs.customize({
- indent: 2,
- quotes: "double",
- semi: true,
- jsx: true,
-});
-
module.exports = {
- extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
+ extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
parser: "@typescript-eslint/parser",
- plugins: ["@typescript-eslint", "@stylistic"],
+ plugins: ["@typescript-eslint"],
root: true,
rules: {
- ...customized.rules,
- "@stylistic/brace-style": ["error", "1tbs"],
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-var-requires": "off",
},
- ignorePatterns: ["test/*", "dist/*", "*.js", "murmurHash3.ts", "packages/**/dist/*", "packages/**/build/*", "**/typeInfo.ts"],
+ ignorePatterns: [
+ "test/*",
+ "dist/*",
+ "*.js",
+ "murmurHash3.ts",
+ "packages/**/dist/*",
+ "packages/**/build/*",
+ "**/typeInfo.ts",
+ ],
};
diff --git a/javascript/.npmrc b/javascript/.npmrc
index 43c97e719..cafe685a1 100644
--- a/javascript/.npmrc
+++ b/javascript/.npmrc
@@ -1 +1 @@
-package-lock=false
+package-lock=true
diff --git a/javascript/.prettierignore b/javascript/.prettierignore
new file mode 100644
index 000000000..124cfadd5
--- /dev/null
+++ b/javascript/.prettierignore
@@ -0,0 +1,6 @@
+node_modules
+packages/**/dist
+packages/**/build
+coverage
+coverage-final.json
+jest-junit.xml
diff --git a/javascript/.prettierrc b/javascript/.prettierrc
new file mode 100644
index 000000000..04e09e44c
--- /dev/null
+++ b/javascript/.prettierrc
@@ -0,0 +1,8 @@
+{
+ "printWidth": 100,
+ "tabWidth": 2,
+ "useTabs": false,
+ "semi": true,
+ "singleQuote": false,
+ "trailingComma": "all"
+}
diff --git a/javascript/package-lock.json b/javascript/package-lock.json
index 39fe76b1d..1674116f6 100644
--- a/javascript/package-lock.json
+++ b/javascript/package-lock.json
@@ -9,13 +9,14 @@
"packages/core"
],
"devDependencies": {
- "@stylistic/eslint-plugin": "^1.5.1",
"@types/js-beautify": "^1.14.3",
"@types/node": "18.19.130",
"eslint": "^8.55.0",
+ "eslint-config-prettier": "^10.1.8",
"jest": "^29.5.0",
"jest-junit": "^17.0.0",
"js-beautify": "^1.14.11",
+ "prettier": "^3.9.4",
"ts-jest": "^29.0.2",
"typescript": "^4.8.4"
}
@@ -1449,97 +1450,6 @@
"@sinonjs/commons": "^3.0.0"
}
},
- "node_modules/@stylistic/eslint-plugin": {
- "version": "1.8.1",
- "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-1.8.1.tgz",
- "integrity": "sha512-64My6I7uCcmSQ//427Pfg2vjSf9SDzfsGIWohNFgISMLYdC5BzJqDo647iDDJzSxINh3WTC0Ql46ifiKuOoTyA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@stylistic/eslint-plugin-js": "1.8.1",
- "@stylistic/eslint-plugin-jsx": "1.8.1",
- "@stylistic/eslint-plugin-plus": "1.8.1",
- "@stylistic/eslint-plugin-ts": "1.8.1",
- "@types/eslint": "^8.56.10"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "peerDependencies": {
- "eslint": ">=8.40.0"
- }
- },
- "node_modules/@stylistic/eslint-plugin-js": {
- "version": "1.8.1",
- "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin-js/-/eslint-plugin-js-1.8.1.tgz",
- "integrity": "sha512-c5c2C8Mos5tTQd+NWpqwEu7VT6SSRooAguFPMj1cp2RkTYl1ynKoXo8MWy3k4rkbzoeYHrqC2UlUzsroAN7wtQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/eslint": "^8.56.10",
- "acorn": "^8.11.3",
- "escape-string-regexp": "^4.0.0",
- "eslint-visitor-keys": "^3.4.3",
- "espree": "^9.6.1"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "peerDependencies": {
- "eslint": ">=8.40.0"
- }
- },
- "node_modules/@stylistic/eslint-plugin-jsx": {
- "version": "1.8.1",
- "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin-jsx/-/eslint-plugin-jsx-1.8.1.tgz",
- "integrity": "sha512-k1Eb6rcjMP+mmjvj+vd9y5KUdWn1OBkkPLHXhsrHt5lCDFZxJEs0aVQzE5lpYrtVZVkpc5esTtss/cPJux0lfA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@stylistic/eslint-plugin-js": "^1.8.1",
- "@types/eslint": "^8.56.10",
- "estraverse": "^5.3.0",
- "picomatch": "^4.0.2"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "peerDependencies": {
- "eslint": ">=8.40.0"
- }
- },
- "node_modules/@stylistic/eslint-plugin-plus": {
- "version": "1.8.1",
- "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin-plus/-/eslint-plugin-plus-1.8.1.tgz",
- "integrity": "sha512-4+40H3lHYTN8OWz+US8CamVkO+2hxNLp9+CAjorI7top/lHqemhpJvKA1LD9Uh+WMY9DYWiWpL2+SZ2wAXY9fQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/eslint": "^8.56.10",
- "@typescript-eslint/utils": "^6.21.0"
- },
- "peerDependencies": {
- "eslint": "*"
- }
- },
- "node_modules/@stylistic/eslint-plugin-ts": {
- "version": "1.8.1",
- "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin-ts/-/eslint-plugin-ts-1.8.1.tgz",
- "integrity": "sha512-/q1m+ZuO1JHfiSF16EATFzv7XSJkc5W6DocfvH5o9oB6WWYFMF77fVoBWnKT3wGptPOc2hkRupRKhmeFROdfWA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@stylistic/eslint-plugin-js": "1.8.1",
- "@types/eslint": "^8.56.10",
- "@typescript-eslint/utils": "^6.21.0"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "peerDependencies": {
- "eslint": ">=8.40.0"
- }
- },
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -1585,24 +1495,6 @@
"@babel/types": "^7.28.2"
}
},
- "node_modules/@types/eslint": {
- "version": "8.56.12",
- "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.56.12.tgz",
- "integrity": "sha512-03ruubjWyOHlmljCVoxSuNDdmfZDzsrrz0P2LeJsOXr+ZwFQ+0yQIwNCwt/GYhV7Z31fgtXJTAEs+FYlEL851g==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/estree": "*",
- "@types/json-schema": "*"
- }
- },
- "node_modules/@types/estree": {
- "version": "1.0.9",
- "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
- "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/graceful-fs": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz",
@@ -1965,24 +1857,6 @@
"url": "https://opencollective.com/typescript-eslint"
}
},
- "node_modules/@typescript-eslint/scope-manager": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.21.0.tgz",
- "integrity": "sha512-OwLUIWZJry80O99zvqXVEioyniJMa+d2GrqpUTqi5/v5D5rOrppJVBPa0yKCblcigC0/aYAzxxqQ1B+DS2RYsg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@typescript-eslint/types": "6.21.0",
- "@typescript-eslint/visitor-keys": "6.21.0"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/typescript-eslint"
- }
- },
"node_modules/@typescript-eslint/type-utils": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz",
@@ -2140,93 +2014,6 @@
"node": ">=4.0"
}
},
- "node_modules/@typescript-eslint/types": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.21.0.tgz",
- "integrity": "sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/typescript-eslint"
- }
- },
- "node_modules/@typescript-eslint/typescript-estree": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.21.0.tgz",
- "integrity": "sha512-6npJTkZcO+y2/kr+z0hc4HwNfrrP4kNYh57ek7yCNlrBjWQ1Y0OS7jiZTkgumrvkX5HkEKXFZkkdFNkaW2wmUQ==",
- "dev": true,
- "license": "BSD-2-Clause",
- "dependencies": {
- "@typescript-eslint/types": "6.21.0",
- "@typescript-eslint/visitor-keys": "6.21.0",
- "debug": "^4.3.4",
- "globby": "^11.1.0",
- "is-glob": "^4.0.3",
- "minimatch": "9.0.3",
- "semver": "^7.5.4",
- "ts-api-utils": "^1.0.1"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/typescript-eslint"
- },
- "peerDependenciesMeta": {
- "typescript": {
- "optional": true
- }
- }
- },
- "node_modules/@typescript-eslint/utils": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.21.0.tgz",
- "integrity": "sha512-NfWVaC8HP9T8cbKQxHcsJBY5YE1O33+jpMwN45qzWWaPDZgLIbo12toGMWnmhvCpd3sIxkpDw3Wv1B3dYrbDQQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@eslint-community/eslint-utils": "^4.4.0",
- "@types/json-schema": "^7.0.12",
- "@types/semver": "^7.5.0",
- "@typescript-eslint/scope-manager": "6.21.0",
- "@typescript-eslint/types": "6.21.0",
- "@typescript-eslint/typescript-estree": "6.21.0",
- "semver": "^7.5.4"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/typescript-eslint"
- },
- "peerDependencies": {
- "eslint": "^7.0.0 || ^8.0.0"
- }
- },
- "node_modules/@typescript-eslint/visitor-keys": {
- "version": "6.21.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.21.0.tgz",
- "integrity": "sha512-JJtkDduxLi9bivAB+cYOVMtbkqdPOhZ+ZI5LC47MIRrDV4Yn2o+ZnW10Nkmr28xRpSpdJ6Sm42Hjf2+REYXm0A==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@typescript-eslint/types": "6.21.0",
- "eslint-visitor-keys": "^3.4.1"
- },
- "engines": {
- "node": "^16.0.0 || >=18.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/typescript-eslint"
- }
- },
"node_modules/@ungap/structured-clone": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz",
@@ -3181,6 +2968,22 @@
"url": "https://opencollective.com/eslint"
}
},
+ "node_modules/eslint-config-prettier": {
+ "version": "10.1.8",
+ "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz",
+ "integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "eslint-config-prettier": "bin/cli.js"
+ },
+ "funding": {
+ "url": "https://opencollective.com/eslint-config-prettier"
+ },
+ "peerDependencies": {
+ "eslint": ">=7.0.0"
+ }
+ },
"node_modules/eslint-scope": {
"version": "7.2.2",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz",
@@ -5788,6 +5591,22 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/prettier": {
+ "version": "3.9.4",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.4.tgz",
+ "integrity": "sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "prettier": "bin/prettier.cjs"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/prettier/prettier?sponsor=1"
+ }
+ },
"node_modules/pretty-format": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz",
@@ -6474,19 +6293,6 @@
"node": ">=8.0"
}
},
- "node_modules/ts-api-utils": {
- "version": "1.4.3",
- "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
- "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=16"
- },
- "peerDependencies": {
- "typescript": ">=4.2.0"
- }
- },
"node_modules/ts-jest": {
"version": "29.4.11",
"resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.11.tgz",
diff --git a/javascript/package.json b/javascript/package.json
index d1d10c794..bf4ae68e4 100644
--- a/javascript/package.json
+++ b/javascript/package.json
@@ -4,8 +4,10 @@
"test": "npm run build && jest",
"clear": "rm -rf ./packages/core/dist && rm -rf ./packages/hps/dist",
"build": "npm run clear && npm run build -w packages/core -w packages/hps",
- "lint": "eslint .",
- "lint-fix": "eslint . --fix"
+ "lint": "npm run format-check",
+ "lint-fix": "npm run format",
+ "format": "prettier --write \"{packages,test}/**/*.ts\" && eslint . --fix",
+ "format-check": "prettier --check \"{packages,test}/**/*.ts\" && eslint ."
},
"repository": "git@github.com:apache/fory.git",
"workspaces": [
@@ -13,13 +15,14 @@
"packages/core"
],
"devDependencies": {
- "@stylistic/eslint-plugin": "^1.5.1",
"@types/js-beautify": "^1.14.3",
"@types/node": "18.19.130",
"eslint": "^8.55.0",
+ "eslint-config-prettier": "^10.1.8",
"jest": "^29.5.0",
"jest-junit": "^17.0.0",
"js-beautify": "^1.14.11",
+ "prettier": "^3.9.4",
"ts-jest": "^29.0.2",
"typescript": "^4.8.4"
},
diff --git a/javascript/packages/core/index.ts b/javascript/packages/core/index.ts
index a0c99e25c..869ad3497 100644
--- a/javascript/packages/core/index.ts
+++ b/javascript/packages/core/index.ts
@@ -17,11 +17,7 @@
* under the License.
*/
-import {
- TypeInfo,
- Type,
- Dynamic,
-} from "./lib/typeInfo";
+import { TypeInfo, Type, Dynamic } from "./lib/typeInfo";
import { Serializer, Mode } from "./lib/type";
import Fory from "./lib/fory";
import { BinaryReader } from "./lib/reader";
diff --git a/javascript/packages/core/lib/compatible/scalar.ts b/javascript/packages/core/lib/compatible/scalar.ts
index 5d78cbccc..22c246a5c 100644
--- a/javascript/packages/core/lib/compatible/scalar.ts
+++ b/javascript/packages/core/lib/compatible/scalar.ts
@@ -52,8 +52,7 @@ const INT32_MIN = -2147483648n;
const INT32_MAX = 2147483647n;
const MAX_COMPATIBLE_DECIMAL_DIGITS = 256;
const MAX_COMPATIBLE_NUMERIC_TEXT_LENGTH = 320;
-const MAX_COMPATIBLE_DECIMAL_MAGNITUDE
- = 10n ** BigInt(MAX_COMPATIBLE_DECIMAL_DIGITS);
+const MAX_COMPATIBLE_DECIMAL_MAGNITUDE = 10n ** BigInt(MAX_COMPATIBLE_DECIMAL_DIGITS);
const INT64_MIN = -(1n << 63n);
const INT64_MAX = (1n << 63n) - 1n;
const UINT8_MAX = 255n;
@@ -79,10 +78,7 @@ export function isCompatibleScalarType(typeId: number): boolean {
return scalarKind(typeId) !== undefined;
}
-export function isCompatibleScalarPair(
- remoteTypeId: number,
- localTypeId: number,
-): boolean {
+export function isCompatibleScalarPair(remoteTypeId: number, localTypeId: number): boolean {
if (remoteTypeId === localTypeId) {
return scalarKind(remoteTypeId) !== undefined;
}
@@ -158,12 +154,9 @@ function readDecimal(reader: BinaryReader): Decimal {
}
const magnitudeBytes = reader.buffer(length);
if (magnitudeBytes[length - 1] === 0) {
- throw new Error(
- "Non-canonical decimal magnitude bytes: trailing zero byte.",
- );
+ throw new Error("Non-canonical decimal magnitude bytes: trailing zero byte.");
}
- const magnitude
- = DecimalCodec.fromCanonicalLittleEndianMagnitude(magnitudeBytes);
+ const magnitude = DecimalCodec.fromCanonicalLittleEndianMagnitude(magnitudeBytes);
if (magnitude === 0n) {
throw new Error("Big decimal encoding must not represent zero.");
}
@@ -196,13 +189,8 @@ function normalizeParts(value: DecimalParts): DecimalParts {
scale--;
}
const digits = decimalDigitCount(unscaled);
- if (
- scale > MAX_COMPATIBLE_DECIMAL_DIGITS
- || digits > MAX_COMPATIBLE_DECIMAL_DIGITS
- ) {
- throw new Error(
- "Scalar decimal magnitude exceeds compatible conversion limit.",
- );
+ if (scale > MAX_COMPATIBLE_DECIMAL_DIGITS || digits > MAX_COMPATIBLE_DECIMAL_DIGITS) {
+ throw new Error("Scalar decimal magnitude exceeds compatible conversion limit.");
}
return { unscaled, scale, negativeZero: false };
}
@@ -214,9 +202,7 @@ function decimalToParts(value: Decimal): DecimalParts {
if (value.scale < 0) {
const digits = decimalDigitCount(value.unscaledValue);
if (digits - value.scale > MAX_COMPATIBLE_DECIMAL_DIGITS) {
- throw new Error(
- "Scalar decimal magnitude exceeds compatible conversion limit.",
- );
+ throw new Error("Scalar decimal magnitude exceeds compatible conversion limit.");
}
return normalizeParts({
unscaled: value.unscaledValue * pow10(-value.scale),
@@ -368,10 +354,7 @@ function parseDecimalString(value: string): DecimalParts {
exponent = -exponent;
}
}
- if (
- index !== value.length
- || significantDigits > MAX_COMPATIBLE_DECIMAL_DIGITS
- ) {
+ if (index !== value.length || significantDigits > MAX_COMPATIBLE_DECIMAL_DIGITS) {
throw new Error(`Invalid scalar string magnitude in "${value}".`);
}
let scale = fractionEnd - fractionStart - exponent;
@@ -402,9 +385,7 @@ function decimalShapeFits(significantDigits: number, scale: number): boolean {
if (scale > MAX_COMPATIBLE_DECIMAL_DIGITS) {
return false;
}
- return (
- scale >= 0 || significantDigits + -scale <= MAX_COMPATIBLE_DECIMAL_DIGITS
- );
+ return scale >= 0 || significantDigits + -scale <= MAX_COMPATIBLE_DECIMAL_DIGITS;
}
function decimalDigitCount(value: bigint): number {
@@ -428,9 +409,7 @@ function formatParts(value: DecimalParts, forceDecimal: boolean): string {
return forceDecimal ? "0.0" : "0";
}
const negative = normalized.unscaled < 0n;
- const digits = (
- negative ? -normalized.unscaled : normalized.unscaled
- ).toString();
+ const digits = (negative ? -normalized.unscaled : normalized.unscaled).toString();
let result: string;
if (normalized.scale === 0) {
result = forceDecimal ? `${digits}.0` : digits;
@@ -446,11 +425,7 @@ function formatParts(value: DecimalParts, forceDecimal: boolean): string {
function partsEqual(left: DecimalParts, right: DecimalParts): boolean {
const l = normalizeParts(left);
const r = normalizeParts(right);
- return (
- l.unscaled === r.unscaled
- && l.scale === r.scale
- && l.negativeZero === r.negativeZero
- );
+ return l.unscaled === r.unscaled && l.scale === r.scale && l.negativeZero === r.negativeZero;
}
function partsToNumber(value: DecimalParts): number {
@@ -468,9 +443,7 @@ function exactInteger(value: DecimalParts): bigint {
function exactFloat(value: DecimalParts, localTypeId: number): number {
let candidate = partsToNumber(value);
if (!Number.isFinite(candidate)) {
- throw new Error(
- "Scalar value is not exactly representable as a finite float.",
- );
+ throw new Error("Scalar value is not exactly representable as a finite float.");
}
switch (canonicalScalarTypeId(localTypeId)) {
case TypeId.FLOAT16:
@@ -487,17 +460,12 @@ function exactFloat(value: DecimalParts, localTypeId: number): number {
break;
}
if (!partsEqual(value, floatToParts(candidate))) {
- throw new Error(
- "Scalar value is not exactly representable by the target float type.",
- );
+ throw new Error("Scalar value is not exactly representable by the target float type.");
}
return candidate;
}
-function rangeCheckedInteger(
- value: number | bigint,
- localTypeId: number,
-): number | bigint {
+function rangeCheckedInteger(value: number | bigint, localTypeId: number): number | bigint {
const integer = typeof value === "bigint" ? value : BigInt(value);
switch (canonicalScalarTypeId(localTypeId)) {
case TypeId.INT8:
diff --git a/javascript/packages/core/lib/context.ts b/javascript/packages/core/lib/context.ts
index bccde267e..3b50a5833 100644
--- a/javascript/packages/core/lib/context.ts
+++ b/javascript/packages/core/lib/context.ts
@@ -19,11 +19,7 @@
import { BinaryReader } from "./reader";
import { BinaryWriter } from "./writer";
-import {
- MetaString,
- MetaStringDecoder,
- MetaStringEncoder,
-} from "./meta/MetaString";
+import { MetaString, MetaStringDecoder, MetaStringEncoder } from "./meta/MetaString";
import { InnerFieldInfo, TypeMeta } from "./meta/TypeMeta";
import { Type, TypeInfo } from "./typeInfo";
import { Config, RefFlags, Serializer, TypeId } from "./type";
@@ -52,9 +48,7 @@ type CompatibleReadSerializerCacheEntry = {
serializer: Serializer;
};
-function remoteListElementType(
- fieldInfo: InnerFieldInfo,
-): InnerFieldInfo | undefined {
+function remoteListElementType(fieldInfo: InnerFieldInfo): InnerFieldInfo | undefined {
if (fieldInfo.typeId !== TypeId.LIST) {
return undefined;
}
@@ -541,15 +535,11 @@ export class ReadContext {
private typeMetaCache: Map<number, TypeMeta> = new Map();
private totalAcceptedSchemaVersions = 0;
private cachedTypeMeta: TypeMeta | undefined;
- private compatibleReadSerializers = new Map<
- number,
- CompatibleReadSerializerCacheEntry
- >();
+ private compatibleReadSerializers = new Map<number, CompatibleReadSerializerCacheEntry>();
private _depth = 0;
private _maxDepth: number;
- private remoteSchemaVersionsByType: Map<string | number, number> | undefined
- = undefined;
+ private remoteSchemaVersionsByType: Map<string | number, number> | undefined = undefined;
constructor(
readonly typeResolver: TypeResolverLike,
@@ -577,8 +567,8 @@ export class ReadContext {
this._depth++;
if (this._depth > this._maxDepth) {
throw new Error(
- `Deserialization depth limit exceeded: ${this._depth} > ${this._maxDepth}. `
- + "The data may be malicious, or increase maxDepth if needed.",
+ `Deserialization depth limit exceeded: ${this._depth} > ${this._maxDepth}. ` +
+ "The data may be malicious, or increase maxDepth if needed.",
);
}
}
@@ -638,12 +628,7 @@ export class ReadContext {
const idOrLen = this.reader.readVarUInt32();
if (idOrLen & 1) {
const typeMeta = this.readTypeMetaRef(idOrLen);
- this.checkNamedTypeMeta(
- typeMeta,
- expectedTypeId,
- expectedNamespace,
- expectedTypeName,
- );
+ this.checkNamedTypeMeta(typeMeta, expectedTypeId, expectedNamespace, expectedTypeName);
return typeMeta;
}
const dynamicTypeId = idOrLen >> 1;
@@ -676,21 +661,14 @@ export class ReadContext {
this.typeResolver.config.maxTypeMetaBytes,
);
const typeMetaEnd = this.reader.readGetCursor();
- this.checkNamedTypeMeta(
- typeMeta,
- expectedTypeId,
- expectedNamespace,
- expectedTypeName,
- );
+ this.checkNamedTypeMeta(typeMeta, expectedTypeId, expectedNamespace, expectedTypeName);
const localSerializer = this.serializerByTypeMeta(typeMeta);
if (localSerializer === undefined) {
throw new Error(
`can't find serializer for TypeMeta ${typeMeta.getNs()}$${typeMeta.getTypeName()}`,
);
}
- if (
- this.matchesExactLocalTypeMeta(typeMeta, typeMetaStart, typeMetaEnd)
- ) {
+ if (this.matchesExactLocalTypeMeta(typeMeta, typeMetaStart, typeMetaEnd)) {
this.cacheTypeMeta(headerHash, typeMeta, undefined);
} else {
const typeKey = this.checkRemoteTypeMetaLimit(typeMeta);
@@ -700,20 +678,12 @@ export class ReadContext {
return typeMeta;
}
}
- this.checkNamedTypeMeta(
- typeMeta,
- expectedTypeId,
- expectedNamespace,
- expectedTypeName,
- );
+ this.checkNamedTypeMeta(typeMeta, expectedTypeId, expectedNamespace, expectedTypeName);
this.typeMeta[dynamicTypeId] = typeMeta;
return typeMeta;
}
- readCompatibleStructSerializer(
- localHash: number,
- original?: Serializer,
- ): Serializer | undefined {
+ readCompatibleStructSerializer(localHash: number, original?: Serializer): Serializer | undefined {
const idOrLen = this.reader.readVarUInt32();
let typeMeta: TypeMeta;
let remoteHash: number;
@@ -739,12 +709,7 @@ export class ReadContext {
remoteHash = headerHash;
}
if (localHash !== remoteHash) {
- return this.ensureCompatibleReadSerializer(
- typeMeta,
- localHash,
- remoteHash,
- original,
- );
+ return this.ensureCompatibleReadSerializer(typeMeta, localHash, remoteHash, original);
}
return undefined;
}
@@ -765,14 +730,14 @@ export class ReadContext {
expectedTypeName: string,
) {
if (
- typeMeta.getTypeId() !== expectedTypeId
- || typeMeta.getNs() !== expectedNamespace
- || typeMeta.getTypeName() !== expectedTypeName
+ typeMeta.getTypeId() !== expectedTypeId ||
+ typeMeta.getNs() !== expectedNamespace ||
+ typeMeta.getTypeName() !== expectedTypeName
) {
throw new Error(
- `TypeMeta mismatch: expected ${expectedNamespace}$${expectedTypeName} `
- + `type ${expectedTypeId}, got ${typeMeta.getNs()}$${typeMeta.getTypeName()} `
- + `type ${typeMeta.getTypeId()}`,
+ `TypeMeta mismatch: expected ${expectedNamespace}$${expectedTypeName} ` +
+ `type ${expectedTypeId}, got ${typeMeta.getNs()}$${typeMeta.getTypeName()} ` +
+ `type ${typeMeta.getTypeId()}`,
);
}
}
@@ -813,25 +778,17 @@ export class ReadContext {
this.typeResolver.config.maxTypeMetaBytes,
);
const typeMetaEnd = this.reader.readGetCursor();
- if (
- this.matchesExactLocalTypeMeta(typeMeta, typeMetaStart, typeMetaEnd)
- ) {
+ if (this.matchesExactLocalTypeMeta(typeMeta, typeMetaStart, typeMetaEnd)) {
this.cacheTypeMeta(headerHash, typeMeta, undefined);
} else {
const localSerializer = original ?? this.serializerByTypeMeta(typeMeta);
- if (
- localSerializer === undefined
- && !TypeId.structType(typeMeta.getTypeId())
- ) {
+ if (localSerializer === undefined && !TypeId.structType(typeMeta.getTypeId())) {
throw new Error(
`can't find serializer for TypeMeta ${typeMeta.getNs()}$${typeMeta.getTypeName()}`,
);
}
const typeKey = this.checkRemoteTypeMetaLimit(typeMeta);
- if (
- localSerializer !== undefined
- && TypeId.structType(typeMeta.getTypeId())
- ) {
+ if (localSerializer !== undefined && TypeId.structType(typeMeta.getTypeId())) {
const expectedHash = localHash ?? localSerializer.getHash();
if (expectedHash !== typeMeta.getHash()) {
this.ensureCompatibleReadSerializer(
@@ -841,16 +798,8 @@ export class ReadContext {
localSerializer,
);
}
- } else if (
- localHash !== undefined
- && localHash !== typeMeta.getHash()
- ) {
- this.ensureCompatibleReadSerializer(
- typeMeta,
- localHash,
- typeMeta.getHash(),
- original,
- );
+ } else if (localHash !== undefined && localHash !== typeMeta.getHash()) {
+ this.ensureCompatibleReadSerializer(typeMeta, localHash, typeMeta.getHash(), original);
}
this.cacheTypeMeta(headerHash, typeMeta, typeKey);
}
@@ -883,33 +832,30 @@ export class ReadContext {
: typeMeta.getUserTypeId();
const versionsByType = this.remoteSchemaVersionsByType;
const versionsForType = versionsByType?.get(typeKey) ?? 0;
- const maxSchemaVersionsPerType
- = this.typeResolver.config.maxSchemaVersionsPerType;
+ const maxSchemaVersionsPerType = this.typeResolver.config.maxSchemaVersionsPerType;
if (versionsForType >= maxSchemaVersionsPerType) {
throw new Error(
- `Remote schema version limit exceeded for type ${String(typeKey)}: `
- + `${versionsForType} >= ${maxSchemaVersionsPerType}. The data may `
- + "be malicious. If the data is not malicious, please increase "
- + "maxSchemaVersionsPerType.",
+ `Remote schema version limit exceeded for type ${String(typeKey)}: ` +
+ `${versionsForType} >= ${maxSchemaVersionsPerType}. The data may ` +
+ "be malicious. If the data is not malicious, please increase " +
+ "maxSchemaVersionsPerType.",
);
}
- const acceptedTypeCount
- = versionsForType === 0
- ? (versionsByType?.size ?? 0) + 1
- : versionsByType!.size;
- const maxAverageSchemaVersionsPerType
- = this.typeResolver.config.maxAverageSchemaVersionsPerType;
+ const acceptedTypeCount =
+ versionsForType === 0 ? (versionsByType?.size ?? 0) + 1 : versionsByType!.size;
+ const maxAverageSchemaVersionsPerType =
+ this.typeResolver.config.maxAverageSchemaVersionsPerType;
const globalLimit = Math.max(
ReadContext.MIN_REMOTE_TYPE_META_LIMIT,
acceptedTypeCount * maxAverageSchemaVersionsPerType,
);
if (this.totalAcceptedSchemaVersions >= globalLimit) {
throw new Error(
- `Remote schema version limit exceeded: ${this.totalAcceptedSchemaVersions} `
- + `metadata versions for ${acceptedTypeCount} accepted remote types `
- + `exceeds the average limit ${maxAverageSchemaVersionsPerType}. `
- + "The data may be malicious. If the data is not malicious, please "
- + "increase maxAverageSchemaVersionsPerType.",
+ `Remote schema version limit exceeded: ${this.totalAcceptedSchemaVersions} ` +
+ `metadata versions for ${acceptedTypeCount} accepted remote types ` +
+ `exceeds the average limit ${maxAverageSchemaVersionsPerType}. ` +
+ "The data may be malicious. If the data is not malicious, please " +
+ "increase maxAverageSchemaVersionsPerType.",
);
}
return typeKey;
@@ -937,24 +883,15 @@ export class ReadContext {
private serializerByTypeMeta(typeMeta: TypeMeta) {
const typeId = typeMeta.getTypeId();
if (TypeId.isNamedType(typeId)) {
- return this.typeResolver.getSerializerByName(
- `${typeMeta.getNs()}$${typeMeta.getTypeName()}`,
- );
+ return this.typeResolver.getSerializerByName(`${typeMeta.getNs()}$${typeMeta.getTypeName()}`);
}
if (TypeId.needsUserTypeId(typeId)) {
- return this.typeResolver.getSerializerById(
- typeId,
- typeMeta.getUserTypeId(),
- );
+ return this.typeResolver.getSerializerById(typeId, typeMeta.getUserTypeId());
}
return this.typeResolver.getSerializerById(typeId);
}
- private matchesExactLocalTypeMeta(
- remoteTypeMeta: TypeMeta,
- start: number,
- end: number,
- ): boolean {
+ private matchesExactLocalTypeMeta(remoteTypeMeta: TypeMeta, start: number, end: number): boolean {
const serializer = this.serializerByTypeMeta(remoteTypeMeta);
const localBytes = serializer?.getTypeMetaBytes?.();
if (localBytes === undefined) {
@@ -1002,28 +939,23 @@ export class ReadContext {
if (remote === undefined || local === undefined) {
return false;
}
- if (
- this.canonicalTypeId(remote.typeId) !== this.canonicalFieldTypeId(local)
- ) {
+ if (this.canonicalTypeId(remote.typeId) !== this.canonicalFieldTypeId(local)) {
return false;
}
if (
- (remote.trackingRef === true) !== (local.trackingRef === true)
- || (remote.nullable === true) !== (local.nullable === true)
+ (remote.trackingRef === true) !== (local.trackingRef === true) ||
+ (remote.nullable === true) !== (local.nullable === true)
) {
return false;
}
switch (remote.typeId) {
case TypeId.MAP:
return (
- this.fieldSchemasEqual(remote.options?.key, local.options?.key)
- && this.fieldSchemasEqual(remote.options?.value, local.options?.value)
+ this.fieldSchemasEqual(remote.options?.key, local.options?.key) &&
+ this.fieldSchemasEqual(remote.options?.value, local.options?.value)
);
case TypeId.LIST:
- return this.fieldSchemasEqual(
- remote.options?.inner,
- local.options?.inner,
- );
+ return this.fieldSchemasEqual(remote.options?.inner, local.options?.inner);
case TypeId.SET:
return this.fieldSchemasEqual(remote.options?.key, local.options?.key);
default:
@@ -1040,62 +972,39 @@ export class ReadContext {
if (this.fieldSchemasEqual(fieldInfo, fallbackTypeInfo)) {
return fallbackTypeInfo.clone();
}
- const compatible = this.compatibleFieldTypeInfo(
- fieldInfo,
- fallbackTypeInfo,
- );
+ const compatible = this.compatibleFieldTypeInfo(fieldInfo, fallbackTypeInfo);
if (compatible) {
return compatible;
}
if (
- isCompatibleScalarType(fieldInfo.typeId)
- && isCompatibleScalarType(fallbackTypeInfo.typeId)
- && ((fieldInfo.trackingRef === true)
- !== (fallbackTypeInfo.trackingRef === true)
- || ((fieldInfo.trackingRef === true
- || fallbackTypeInfo.trackingRef === true)
- && (fieldInfo.typeId !== fallbackTypeInfo.typeId
- || fieldInfo.nullable !== fallbackTypeInfo.nullable)))
+ isCompatibleScalarType(fieldInfo.typeId) &&
+ isCompatibleScalarType(fallbackTypeInfo.typeId) &&
+ ((fieldInfo.trackingRef === true) !== (fallbackTypeInfo.trackingRef === true) ||
+ ((fieldInfo.trackingRef === true || fallbackTypeInfo.trackingRef === true) &&
+ (fieldInfo.typeId !== fallbackTypeInfo.typeId ||
+ fieldInfo.nullable !== fallbackTypeInfo.nullable)))
) {
- throw new Error(
- "unsupported compatible scalar tracking-ref schema mismatch",
- );
+ throw new Error("unsupported compatible scalar tracking-ref schema mismatch");
}
if (
- isCompatibleScalarPair(fieldInfo.typeId, fallbackTypeInfo.typeId)
- && fieldInfo.typeId !== fallbackTypeInfo.typeId
- && (fieldInfo.trackingRef === true
- || fallbackTypeInfo.trackingRef === true)
+ isCompatibleScalarPair(fieldInfo.typeId, fallbackTypeInfo.typeId) &&
+ fieldInfo.typeId !== fallbackTypeInfo.typeId &&
+ (fieldInfo.trackingRef === true || fallbackTypeInfo.trackingRef === true)
) {
- throw new Error(
- "unsupported compatible scalar tracking-ref schema mismatch",
- );
+ throw new Error("unsupported compatible scalar tracking-ref schema mismatch");
}
- if (
- this.hasUnsupportedListArrayMismatch(
- fieldInfo,
- fallbackTypeInfo,
- topLevel,
- )
- ) {
+ if (this.hasUnsupportedListArrayMismatch(fieldInfo, fallbackTypeInfo, topLevel)) {
throw new Error("unsupported compatible list/array schema mismatch");
}
if (
- fieldInfo.typeId !== TypeId.UNKNOWN
- && this.canonicalFieldTypeId(fallbackTypeInfo) !== TypeId.UNKNOWN
- && this.canonicalTypeId(fieldInfo.typeId)
- !== this.canonicalFieldTypeId(fallbackTypeInfo)
+ fieldInfo.typeId !== TypeId.UNKNOWN &&
+ this.canonicalFieldTypeId(fallbackTypeInfo) !== TypeId.UNKNOWN &&
+ this.canonicalTypeId(fieldInfo.typeId) !== this.canonicalFieldTypeId(fallbackTypeInfo)
) {
throw new Error("unsupported compatible field schema mismatch");
}
}
- if (
- this.hasUnsupportedListArrayMismatch(
- fieldInfo,
- fallbackTypeInfo,
- topLevel,
- )
- ) {
+ if (this.hasUnsupportedListArrayMismatch(fieldInfo, fallbackTypeInfo, topLevel)) {
throw new Error("unsupported compatible list/array schema mismatch");
}
if (this.hasNestedSchemaMismatch(fieldInfo, fallbackTypeInfo, topLevel)) {
@@ -1104,11 +1013,7 @@ export class ReadContext {
switch (fieldInfo.typeId) {
case TypeId.MAP:
return Type.map(
- this.fieldInfoToTypeInfo(
- fieldInfo.options!.key!,
- fallbackTypeInfo?.options?.key,
- false,
- ),
+ this.fieldInfoToTypeInfo(fieldInfo.options!.key!, fallbackTypeInfo?.options?.key, false),
this.fieldInfoToTypeInfo(
fieldInfo.options!.value!,
fallbackTypeInfo?.options?.value,
@@ -1125,11 +1030,7 @@ export class ReadContext {
);
case TypeId.SET:
return Type.set(
- this.fieldInfoToTypeInfo(
- fieldInfo.options!.key!,
- fallbackTypeInfo?.options?.key,
- false,
- ),
+ this.fieldInfoToTypeInfo(fieldInfo.options!.key!, fallbackTypeInfo?.options?.key, false),
);
default: {
// Remote TypeMeta only carries the nested user-defined type kind, not the
@@ -1174,53 +1075,37 @@ export class ReadContext {
return false;
}
if (
- this.schemaMatchTypeId(remote.typeId)
- !== this.schemaMatchTypeId(this.typeResolver.computeTypeId(local))
+ this.schemaMatchTypeId(remote.typeId) !==
+ this.schemaMatchTypeId(this.typeResolver.computeTypeId(local))
) {
return true;
}
const remoteTracksRef = remote.trackingRef === true;
const localTracksRef = local.trackingRef === true;
if (
- remoteTracksRef !== localTracksRef
- || ((remoteTracksRef || localTracksRef)
- && (remote.nullable === true) !== (local.nullable === true))
+ remoteTracksRef !== localTracksRef ||
+ ((remoteTracksRef || localTracksRef) &&
+ (remote.nullable === true) !== (local.nullable === true))
) {
return true;
}
switch (remote.typeId) {
case TypeId.MAP:
return (
- local.options?.key === undefined
- || local.options?.value === undefined
- || this.hasNestedSchemaMismatch(
- remote.options!.key!,
- local.options.key,
- false,
- )
- || this.hasNestedSchemaMismatch(
- remote.options!.value!,
- local.options.value,
- false,
- )
+ local.options?.key === undefined ||
+ local.options?.value === undefined ||
+ this.hasNestedSchemaMismatch(remote.options!.key!, local.options.key, false) ||
+ this.hasNestedSchemaMismatch(remote.options!.value!, local.options.value, false)
);
case TypeId.LIST:
return (
- local.options?.inner === undefined
- || this.hasNestedSchemaMismatch(
- remote.options!.inner!,
- local.options.inner,
- false,
- )
+ local.options?.inner === undefined ||
+ this.hasNestedSchemaMismatch(remote.options!.inner!, local.options.inner, false)
);
case TypeId.SET:
return (
- local.options?.key === undefined
- || this.hasNestedSchemaMismatch(
- remote.options!.key!,
- local.options.key,
- false,
- )
+ local.options?.key === undefined ||
+ this.hasNestedSchemaMismatch(remote.options!.key!, local.options.key, false)
);
default:
return false;
@@ -1231,25 +1116,22 @@ export class ReadContext {
return this.canonicalTypeId(typeId);
}
- private compatibleFieldTypeInfo(
- remote: InnerFieldInfo,
- local: TypeInfo,
- ): TypeInfo | undefined {
+ private compatibleFieldTypeInfo(remote: InnerFieldInfo, local: TypeInfo): TypeInfo | undefined {
if (this.isByteSequenceRootPair(remote, local)) {
if (
- (remote.nullable === true) !== (local.nullable === true)
- || (remote.trackingRef === true) !== (local.trackingRef === true)
+ (remote.nullable === true) !== (local.nullable === true) ||
+ (remote.trackingRef === true) !== (local.trackingRef === true)
) {
return undefined;
}
return local.clone();
}
if (
- this.isListArrayRootPair(remote, local)
- && (remote.nullable === true
- || local.nullable === true
- || remote.trackingRef === true
- || local.trackingRef === true)
+ this.isListArrayRootPair(remote, local) &&
+ (remote.nullable === true ||
+ local.nullable === true ||
+ remote.trackingRef === true ||
+ local.trackingRef === true)
) {
return undefined;
}
@@ -1269,22 +1151,20 @@ export class ReadContext {
}
const remoteArrayElement = denseArrayElementTypeId(remote.typeId);
if (
- remoteArrayElement !== undefined
- && local.typeId === TypeId.LIST
- && local.options?.inner
- && compatibleArrayElementTypeId(local.options.inner.typeId)
- === remoteArrayElement
+ remoteArrayElement !== undefined &&
+ local.typeId === TypeId.LIST &&
+ local.options?.inner &&
+ compatibleArrayElementTypeId(local.options.inner.typeId) === remoteArrayElement
) {
return compatibleArrayToListTypeInfo(remoteArrayElement);
}
if (
- remote.trackingRef !== true
- && local.trackingRef !== true
- && !(
- remote.typeId === local.typeId
- && (remote.nullable === true) === (local.nullable === true)
- )
- && isCompatibleScalarPair(remote.typeId, local.typeId)
+ remote.trackingRef !== true &&
+ local.trackingRef !== true &&
+ !(
+ remote.typeId === local.typeId && (remote.nullable === true) === (local.nullable === true)
+ ) &&
+ isCompatibleScalarPair(remote.typeId, local.typeId)
) {
return markCompatibleScalarRead(local.clone(), {
remoteTypeId: remote.typeId,
@@ -1312,16 +1192,8 @@ export class ReadContext {
switch (remote.typeId) {
case TypeId.MAP:
return (
- this.hasUnsupportedListArrayMismatch(
- remote.options!.key!,
- local.options?.key,
- false,
- )
- || this.hasUnsupportedListArrayMismatch(
- remote.options!.value!,
- local.options?.value,
- false,
- )
+ this.hasUnsupportedListArrayMismatch(remote.options!.key!, local.options?.key, false) ||
+ this.hasUnsupportedListArrayMismatch(remote.options!.value!, local.options?.value, false)
);
case TypeId.LIST:
return this.hasUnsupportedListArrayMismatch(
@@ -1340,26 +1212,17 @@ export class ReadContext {
}
}
- private isListArrayRootPair(
- remote: InnerFieldInfo,
- local: TypeInfo,
- ): boolean {
+ private isListArrayRootPair(remote: InnerFieldInfo, local: TypeInfo): boolean {
return (
- (remote.typeId === TypeId.LIST
- && denseArrayElementTypeId(local.typeId) !== undefined)
- || (denseArrayElementTypeId(remote.typeId) !== undefined
- && local.typeId === TypeId.LIST)
+ (remote.typeId === TypeId.LIST && denseArrayElementTypeId(local.typeId) !== undefined) ||
+ (denseArrayElementTypeId(remote.typeId) !== undefined && local.typeId === TypeId.LIST)
);
}
- private isByteSequenceRootPair(
- remote: InnerFieldInfo,
- local: TypeInfo,
- ): boolean {
+ private isByteSequenceRootPair(remote: InnerFieldInfo, local: TypeInfo): boolean {
return (
- (remote.typeId === TypeId.BINARY
- && local.typeId === TypeId.UINT8_ARRAY)
- || (remote.typeId === TypeId.UINT8_ARRAY && local.typeId === TypeId.BINARY)
+ (remote.typeId === TypeId.BINARY && local.typeId === TypeId.UINT8_ARRAY) ||
+ (remote.typeId === TypeId.UINT8_ARRAY && local.typeId === TypeId.BINARY)
);
}
@@ -1373,10 +1236,7 @@ export class ReadContext {
const named = `${typeMeta.getNs()}$${typeMeta.getTypeName()}`;
original = this.typeResolver.getSerializerByName(named);
} else {
- original = this.typeResolver.getSerializerById(
- typeId,
- typeMeta.getUserTypeId(),
- );
+ original = this.typeResolver.getSerializerById(typeId, typeMeta.getUserTypeId());
}
}
let typeInfo: TypeInfo;
@@ -1391,25 +1251,18 @@ export class ReadContext {
});
}
const localProps = original?.getTypeInfo().options?.props;
- const fieldEntries = typeMeta
- .remapFieldNames(localProps)
- .map((fieldInfo) => {
- const localFieldTypeInfo = localProps?.[fieldInfo.getFieldName()];
- let fieldTypeInfo = this.fieldInfoToTypeInfo(
- fieldInfo,
- localFieldTypeInfo,
- )
- .setNullable(fieldInfo.nullable)
- .setTrackingRef(fieldInfo.trackingRef)
- .setId(fieldInfo.fieldId);
- if (localFieldTypeInfo === undefined) {
- fieldTypeInfo = markCompatibleSkipRead(fieldTypeInfo);
- }
- return { key: fieldInfo.getFieldName(), typeInfo: fieldTypeInfo };
- });
- const props = Object.fromEntries(
- fieldEntries.map(({ key, typeInfo }) => [key, typeInfo]),
- );
+ const fieldEntries = typeMeta.remapFieldNames(localProps).map((fieldInfo) => {
+ const localFieldTypeInfo = localProps?.[fieldInfo.getFieldName()];
+ let fieldTypeInfo = this.fieldInfoToTypeInfo(fieldInfo, localFieldTypeInfo)
+ .setNullable(fieldInfo.nullable)
+ .setTrackingRef(fieldInfo.trackingRef)
+ .setId(fieldInfo.fieldId);
+ if (localFieldTypeInfo === undefined) {
+ fieldTypeInfo = markCompatibleSkipRead(fieldTypeInfo);
+ }
+ return { key: fieldInfo.getFieldName(), typeInfo: fieldTypeInfo };
+ });
+ const props = Object.fromEntries(fieldEntries.map(({ key, typeInfo }) => [key, typeInfo]));
typeInfo.options = {
...typeInfo.options,
preserveFieldOrder: true,
diff --git a/javascript/packages/core/lib/fory.ts b/javascript/packages/core/lib/fory.ts
index 05b424b1c..f50d2fceb 100644
--- a/javascript/packages/core/lib/fory.ts
+++ b/javascript/packages/core/lib/fory.ts
@@ -44,23 +44,15 @@ export default class Fory {
readonly config: Config;
readonly writeContext: WriteContext;
readonly readContext: ReadContext;
- private readonly rootSerializers = new WeakMap<
- Serializer,
- (data: any) => PlatformBuffer
- >();
+ private readonly rootSerializers = new WeakMap<Serializer, (data: any) => PlatformBuffer>();
- private readonly rootDeserializers = new WeakMap<
- Serializer,
- (bytes: Uint8Array) => any
- >();
+ private readonly rootDeserializers = new WeakMap<Serializer, (bytes: Uint8Array) => any>();
constructor(config?: Partial<Config>) {
this.config = this.initConfig(config);
const maxDepth = this.config.maxDepth ?? DEFAULT_DEPTH_LIMIT;
if (!Number.isInteger(maxDepth) || maxDepth < MIN_DEPTH_LIMIT) {
- throw new Error(
- `maxDepth must be an integer >= ${MIN_DEPTH_LIMIT} but got ${maxDepth}`,
- );
+ throw new Error(`maxDepth must be an integer >= ${MIN_DEPTH_LIMIT} but got ${maxDepth}`);
}
this.typeResolver = new TypeResolver(this.config);
this.writeContext = new WriteContext(this.typeResolver, this.config);
@@ -73,33 +65,24 @@ export default class Fory {
private initConfig(config: Partial<Config> | undefined) {
const maxTypeFields = config?.maxTypeFields ?? DEFAULT_MAX_TYPE_FIELDS;
if (!Number.isInteger(maxTypeFields) || maxTypeFields <= 0) {
- throw new Error(
- `maxTypeFields must be a positive integer but got ${maxTypeFields}`,
- );
+ throw new Error(`maxTypeFields must be a positive integer but got ${maxTypeFields}`);
}
- const maxTypeMetaBytes
- = config?.maxTypeMetaBytes ?? DEFAULT_MAX_TYPE_META_BYTES;
+ const maxTypeMetaBytes = config?.maxTypeMetaBytes ?? DEFAULT_MAX_TYPE_META_BYTES;
if (!Number.isInteger(maxTypeMetaBytes) || maxTypeMetaBytes <= 0) {
- throw new Error(
- `maxTypeMetaBytes must be a positive integer but got ${maxTypeMetaBytes}`,
- );
+ throw new Error(`maxTypeMetaBytes must be a positive integer but got ${maxTypeMetaBytes}`);
}
- const maxSchemaVersionsPerType
- = config?.maxSchemaVersionsPerType ?? DEFAULT_MAX_SCHEMA_VERSIONS_PER_TYPE;
- if (
- !Number.isInteger(maxSchemaVersionsPerType)
- || maxSchemaVersionsPerType <= 0
- ) {
+ const maxSchemaVersionsPerType =
+ config?.maxSchemaVersionsPerType ?? DEFAULT_MAX_SCHEMA_VERSIONS_PER_TYPE;
+ if (!Number.isInteger(maxSchemaVersionsPerType) || maxSchemaVersionsPerType <= 0) {
throw new Error(
`maxSchemaVersionsPerType must be a positive integer but got ${maxSchemaVersionsPerType}`,
);
}
- const maxAverageSchemaVersionsPerType
- = config?.maxAverageSchemaVersionsPerType
- ?? DEFAULT_MAX_AVERAGE_SCHEMA_VERSIONS_PER_TYPE;
+ const maxAverageSchemaVersionsPerType =
+ config?.maxAverageSchemaVersionsPerType ?? DEFAULT_MAX_AVERAGE_SCHEMA_VERSIONS_PER_TYPE;
if (
- !Number.isInteger(maxAverageSchemaVersionsPerType)
- || maxAverageSchemaVersionsPerType <= 0
+ !Number.isInteger(maxAverageSchemaVersionsPerType) ||
+ maxAverageSchemaVersionsPerType <= 0
) {
throw new Error(
`maxAverageSchemaVersionsPerType must be a positive integer but got ${maxAverageSchemaVersionsPerType}`,
@@ -144,9 +127,8 @@ export default class Fory {
register(constructor: any, customSerializer?: CustomSerializer<any>) {
let serializer: Serializer;
if (constructor.prototype?.[ForyTypeInfoSymbol]) {
- const typeInfo: TypeInfo = (
- constructor.prototype[ForyTypeInfoSymbol] as WithForyClsInfo
- ).structTypeInfo;
+ const typeInfo: TypeInfo = (constructor.prototype[ForyTypeInfoSymbol] as WithForyClsInfo)
+ .structTypeInfo;
typeInfo.freeze();
serializer = new Gen(this.typeResolver, {
creator: constructor,
@@ -168,10 +150,7 @@ export default class Fory {
};
}
- deserialize<T = any>(
- bytes: Uint8Array,
- serializer: Serializer = this.anySerializer,
- ): T | null {
+ deserialize<T = any>(bytes: Uint8Array, serializer: Serializer = this.anySerializer): T | null {
this.readContext.reset(bytes);
const reader = this.readContext.reader;
const bitmap = reader.readUint8();
@@ -182,12 +161,9 @@ export default class Fory {
}
private throwInvalidRootHeader(bitmap: number): never {
- const knownFlags
- = ConfigFlags.isCrossLanguageFlag | ConfigFlags.isOutOfBandFlag;
+ const knownFlags = ConfigFlags.isCrossLanguageFlag | ConfigFlags.isOutOfBandFlag;
if ((bitmap & ~knownFlags) !== 0) {
- throw new Error(
- `unsupported root header bitmap 0x${bitmap.toString(16)}`,
- );
+ throw new Error(`unsupported root header bitmap 0x${bitmap.toString(16)}`);
}
if ((bitmap & ConfigFlags.isCrossLanguageFlag) === 0) {
throw new Error("support crosslanguage mode only");
diff --git a/javascript/packages/core/lib/gen/builder.ts b/javascript/packages/core/lib/gen/builder.ts
index 6b88f22e1..128ecf90d 100644
--- a/javascript/packages/core/lib/gen/builder.ts
+++ b/javascript/packages/core/lib/gen/builder.ts
@@ -21,8 +21,7 @@ import { Scope } from "./scope";
import TypeResolver from "../typeResolver";
export class BinaryReaderBuilder {
- constructor(private holder: string) {
- }
+ constructor(private holder: string) {}
ownName() {
return this.holder;
@@ -154,8 +153,7 @@ export class BinaryReaderBuilder {
}
class BinaryWriterBuilder {
- constructor(private holder: string) {
- }
+ constructor(private holder: string) {}
ownName() {
return this.holder;
@@ -307,8 +305,10 @@ class BinaryWriterBuilder {
}
class ReferenceResolverBuilder {
- constructor(private readHolder: string, private writeHolder: string) {
- }
+ constructor(
+ private readHolder: string,
+ private writeHolder: string,
+ ) {}
ownReadName() {
return this.readHolder;
@@ -340,8 +340,7 @@ class ReferenceResolverBuilder {
}
class TypeResolverBuilder {
- constructor(private holder: string) {
- }
+ constructor(private holder: string) {}
ownName() {
return this.holder;
@@ -364,8 +363,10 @@ class TypeResolverBuilder {
}
class TypeMetaContextBuilder {
- constructor(private writeHolder: string, private readHolder: string) {
- }
+ constructor(
+ private writeHolder: string,
+ private readHolder: string,
+ ) {}
writeTypeMeta(typeInfo: string, bytes: string) {
return `${this.writeHolder}.writeTypeMeta(${typeInfo}, ${bytes})`;
@@ -401,8 +402,7 @@ class MetaStringContextBuilder {
private writeContextHolder: string,
private readContextHolder: string,
private writeHelperHolder: string,
- ) {
- }
+ ) {}
writeBytes(bytes: string) {
return `${this.writeContextHolder}.writeMetaStringBytes(${bytes})`;
@@ -433,7 +433,10 @@ export class CodecBuilder {
readonly typeMetaResolver: TypeMetaContextBuilder;
readonly metaStringResolver: MetaStringContextBuilder;
- constructor(scope: Scope, readonly resolver: TypeResolver) {
+ constructor(
+ scope: Scope,
+ readonly resolver: TypeResolver,
+ ) {
const writeContext = scope.declareByName("writeContext", "typeResolver.writeContext");
const readContext = scope.declareByName("readContext", "typeResolver.readContext");
const br = scope.declareByName("br", "readContext.reader");
@@ -452,7 +455,9 @@ export class CodecBuilder {
}
static isReserved(key: string) {
- return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(key);
+ return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(
+ key,
+ );
}
static isDotPropAccessor(prop: string) {
@@ -460,7 +465,7 @@ export class CodecBuilder {
}
static replaceBackslashAndQuote(v: string) {
- return v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
+ return v.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
static safeString(target: string) {
diff --git a/javascript/packages/core/lib/gen/collection.ts b/javascript/packages/core/lib/gen/collection.ts
index 74344fc00..03139bebb 100644
--- a/javascript/packages/core/lib/gen/collection.ts
+++ b/javascript/packages/core/lib/gen/collection.ts
@@ -64,10 +64,7 @@ export const CollectionFlags = {
SAME_TYPE: 0b1000,
};
-function compatibleArrayCollectionExpr(
- elementTypeId: number,
- len: string,
-): string {
+function compatibleArrayCollectionExpr(elementTypeId: number, len: string): string {
switch (elementTypeId) {
case TypeId.BOOL:
return `new external.BoolArray(${len})`;
@@ -150,11 +147,7 @@ class CollectionAnySerializer {
trackingRef = current.needToWriteRef();
}
if (isSame) {
- if (
- serializer !== null
- && serializer !== undefined
- && current !== serializer
- ) {
+ if (serializer !== null && serializer !== undefined && current !== serializer) {
isSame = false;
} else {
serializer = current;
@@ -186,8 +179,7 @@ class CollectionAnySerializer {
if (size === 0) {
return;
}
- const { serializer, isSame, includeNone, trackingRef }
- = this.writeElementsHeader(value);
+ const { serializer, isSame, includeNone, trackingRef } = this.writeElementsHeader(value);
if (isSame) {
serializer!.writeTypeInfo(value);
if (trackingRef) {
@@ -213,8 +205,7 @@ class CollectionAnySerializer {
} else {
if (trackingRef) {
for (const item of value) {
- const serializer
- = this.writeContext.typeResolver.getSerializerByData(item);
+ const serializer = this.writeContext.typeResolver.getSerializerByData(item);
serializer?.writeRef(item);
}
} else if (includeNone) {
@@ -222,16 +213,14 @@ class CollectionAnySerializer {
if (item === null || item === undefined) {
this.writeContext.writer.writeInt8(RefFlags.NullFlag);
} else {
- const serializer
- = this.writeContext.typeResolver.getSerializerByData(item);
+ const serializer = this.writeContext.typeResolver.getSerializerByData(item);
this.writeContext.writer.writeInt8(RefFlags.NotNullValueFlag);
serializer!.writeNoRef(item);
}
}
} else {
for (const item of value) {
- const serializer
- = this.writeContext.typeResolver.getSerializerByData(item);
+ const serializer = this.writeContext.typeResolver.getSerializerByData(item);
serializer!.writeNoRef(item);
}
}
@@ -268,11 +257,7 @@ class CollectionAnySerializer {
const refId = this.readContext.reader.readVarUInt32();
accessor(result, i, this.readContext.getReadRef(refId));
} else if (refFlag === RefFlags.RefValueFlag) {
- accessor(
- result,
- i,
- this.readSerializerWithDepth(serializer!, true),
- );
+ accessor(result, i, this.readSerializerWithDepth(serializer!, true));
} else {
accessor(result, i, null);
}
@@ -283,11 +268,7 @@ class CollectionAnySerializer {
if (flag === RefFlags.NullFlag) {
accessor(result, i, null);
} else {
- accessor(
- result,
- i,
- this.readSerializerWithDepth(serializer!, false),
- );
+ accessor(result, i, this.readSerializerWithDepth(serializer!, false));
}
}
} else {
@@ -308,21 +289,13 @@ class CollectionAnySerializer {
accessor(result, i, null);
} else {
const itemSerializer = AnyHelper.detectSerializer(this.readContext);
- accessor(
- result,
- i,
- this.readSerializerWithDepth(itemSerializer!, false),
- );
+ accessor(result, i, this.readSerializerWithDepth(itemSerializer!, false));
}
}
} else {
for (let i = 0; i < len; i++) {
const itemSerializer = AnyHelper.detectSerializer(this.readContext);
- accessor(
- result,
- i,
- this.readSerializerWithDepth(itemSerializer!, false),
- );
+ accessor(result, i, this.readSerializerWithDepth(itemSerializer!, false));
}
}
}
@@ -338,11 +311,7 @@ export abstract class CollectionSerializerGenerator extends BaseSerializerGenera
super(typeInfo, builder, scope);
this.typeInfo = typeInfo;
const inner = this.genericTypeDescriptin()!;
- this.innerGenerator = CodegenRegistry.newGeneratorByTypeInfo(
- inner,
- this.builder,
- this.scope,
- );
+ this.innerGenerator = CodegenRegistry.newGeneratorByTypeInfo(inner, this.builder, this.scope);
}
abstract genericTypeDescriptin(): TypeInfo | undefined;
@@ -360,12 +329,12 @@ export abstract class CollectionSerializerGenerator extends BaseSerializerGenera
private isDeclaredElementType() {
const innerTypeId = this.innerGenerator.getTypeId();
return (
- innerTypeId !== TypeId.STRUCT
- && innerTypeId !== TypeId.COMPATIBLE_STRUCT
- && innerTypeId !== TypeId.NAMED_STRUCT
- && innerTypeId !== TypeId.NAMED_COMPATIBLE_STRUCT
- && innerTypeId !== TypeId.EXT
- && innerTypeId !== TypeId.NAMED_EXT
+ innerTypeId !== TypeId.STRUCT &&
+ innerTypeId !== TypeId.COMPATIBLE_STRUCT &&
+ innerTypeId !== TypeId.NAMED_STRUCT &&
+ innerTypeId !== TypeId.NAMED_COMPATIBLE_STRUCT &&
+ innerTypeId !== TypeId.EXT &&
+ innerTypeId !== TypeId.NAMED_EXT
);
}
@@ -434,10 +403,7 @@ export abstract class CollectionSerializerGenerator extends BaseSerializerGenera
`;
}
- readSpecificType(
- accessor: (expr: string) => string,
- refState: string,
- ): string {
+ readSpecificType(accessor: (expr: string) => string, refState: string): string {
const result = this.scope.uniqueName("result");
const len = this.scope.uniqueName("len");
const flags = this.scope.uniqueName("flags");
@@ -446,24 +412,15 @@ export abstract class CollectionSerializerGenerator extends BaseSerializerGenera
const elemSerializer = this.scope.uniqueName("elemSerializer");
const anyHelper = this.builder.getExternal(AnyHelper.name);
const readContextName = this.builder.getReadContextName();
- const useDeclaredStructElementReader = TypeId.structType(
- this.innerGenerator.getTypeId()!,
- );
- const compatibleReadAction = getCompatibleCollectionArrayReadAction(
- this.typeInfo,
- );
+ const useDeclaredStructElementReader = TypeId.structType(this.innerGenerator.getTypeId()!);
+ const compatibleReadAction = getCompatibleCollectionArrayReadAction(this.typeInfo);
const compatibleListToArray = compatibleReadAction?.target === "array";
const newCollection = compatibleListToArray
? compatibleArrayCollectionExpr(compatibleReadAction!.elementTypeId, len)
: this.newCollection(len);
const putAccessor = (item: string, index: string) =>
compatibleListToArray
- ? compatibleArrayPutAccessor(
- compatibleReadAction!.elementTypeId,
- result,
- item,
- index,
- )
+ ? compatibleArrayPutAccessor(compatibleReadAction!.elementTypeId, result, item, index)
: this.putAccessor(result, item, index);
const rejectCompatiblePayload = compatibleListToArray
? `
@@ -480,18 +437,15 @@ export abstract class CollectionSerializerGenerator extends BaseSerializerGenera
const innerReader = useDeclaredStructElementReader
? this.innerGenerator.readEmbed()
: this.innerGenerator;
- const readInnerElement = (
- assignStmt: (x: any) => string,
- refState: string,
- ) => {
+ const readInnerElement = (assignStmt: (x: any) => string, refState: string) => {
return innerIsLeaf
? this.innerGenerator.read(assignStmt, refState)
: innerReader.readWithDepth(assignStmt, refState);
};
const readElementTypeInfo = useDeclaredStructElementReader
? this.innerGenerator
- .readEmbed()
- .readTypeInfo((expr: string) => `${elemSerializer} = ${expr};`)
+ .readEmbed()
+ .readTypeInfo((expr: string) => `${elemSerializer} = ${expr};`)
: `${elemSerializer} = ${anyHelper}.detectSerializer(${readContextName});`;
return `
const ${len} = ${this.builder.reader.readVarUint32Small7()};
diff --git a/javascript/packages/core/lib/gen/datetime.ts b/javascript/packages/core/lib/gen/datetime.ts
index fe6b8972b..98b3c83bd 100644
--- a/javascript/packages/core/lib/gen/datetime.ts
+++ b/javascript/packages/core/lib/gen/datetime.ts
@@ -109,7 +109,9 @@ class DateSerializerGenerator extends BaseSerializerGenerator {
read(accessor: (expr: string) => string): string {
const epoch = this.scope.declareByName("epoch", `new Date("1970/01/01 00:00").getTime()`);
- return accessor(`new Date(${epoch} + (Number(${this.builder.reader.readVarInt64()}) * (24 * 60 * 60) * 1000))`);
+ return accessor(
+ `new Date(${epoch} + (Number(${this.builder.reader.readVarInt64()}) * (24 * 60 * 60) * 1000))`,
+ );
}
getFixedSize(): number {
diff --git a/javascript/packages/core/lib/gen/enum.ts b/javascript/packages/core/lib/gen/enum.ts
index b0f0cb320..f67715195 100644
--- a/javascript/packages/core/lib/gen/enum.ts
+++ b/javascript/packages/core/lib/gen/enum.ts
@@ -70,21 +70,23 @@ class EnumSerializerGenerator extends BaseSerializerGenerator {
const enumEntries = this.getEnumEntries();
const useExplicitNumericWireValues = this.useExplicitNumericWireValues(enumEntries);
return `
- ${enumEntries.map(([, value], index) => {
- if (typeof value !== "string" && typeof value !== "number") {
- throw new Error("Enum value must be string or number");
- }
- if (typeof value === "number") {
- if (value > MaxUInt32 || value < 0) {
- throw new Error("Enum value must be a valid uint32");
- }
- }
- const safeValue = typeof value === "string" ? `"${value}"` : value;
- const wireValue = useExplicitNumericWireValues ? safeValue : index;
- return ` if (${accessor} === ${safeValue}) {
+ ${enumEntries
+ .map(([, value], index) => {
+ if (typeof value !== "string" && typeof value !== "number") {
+ throw new Error("Enum value must be string or number");
+ }
+ if (typeof value === "number") {
+ if (value > MaxUInt32 || value < 0) {
+ throw new Error("Enum value must be a valid uint32");
+ }
+ }
+ const safeValue = typeof value === "string" ? `"${value}"` : value;
+ const wireValue = useExplicitNumericWireValues ? safeValue : index;
+ return ` if (${accessor} === ${safeValue}) {
${this.builder.writer.writeVarUInt32(wireValue)}
}`;
- }).join(" else ")}
+ })
+ .join(" else ")}
else {
throw new Error("Enum received an unexpected value: " + ${accessor});
}
@@ -116,8 +118,8 @@ class EnumSerializerGenerator extends BaseSerializerGenerator {
}
${
- // skip the type name
- this.builder.metaStringResolver.readTypeName()
+ // skip the type name
+ this.builder.metaStringResolver.readTypeName()
}
`;
}
@@ -127,8 +129,8 @@ class EnumSerializerGenerator extends BaseSerializerGenerator {
}
return `
${
- // skip the typeId
- this.builder.reader.readUint8()
+ // skip the typeId
+ this.builder.reader.readUint8()
}
${readUserTypeIdStmt}
${namesStmt}
@@ -145,12 +147,25 @@ class EnumSerializerGenerator extends BaseSerializerGenerator {
break;
case TypeId.NAMED_ENUM:
if (this.builder.resolver.isCompatible()) {
- const bytes = this.scope.declare("enumTypeInfoBytes", `new Uint8Array([${TypeMeta.fromTypeInfo(this.typeInfo, this.builder.resolver).toBytes().join(",")}])`);
+ const bytes = this.scope.declare(
+ "enumTypeInfoBytes",
+ `new Uint8Array([${TypeMeta.fromTypeInfo(this.typeInfo, this.builder.resolver).toBytes().join(",")}])`,
+ );
typeMeta = this.builder.typeMetaResolver.writeTypeMeta(this.builder.getTypeInfo(), bytes);
} else {
const typeInfo = this.typeInfo;
- const nsBytes = this.scope.declare("nsBytes", this.builder.metaStringResolver.encodeNamespace(CodecBuilder.replaceBackslashAndQuote(typeInfo.namespace)));
- const typeNameBytes = this.scope.declare("typeNameBytes", this.builder.metaStringResolver.encodeTypeName(CodecBuilder.replaceBackslashAndQuote(typeInfo.typeName)));
+ const nsBytes = this.scope.declare(
+ "nsBytes",
+ this.builder.metaStringResolver.encodeNamespace(
+ CodecBuilder.replaceBackslashAndQuote(typeInfo.namespace),
+ ),
+ );
+ const typeNameBytes = this.scope.declare(
+ "typeNameBytes",
+ this.builder.metaStringResolver.encodeTypeName(
+ CodecBuilder.replaceBackslashAndQuote(typeInfo.typeName),
+ ),
+ );
typeMeta = `
${this.builder.metaStringResolver.writeBytes(nsBytes)}
${this.builder.metaStringResolver.writeBytes(typeNameBytes)}
@@ -177,23 +192,25 @@ class EnumSerializerGenerator extends BaseSerializerGenerator {
return `
const ${enumValue} = ${this.builder.reader.readVarUInt32()};
switch(${enumValue}) {
- ${enumEntries.map(([, value], index) => {
- if (typeof value !== "string" && typeof value !== "number") {
- throw new Error("Enum value must be string or number");
- }
- if (typeof value === "number") {
- if (value > MaxUInt32 || value < 0) {
- throw new Error("Enum value must be a valid uint32");
- }
- }
- const safeValue = typeof value === "string" ? `"${value}"` : `${value}`;
- const wireValue = useExplicitNumericWireValues ? safeValue : `${index}`;
- return `
+ ${enumEntries
+ .map(([, value], index) => {
+ if (typeof value !== "string" && typeof value !== "number") {
+ throw new Error("Enum value must be string or number");
+ }
+ if (typeof value === "number") {
+ if (value > MaxUInt32 || value < 0) {
+ throw new Error("Enum value must be a valid uint32");
+ }
+ }
+ const safeValue = typeof value === "string" ? `"${value}"` : `${value}`;
+ const wireValue = useExplicitNumericWireValues ? safeValue : `${index}`;
+ return `
case ${wireValue}:
${accessor(safeValue)}
break;
`;
- }).join("\n")}
+ })
+ .join("\n")}
default:
throw new Error("Enum received an unexpected value: " + ${enumValue});
}
diff --git a/javascript/packages/core/lib/gen/ext.ts b/javascript/packages/core/lib/gen/ext.ts
index 704495edf..5d8af562a 100644
--- a/javascript/packages/core/lib/gen/ext.ts
+++ b/javascript/packages/core/lib/gen/ext.ts
@@ -50,19 +50,18 @@ class ExtSerializerGenerator extends BaseSerializerGenerator {
read(accessor: (expr: string) => string, refState: string): string {
const result = this.scope.uniqueName("result");
return `
- ${this.typeInfo.options!.withConstructor
- ? `
+ ${
+ this.typeInfo.options!.withConstructor
+ ? `
const ${result} = new ${this.builder.getOptions("creator")}();
`
- : `
+ : `
const ${result} = {};
`
}
${this.maybeReference(result, refState)}
${this.builder.getOptions("customSerializer")}.read(${this.builder.getReadContextName()}, ${result})
- ${
- accessor(result)
- }
+ ${accessor(result)}
`;
}
@@ -72,7 +71,7 @@ class ExtSerializerGenerator extends BaseSerializerGenerator {
${this.readTypeInfo()}
${this.builder.getReadContextName()}.incReadDepth();
let ${result};
- ${this.read(v => `${result} = ${v}`, refState)};
+ ${this.read((v) => `${result} = ${v}`, refState)};
${this.builder.getReadContextName()}.decReadDepth();
${assignStmt(result)};
`;
@@ -90,12 +89,8 @@ class ExtSerializerGenerator extends BaseSerializerGenerator {
case TypeId.NAMED_EXT:
if (!this.builder.resolver.isCompatible()) {
namesStmt = `
- ${
- this.builder.metaStringResolver.readNamespace()
- };
- ${
- this.builder.metaStringResolver.readTypeName()
- };
+ ${this.builder.metaStringResolver.readNamespace()};
+ ${this.builder.metaStringResolver.readTypeName()};
`;
} else {
typeMetaStmt = `
@@ -109,49 +104,59 @@ class ExtSerializerGenerator extends BaseSerializerGenerator {
break;
}
return `
- ${
- this.builder.reader.readUint8()
- };
+ ${this.builder.reader.readUint8()};
${readUserTypeIdStmt}
- ${
- namesStmt
- }
- ${
- typeMetaStmt
- }
+ ${namesStmt}
+ ${typeMetaStmt}
`;
}
readEmbed() {
- return new Proxy({}, {
- get: (target, prop: string) => {
- return (accessor: (expr: string) => string, ...args: string[]) => {
- const name = this.scope.declare(
- "ext_ser",
- TypeId.isNamedType(this.typeInfo.typeId)
- ? this.builder.typeResolver.getSerializerByName(CodecBuilder.replaceBackslashAndQuote(this.typeInfo.named!))
- : this.builder.typeResolver.getSerializerById(this.typeInfo.typeId, this.typeInfo.userTypeId)
- );
- return accessor(`${name}.${prop}(${args.join(",")})`);
- };
+ return new Proxy(
+ {},
+ {
+ get: (target, prop: string) => {
+ return (accessor: (expr: string) => string, ...args: string[]) => {
+ const name = this.scope.declare(
+ "ext_ser",
+ TypeId.isNamedType(this.typeInfo.typeId)
+ ? this.builder.typeResolver.getSerializerByName(
+ CodecBuilder.replaceBackslashAndQuote(this.typeInfo.named!),
+ )
+ : this.builder.typeResolver.getSerializerById(
+ this.typeInfo.typeId,
+ this.typeInfo.userTypeId,
+ ),
+ );
+ return accessor(`${name}.${prop}(${args.join(",")})`);
+ };
+ },
},
- });
+ );
}
writeEmbed() {
- return new Proxy({}, {
- get: (target, prop: string) => {
- return (accessor: string) => {
- const name = this.scope.declare(
- "ext_ser",
- TypeId.isNamedType(this.typeInfo.typeId)
- ? this.builder.typeResolver.getSerializerByName(CodecBuilder.replaceBackslashAndQuote(this.typeInfo.named!))
- : this.builder.typeResolver.getSerializerById(this.typeInfo.typeId, this.typeInfo.userTypeId)
- );
- return `${name}.${prop}(${accessor})`;
- };
+ return new Proxy(
+ {},
+ {
+ get: (target, prop: string) => {
+ return (accessor: string) => {
+ const name = this.scope.declare(
+ "ext_ser",
+ TypeId.isNamedType(this.typeInfo.typeId)
+ ? this.builder.typeResolver.getSerializerByName(
+ CodecBuilder.replaceBackslashAndQuote(this.typeInfo.named!),
+ )
+ : this.builder.typeResolver.getSerializerById(
+ this.typeInfo.typeId,
+ this.typeInfo.userTypeId,
+ ),
+ );
+ return `${name}.${prop}(${accessor})`;
+ };
+ },
},
- });
+ );
}
writeTypeInfo(): string {
@@ -165,14 +170,27 @@ class ExtSerializerGenerator extends BaseSerializerGenerator {
case TypeId.NAMED_EXT:
if (!this.builder.resolver.isCompatible()) {
const typeInfo = this.typeInfo;
- const nsBytes = this.scope.declare("nsBytes", this.builder.metaStringResolver.encodeNamespace(CodecBuilder.replaceBackslashAndQuote(typeInfo.namespace)));
- const typeNameBytes = this.scope.declare("typeNameBytes", this.builder.metaStringResolver.encodeTypeName(CodecBuilder.replaceBackslashAndQuote(typeInfo.typeName)));
+ const nsBytes = this.scope.declare(
+ "nsBytes",
+ this.builder.metaStringResolver.encodeNamespace(
+ CodecBuilder.replaceBackslashAndQuote(typeInfo.namespace),
+ ),
+ );
+ const typeNameBytes = this.scope.declare(
+ "typeNameBytes",
+ this.builder.metaStringResolver.encodeTypeName(
+ CodecBuilder.replaceBackslashAndQuote(typeInfo.typeName),
+ ),
+ );
typeMeta = `
${this.builder.metaStringResolver.writeBytes(nsBytes)}
${this.builder.metaStringResolver.writeBytes(typeNameBytes)}
`;
} else {
- const bytes = this.scope.declare("typeInfoBytes", `new Uint8Array([${TypeMeta.fromTypeInfo(this.typeInfo, this.builder.resolver).toBytes().join(",")}])`);
+ const bytes = this.scope.declare(
+ "typeInfoBytes",
+ `new Uint8Array([${TypeMeta.fromTypeInfo(this.typeInfo, this.builder.resolver).toBytes().join(",")}])`,
+ );
typeMeta = this.builder.typeMetaResolver.writeTypeMeta(this.builder.getTypeInfo(), bytes);
}
break;
diff --git a/javascript/packages/core/lib/gen/index.ts b/javascript/packages/core/lib/gen/index.ts
index aa42501d9..d3479dd0d 100644
--- a/javascript/packages/core/lib/gen/index.ts
+++ b/javascript/packages/core/lib/gen/index.ts
@@ -45,9 +45,10 @@ CodegenRegistry.registerExternal(CompatibleScalarConverter);
export class Gen {
static external = CodegenRegistry.getExternal();
- constructor(private typeResolver: TypeResolver, private regOptions: { [key: string]: any } = {}) {
-
- }
+ constructor(
+ private typeResolver: TypeResolver,
+ private regOptions: { [key: string]: any } = {},
+ ) {}
private generate(typeInfo: TypeInfo) {
const InnerGeneratorClass = CodegenRegistry.get(typeInfo.typeId);
@@ -55,7 +56,11 @@ export class Gen {
throw new Error(`${typeInfo.typeId} generator not exists`);
}
const scope = new Scope();
- const generator = new InnerGeneratorClass(typeInfo, new CodecBuilder(scope, this.typeResolver), scope);
+ const generator = new InnerGeneratorClass(
+ typeInfo,
+ new CodecBuilder(scope, this.typeResolver),
+ scope,
+ );
const funcString = generator.toSerializer();
if (this.typeResolver.config && this.typeResolver.config.hooks) {
@@ -85,10 +90,11 @@ export class Gen {
if (this.isFullyGenerated(typeInfo)) {
return;
}
- const options = (typeInfo).options;
- const unionType = typeInfo.typeId === TypeId.UNION
- || typeInfo.typeId === TypeId.TYPED_UNION
- || typeInfo.typeId === TypeId.NAMED_UNION;
+ const options = typeInfo.options;
+ const unionType =
+ typeInfo.typeId === TypeId.UNION ||
+ typeInfo.typeId === TypeId.TYPED_UNION ||
+ typeInfo.typeId === TypeId.NAMED_UNION;
if (unionType && options?.cases && Object.keys(options.cases).length > 0) {
this.register(typeInfo);
Object.values(options.cases).forEach((x) => {
@@ -119,14 +125,14 @@ export class Gen {
this.traversalContainer(typeInfo.options!.inner!);
}
if (typeInfo.typeId === TypeId.SET) {
- this.traversalContainer((typeInfo).options!.key!);
+ this.traversalContainer(typeInfo.options!.key!);
}
if (typeInfo.typeId === TypeId.MAP) {
if (!typeInfo.options?.key || !typeInfo.options?.value) {
throw new Error("map type must have key and value");
}
- this.traversalContainer((typeInfo).options!.key!);
- this.traversalContainer((typeInfo).options!.value!);
+ this.traversalContainer(typeInfo.options!.key!);
+ this.traversalContainer(typeInfo.options!.value!);
}
if (typeInfo.options?.cases) {
Object.values(typeInfo.options.cases).forEach((caseTypeInfo) => {
diff --git a/javascript/packages/core/lib/gen/map.ts b/javascript/packages/core/lib/gen/map.ts
index c447691d4..db0e147a4 100644
--- a/javascript/packages/core/lib/gen/map.ts
+++ b/javascript/packages/core/lib/gen/map.ts
@@ -49,9 +49,9 @@ class ElementInfo {
return false;
}
return (
- this.serializer === other.serializer
- && this.isNull === other.isNull
- && this.trackRef === other.trackRef
+ this.serializer === other.serializer &&
+ this.isNull === other.isNull &&
+ this.trackRef === other.trackRef
);
}
}
@@ -94,11 +94,7 @@ class MapChunkWriter {
return flag;
}
- private writeHead(
- keyInfo: ElementInfo,
- valueInfo: ElementInfo,
- withOutSize = false,
- ) {
+ private writeHead(keyInfo: ElementInfo, valueInfo: ElementInfo, withOutSize = false) {
// KV header
const header = this.getHead(keyInfo, valueInfo);
// chunkSize default 0 | KV header
@@ -128,10 +124,10 @@ class MapChunkWriter {
}
// max size of chunk is 255
if (
- this.chunkSize == 255
- || this.chunkOffset == 0
- || !keyInfo.equalTo(this.preKeyInfo)
- || !valueInfo.equalTo(this.preValueInfo)
+ this.chunkSize == 255 ||
+ this.chunkOffset == 0 ||
+ !keyInfo.equalTo(this.preKeyInfo) ||
+ !valueInfo.equalTo(this.preValueInfo)
) {
// new chunk
this.endChunk();
@@ -146,10 +142,7 @@ class MapChunkWriter {
endChunk() {
if (this.chunkOffset > 0) {
- this.writeContext.writer.setUint8Position(
- this.chunkOffset,
- this.chunkSize,
- );
+ this.writeContext.writer.setUint8Position(this.chunkOffset, this.chunkSize);
this.chunkSize = 0;
}
}
@@ -196,21 +189,17 @@ class MapAnySerializer {
);
this.writeContext.writer.writeVarUint32Small7(value.size);
for (const [k, v] of value.entries()) {
- const keySerializer
- = this.keySerializer !== null
+ const keySerializer =
+ this.keySerializer !== null
? this.keySerializer
: this.writeContext.typeResolver.getSerializerByData(k);
- const valueSerializer
- = this.valueSerializer !== null
+ const valueSerializer =
+ this.valueSerializer !== null
? this.valueSerializer
: this.writeContext.typeResolver.getSerializerByData(v);
const header = mapChunkWriter.next(
- new ElementInfo(
- keySerializer || null,
- k == null,
- keySerializer?.needToWriteRef() || false,
- ),
+ new ElementInfo(keySerializer || null, k == null, keySerializer?.needToWriteRef() || false),
new ElementInfo(
valueSerializer || null,
v == null,
@@ -220,10 +209,7 @@ class MapAnySerializer {
const keyHeader = header & 0b111;
const valueHeader = header >> 3;
if (mapChunkWriter.isFirst()) {
- if (
- !(keyHeader & MapFlags.HAS_NULL)
- && !(valueHeader & MapFlags.HAS_NULL)
- ) {
+ if (!(keyHeader & MapFlags.HAS_NULL) && !(valueHeader & MapFlags.HAS_NULL)) {
if (!(keyHeader & MapFlags.DECL_ELEMENT_TYPE)) {
keySerializer?.writeTypeInfo(null);
}
@@ -233,8 +219,7 @@ class MapAnySerializer {
}
}
- const includeNone
- = keyHeader & MapFlags.HAS_NULL || valueHeader & MapFlags.HAS_NULL;
+ const includeNone = keyHeader & MapFlags.HAS_NULL || valueHeader & MapFlags.HAS_NULL;
if (!this.writeFlag(keyHeader, k)) {
if (!includeNone) {
keySerializer!.write(k);
@@ -266,32 +251,21 @@ class MapAnySerializer {
return null;
}
if (!trackingRef) {
- serializer
- = serializer == null
- ? AnyHelper.detectSerializer(this.readContext)
- : serializer;
+ serializer = serializer == null ? AnyHelper.detectSerializer(this.readContext) : serializer;
return this.readSerializerWithDepth(serializer!, false);
}
const flag = this.readContext.reader.readInt8();
switch (flag) {
case RefFlags.RefValueFlag:
- serializer
- = serializer == null
- ? AnyHelper.detectSerializer(this.readContext)
- : serializer;
+ serializer = serializer == null ? AnyHelper.detectSerializer(this.readContext) : serializer;
return this.readSerializerWithDepth(serializer!, true);
case RefFlags.RefFlag:
- return this.readContext.getReadRef(
- this.readContext.reader.readVarUInt32(),
- );
+ return this.readContext.getReadRef(this.readContext.reader.readVarUInt32());
case RefFlags.NullFlag:
return null;
case RefFlags.NotNullValueFlag:
- serializer
- = serializer == null
- ? AnyHelper.detectSerializer(this.readContext)
- : serializer;
+ serializer = serializer == null ? AnyHelper.detectSerializer(this.readContext) : serializer;
return this.readSerializerWithDepth(serializer!, false);
}
}
@@ -315,10 +289,7 @@ class MapAnySerializer {
let keySerializer = this.keySerializer;
let valueSerializer = this.valueSerializer;
- if (
- !(keyHeader & MapFlags.HAS_NULL)
- && !(valueHeader & MapFlags.HAS_NULL)
- ) {
+ if (!(keyHeader & MapFlags.HAS_NULL) && !(valueHeader & MapFlags.HAS_NULL)) {
if (!(keyHeader & MapFlags.DECL_ELEMENT_TYPE)) {
keySerializer = AnyHelper.detectSerializer(this.readContext);
}
@@ -363,23 +334,19 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
const keyTypeId = this.typeInfo.options?.key!.typeId;
const valueTypeId = this.typeInfo.options?.value!.typeId;
return (
- keyTypeId === TypeId.UNKNOWN
- || valueTypeId === TypeId.UNKNOWN
- || !TypeId.isBuiltin(keyTypeId!)
- || !TypeId.isBuiltin(valueTypeId!)
+ keyTypeId === TypeId.UNKNOWN ||
+ valueTypeId === TypeId.UNKNOWN ||
+ !TypeId.isBuiltin(keyTypeId!) ||
+ !TypeId.isBuiltin(valueTypeId!)
);
}
private writeSpecificType(accessor: string) {
const k = this.scope.uniqueName("k");
const v = this.scope.uniqueName("v");
- let keyHeader = this.keyGenerator.needToWriteRef()
- ? MapFlags.TRACKING_REF
- : 0;
+ let keyHeader = this.keyGenerator.needToWriteRef() ? MapFlags.TRACKING_REF : 0;
keyHeader |= MapFlags.DECL_ELEMENT_TYPE;
- let valueHeader = this.valueGenerator.needToWriteRef()
- ? MapFlags.TRACKING_REF
- : 0;
+ let valueHeader = this.valueGenerator.needToWriteRef() ? MapFlags.TRACKING_REF : 0;
valueHeader |= MapFlags.DECL_ELEMENT_TYPE;
const lastKeyIsNull = this.scope.uniqueName("lastKeyIsNull");
const lastValueIsNull = this.scope.uniqueName("lastValueIsNull");
@@ -471,12 +438,12 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
"map_inner_ser",
TypeId.isNamedType(innerTypeInfo.typeId)
? this.builder.typeResolver.getSerializerByName(
- CodecBuilder.replaceBackslashAndQuote(innerTypeInfo.named!),
- )
+ CodecBuilder.replaceBackslashAndQuote(innerTypeInfo.named!),
+ )
: this.builder.typeResolver.getSerializerById(
- innerTypeInfo.typeId,
- innerTypeInfo.userTypeId,
- ),
+ innerTypeInfo.typeId,
+ innerTypeInfo.userTypeId,
+ ),
);
};
return `new (${anySerializer})(${this.builder.getWriteContextName()}, ${this.builder.getReadContextName()}, ${
@@ -490,10 +457,7 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
}).write(${accessor})`;
}
- private readSpecificType(
- accessor: (expr: string) => string,
- refState: string,
- ) {
+ private readSpecificType(accessor: (expr: string) => string, refState: string) {
const count = this.scope.uniqueName("count");
const result = this.scope.uniqueName("result");
// Skip depth tracking for leaf key/value types.
@@ -565,12 +529,12 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
switch (flag) {
case ${RefFlags.RefValueFlag}:
if (${keyDeclaredType}) {
- ${readKey(x => `key = ${x}`, "true")}
+ ${readKey((x) => `key = ${x}`, "true")}
} else {
if (!${keySerializer}) {
${keySerializer} = ${anyHelper}.detectSerializer(${readContextName});
}
- ${readDynamic(keySerializer, x => `key = ${x}`, "true")}
+ ${readDynamic(keySerializer, (x) => `key = ${x}`, "true")}
}
break;
case ${RefFlags.RefFlag}:
@@ -581,23 +545,23 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
break;
case ${RefFlags.NotNullValueFlag}:
if (${keyDeclaredType}) {
- ${readKey(x => `key = ${x}`, "false")}
+ ${readKey((x) => `key = ${x}`, "false")}
} else {
if (!${keySerializer}) {
${keySerializer} = ${anyHelper}.detectSerializer(${readContextName});
}
- ${readDynamic(keySerializer, x => `key = ${x}`, "false")}
+ ${readDynamic(keySerializer, (x) => `key = ${x}`, "false")}
}
break;
}
} else {
if (${keyDeclaredType}) {
- ${readKey(x => `key = ${x}`, "false")}
+ ${readKey((x) => `key = ${x}`, "false")}
} else {
if (!${keySerializer}) {
${keySerializer} = ${anyHelper}.detectSerializer(${readContextName});
}
- ${readDynamic(keySerializer, x => `key = ${x}`, "false")}
+ ${readDynamic(keySerializer, (x) => `key = ${x}`, "false")}
}
}
@@ -608,12 +572,12 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
switch (flag) {
case ${RefFlags.RefValueFlag}:
if (${valueDeclaredType}) {
- ${readValue(x => `value = ${x}`, "true")}
+ ${readValue((x) => `value = ${x}`, "true")}
} else {
if (!${valueSerializer}) {
${valueSerializer} = ${anyHelper}.detectSerializer(${readContextName});
}
- ${readDynamic(valueSerializer, x => `value = ${x}`, "true")}
+ ${readDynamic(valueSerializer, (x) => `value = ${x}`, "true")}
}
break;
case ${RefFlags.RefFlag}:
@@ -624,23 +588,23 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
break;
case ${RefFlags.NotNullValueFlag}:
if (${valueDeclaredType}) {
- ${readValue(x => `value = ${x}`, "false")}
+ ${readValue((x) => `value = ${x}`, "false")}
} else {
if (!${valueSerializer}) {
${valueSerializer} = ${anyHelper}.detectSerializer(${readContextName});
}
- ${readDynamic(valueSerializer, x => `value = ${x}`, "false")}
+ ${readDynamic(valueSerializer, (x) => `value = ${x}`, "false")}
}
break;
}
} else {
if (${valueDeclaredType}) {
- ${readValue(x => `value = ${x}`, "false")}
+ ${readValue((x) => `value = ${x}`, "false")}
} else {
if (!${valueSerializer}) {
${valueSerializer} = ${anyHelper}.detectSerializer(${readContextName});
}
- ${readDynamic(valueSerializer, x => `value = ${x}`, "false")}
+ ${readDynamic(valueSerializer, (x) => `value = ${x}`, "false")}
}
}
@@ -665,12 +629,12 @@ export class MapSerializerGenerator extends BaseSerializerGenerator {
"map_inner_ser",
TypeId.isNamedType(innerTypeInfo.typeId)
? this.builder.typeResolver.getSerializerByName(
- CodecBuilder.replaceBackslashAndQuote(innerTypeInfo.named!),
- )
+ CodecBuilder.replaceBackslashAndQuote(innerTypeInfo.named!),
+ )
: this.builder.typeResolver.getSerializerById(
- innerTypeInfo.typeId,
- innerTypeInfo.userTypeId,
- ),
+ innerTypeInfo.typeId,
+ innerTypeInfo.userTypeId,
+ ),
);
};
return accessor(
diff --git a/javascript/packages/core/lib/gen/number.ts b/javascript/packages/core/lib/gen/number.ts
index 55e54554d..d1c702637 100644
--- a/javascript/packages/core/lib/gen/number.ts
+++ b/javascript/packages/core/lib/gen/number.ts
@@ -24,7 +24,10 @@ import { CodegenRegistry } from "./router";
import { TypeId } from "../type";
import { Scope } from "./scope";
-function buildNumberSerializer(writeFun: (builder: CodecBuilder, accessor: string) => string, read: (builder: CodecBuilder) => string) {
+function buildNumberSerializer(
+ writeFun: (builder: CodecBuilder, accessor: string) => string,
+ read: (builder: CodecBuilder) => string,
+) {
return class NumberSerializerGenerator extends BaseSerializerGenerator {
typeInfo: TypeInfo;
@@ -47,125 +50,143 @@ function buildNumberSerializer(writeFun: (builder: CodecBuilder, accessor: strin
};
}
-CodegenRegistry.register(TypeId.INT8,
+CodegenRegistry.register(
+ TypeId.INT8,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeInt8(accessor),
- builder => builder.reader.readInt8()
- )
+ (builder) => builder.reader.readInt8(),
+ ),
);
-CodegenRegistry.register(TypeId.INT16,
+CodegenRegistry.register(
+ TypeId.INT16,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeInt16(accessor),
- builder => builder.reader.readInt16()
- )
+ (builder) => builder.reader.readInt16(),
+ ),
);
-CodegenRegistry.register(TypeId.INT32,
+CodegenRegistry.register(
+ TypeId.INT32,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeInt32(accessor),
- builder => builder.reader.readInt32()
- )
+ (builder) => builder.reader.readInt32(),
+ ),
);
-CodegenRegistry.register(TypeId.VARINT32,
+CodegenRegistry.register(
+ TypeId.VARINT32,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeVarInt32(accessor),
- builder => builder.reader.readVarInt32()
- )
+ (builder) => builder.reader.readVarInt32(),
+ ),
);
-CodegenRegistry.register(TypeId.INT64,
+CodegenRegistry.register(
+ TypeId.INT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeInt64(accessor),
- builder => builder.reader.readInt64()
- )
+ (builder) => builder.reader.readInt64(),
+ ),
);
-CodegenRegistry.register(TypeId.TAGGED_INT64,
+CodegenRegistry.register(
+ TypeId.TAGGED_INT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeTaggedInt64(accessor),
- builder => builder.reader.readTaggedInt64()
- )
+ (builder) => builder.reader.readTaggedInt64(),
+ ),
);
-CodegenRegistry.register(TypeId.TAGGED_UINT64,
+CodegenRegistry.register(
+ TypeId.TAGGED_UINT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeTaggedUInt64(accessor),
- builder => builder.reader.readTaggedUInt64()
- )
+ (builder) => builder.reader.readTaggedUInt64(),
+ ),
);
-CodegenRegistry.register(TypeId.FLOAT16,
+CodegenRegistry.register(
+ TypeId.FLOAT16,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeFloat16(accessor),
- builder => builder.reader.readFloat16()
- )
+ (builder) => builder.reader.readFloat16(),
+ ),
);
-CodegenRegistry.register(TypeId.BFLOAT16,
+CodegenRegistry.register(
+ TypeId.BFLOAT16,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeBfloat16(accessor),
- builder => builder.reader.readBfloat16()
- )
+ (builder) => builder.reader.readBfloat16(),
+ ),
);
-CodegenRegistry.register(TypeId.FLOAT32,
+CodegenRegistry.register(
+ TypeId.FLOAT32,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeFloat32(accessor),
- builder => builder.reader.readFloat32()
- )
+ (builder) => builder.reader.readFloat32(),
+ ),
);
-CodegenRegistry.register(TypeId.FLOAT64,
+CodegenRegistry.register(
+ TypeId.FLOAT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeFloat64(accessor),
- builder => builder.reader.readFloat64()
- )
+ (builder) => builder.reader.readFloat64(),
+ ),
);
-CodegenRegistry.register(TypeId.UINT8,
+CodegenRegistry.register(
+ TypeId.UINT8,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeUint8(accessor),
- builder => builder.reader.readUint8()
- )
+ (builder) => builder.reader.readUint8(),
+ ),
);
-CodegenRegistry.register(TypeId.UINT16,
+CodegenRegistry.register(
+ TypeId.UINT16,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeUint16(accessor),
- builder => builder.reader.readUint16()
- )
+ (builder) => builder.reader.readUint16(),
+ ),
);
-CodegenRegistry.register(TypeId.UINT32,
+CodegenRegistry.register(
+ TypeId.UINT32,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeUint32(accessor),
- builder => builder.reader.readUint32()
- )
+ (builder) => builder.reader.readUint32(),
+ ),
);
-CodegenRegistry.register(TypeId.VAR_UINT32,
+CodegenRegistry.register(
+ TypeId.VAR_UINT32,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeVarUInt32(accessor),
- builder => builder.reader.readVarUInt32()
- )
+ (builder) => builder.reader.readVarUInt32(),
+ ),
);
-CodegenRegistry.register(TypeId.UINT64,
+CodegenRegistry.register(
+ TypeId.UINT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeUint64(accessor),
- builder => builder.reader.readUint64()
- )
+ (builder) => builder.reader.readUint64(),
+ ),
);
-CodegenRegistry.register(TypeId.VAR_UINT64,
+CodegenRegistry.register(
+ TypeId.VAR_UINT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeVarUInt64(accessor),
- builder => builder.reader.readVarUInt64()
- )
+ (builder) => builder.reader.readVarUInt64(),
+ ),
);
-CodegenRegistry.register(TypeId.VARINT64,
+CodegenRegistry.register(
+ TypeId.VARINT64,
buildNumberSerializer(
(builder, accessor) => builder.writer.writeVarInt64(accessor),
- builder => builder.reader.readVarInt64()
- )
+ (builder) => builder.reader.readVarInt64(),
+ ),
);
diff --git a/javascript/packages/core/lib/gen/router.ts b/javascript/packages/core/lib/gen/router.ts
index a934eb618..5492348aa 100644
--- a/javascript/packages/core/lib/gen/router.ts
+++ b/javascript/packages/core/lib/gen/router.ts
@@ -22,7 +22,11 @@ import { SerializerGenerator } from "./serializer";
import { CodecBuilder } from "./builder";
import { Scope } from "./scope";
-type SerializerGeneratorConstructor = new (typeInfo: TypeInfo, builder: CodecBuilder, scope: Scope) => SerializerGenerator;
+type SerializerGeneratorConstructor = new (
+ typeInfo: TypeInfo,
+ builder: CodecBuilder,
+ scope: Scope,
+) => SerializerGenerator;
export class CodegenRegistry {
static map = new Map<number, SerializerGeneratorConstructor>();
@@ -56,6 +60,8 @@ export class CodegenRegistry {
}
static getExternal() {
- return Object.fromEntries(Array.from(CodegenRegistry.external.entries()).map(([key, value]) => [key, value]));
+ return Object.fromEntries(
+ Array.from(CodegenRegistry.external.entries()).map(([key, value]) => [key, value]),
+ );
}
}
diff --git a/javascript/packages/core/lib/gen/scope.ts b/javascript/packages/core/lib/gen/scope.ts
index 5cb8843e5..6402c3436 100644
--- a/javascript/packages/core/lib/gen/scope.ts
+++ b/javascript/packages/core/lib/gen/scope.ts
@@ -63,8 +63,12 @@ export class Scope {
generate() {
return `
- ${Array.from(this.declares.entries()).map(x => `const ${x[1]} = ${x[0]};`).join("\n")}
- ${Array.from(this.varDeclares.entries()).map(x => `let ${x[0]} = ${x[1]};`).join("\n")}
+ ${Array.from(this.declares.entries())
+ .map((x) => `const ${x[1]} = ${x[0]};`)
+ .join("\n")}
+ ${Array.from(this.varDeclares.entries())
+ .map((x) => `let ${x[0]} = ${x[1]};`)
+ .join("\n")}
`;
}
}
diff --git a/javascript/packages/core/lib/gen/serializer.ts b/javascript/packages/core/lib/gen/serializer.ts
index 439e1f490..78d0b0c12 100644
--- a/javascript/packages/core/lib/gen/serializer.ts
+++ b/javascript/packages/core/lib/gen/serializer.ts
@@ -68,9 +68,7 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
protected typeInfo: TypeInfo,
protected builder: CodecBuilder,
protected scope: Scope,
- ) {
-
- }
+ ) {}
abstract getFixedSize(): number;
@@ -115,7 +113,7 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
const noneedWrite = this.scope.uniqueName("noneedWrite");
return `
let ${noneedWrite} = false;
- ${this.writeRefOrNull(accessor, expr => `${noneedWrite} = ${expr}`)}
+ ${this.writeRefOrNull(accessor, (expr) => `${noneedWrite} = ${expr}`)}
if (!${noneedWrite}) {
${this.writeNoRef(accessor)}
}
@@ -161,9 +159,10 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
void accessor;
const typeId = this.getTypeId();
const userTypeId = this.typeInfo.userTypeId;
- const userTypeStmt = TypeId.needsUserTypeId(typeId) && typeId !== TypeId.COMPATIBLE_STRUCT
- ? this.builder.writer.writeVarUint32Small7(userTypeId)
- : "";
+ const userTypeStmt =
+ TypeId.needsUserTypeId(typeId) && typeId !== TypeId.COMPATIBLE_STRUCT
+ ? this.builder.writer.writeVarUint32Small7(userTypeId)
+ : "";
return `
${this.builder.writer.writeUint8(typeId)};
${userTypeStmt}
@@ -193,7 +192,7 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
return `
${this.builder.getReadContextName()}.incReadDepth();
let ${result};
- ${this.read(v => `${result} = ${v}`, refState)};
+ ${this.read((v) => `${result} = ${v}`, refState)};
${this.builder.getReadContextName()}.decReadDepth();
${assignStmt(result)};
`;
@@ -201,9 +200,10 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
readTypeInfo(): string {
const typeId = this.getTypeId();
- const readUserTypeStmt = TypeId.needsUserTypeId(typeId) && typeId !== TypeId.COMPATIBLE_STRUCT
- ? `${this.builder.reader.readVarUint32Small7()};`
- : "";
+ const readUserTypeStmt =
+ TypeId.needsUserTypeId(typeId) && typeId !== TypeId.COMPATIBLE_STRUCT
+ ? `${this.builder.reader.readVarUint32Small7()};`
+ : "";
return `
${this.builder.reader.readUint8()};
${readUserTypeStmt}
@@ -226,7 +226,7 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
switch (${refFlag}) {
case ${RefFlags.NotNullValueFlag}:
case ${RefFlags.RefValueFlag}:
- ${this.readWithDepth(v => `${result} = ${v}`, `${refFlag} === ${RefFlags.RefValueFlag}`)}
+ ${this.readWithDepth((v) => `${result} = ${v}`, `${refFlag} === ${RefFlags.RefValueFlag}`)}
break;
case ${RefFlags.RefFlag}:
${result} = ${this.builder.referenceResolver.getReadRef(this.builder.reader.readVarUInt32())};
@@ -307,22 +307,22 @@ export abstract class BaseSerializerGenerator implements SerializerGenerator {
${this.writeNoRef("v")}
};
const writeRefOrNull = (v) => {
- ${this.writeRefOrNull("v", expr => `return ${expr};`)}
+ ${this.writeRefOrNull("v", (expr) => `return ${expr};`)}
};
const writeTypeInfo = (v) => {
${this.writeTypeInfo("v")}
};
const read = (fromRef) => {
- ${this.read(assignStmt => `return ${assignStmt}`, "fromRef")}
+ ${this.read((assignStmt) => `return ${assignStmt}`, "fromRef")}
};
const readRef = () => {
- ${this.readRef(assignStmt => `return ${assignStmt}`)}
+ ${this.readRef((assignStmt) => `return ${assignStmt}`)}
};
const readRefWithoutTypeInfo = () => {
- ${this.readRefWithoutTypeInfo(assignStmt => `return ${assignStmt}`)}
+ ${this.readRefWithoutTypeInfo((assignStmt) => `return ${assignStmt}`)}
};
const readNoRef = (fromRef) => {
- ${this.readNoRef(assignStmt => `return ${assignStmt}`, "fromRef")}
+ ${this.readNoRef((assignStmt) => `return ${assignStmt}`, "fromRef")}
};
const readTypeInfo = () => {
${this.readTypeInfo()}
diff --git a/javascript/packages/core/lib/gen/struct.ts b/javascript/packages/core/lib/gen/struct.ts
index 5b02a53a1..69ecb5dc1 100644
--- a/javascript/packages/core/lib/gen/struct.ts
+++ b/javascript/packages/core/lib/gen/struct.ts
@@ -25,10 +25,7 @@ import { CodegenRegistry } from "./router";
import { BaseSerializerGenerator, SerializerGenerator } from "./serializer";
import { TypeMeta } from "../meta/TypeMeta";
import { getCompatibleCollectionArrayReadAction } from "./collection";
-import {
- CompatibleScalarConverter,
- getCompatibleScalarReadAction,
-} from "../compatible/scalar";
+import { CompatibleScalarConverter, getCompatibleScalarReadAction } from "../compatible/scalar";
import { shouldSkipCompatibleRead } from "../compatible/field";
/**
@@ -67,11 +64,12 @@ function compatibleReadTargetExpr(typeInfo: TypeInfo, expr: string): string {
const sortProps = (typeInfo: TypeInfo, typeResolver: CodecBuilder["resolver"]) => {
const props = typeInfo.options!.props;
if (typeInfo.options!.preserveFieldOrder) {
- return typeInfo.options!.fieldEntries ?? Object.entries(props!).map(
- ([key, fieldTypeInfo]) => ({
+ return (
+ typeInfo.options!.fieldEntries ??
+ Object.entries(props!).map(([key, fieldTypeInfo]) => ({
key,
typeInfo: fieldTypeInfo,
- }),
+ }))
);
}
const names = TypeMeta.fromTypeInfo(typeInfo, typeResolver).getFieldInfo();
@@ -92,7 +90,6 @@ enum RefMode {
/** Ref tracking enabled (implies nullable). Write ref flags and handle shared references. */
TRACKING,
-
}
function toRefMode(trackingRef?: boolean, nullable?: boolean) {
@@ -105,10 +102,7 @@ function toRefMode(trackingRef?: boolean, nullable?: boolean) {
}
}
-function isDirectVarInt32Field(
- typeInfo: TypeInfo,
- typeResolver: CodecBuilder["resolver"],
-) {
+function isDirectVarInt32Field(typeInfo: TypeInfo, typeResolver: CodecBuilder["resolver"]) {
return varInt32ObjectReadKind(typeInfo, typeResolver) === "number";
}
@@ -117,32 +111,29 @@ function varInt32ObjectReadKind(
typeResolver: CodecBuilder["resolver"],
): "number" | "bigint" | null {
if (
- toRefMode(typeInfo.trackingRef, typeInfo.nullable) !== RefMode.NONE
- || !typeResolver.isMonomorphic(typeInfo, typeInfo.dynamic)
+ toRefMode(typeInfo.trackingRef, typeInfo.nullable) !== RefMode.NONE ||
+ !typeResolver.isMonomorphic(typeInfo, typeInfo.dynamic)
) {
return null;
}
const scalarAction = getCompatibleScalarReadAction(typeInfo);
if (scalarAction !== undefined) {
- return scalarAction.remoteNullable !== true
- && scalarAction.remoteTypeId === TypeId.VARINT32
- && (scalarAction.localTypeId === TypeId.INT64
- || scalarAction.localTypeId === TypeId.VARINT64
- || scalarAction.localTypeId === TypeId.TAGGED_INT64)
+ return scalarAction.remoteNullable !== true &&
+ scalarAction.remoteTypeId === TypeId.VARINT32 &&
+ (scalarAction.localTypeId === TypeId.INT64 ||
+ scalarAction.localTypeId === TypeId.VARINT64 ||
+ scalarAction.localTypeId === TypeId.TAGGED_INT64)
? "bigint"
: null;
}
return typeInfo.typeId === TypeId.VARINT32 ? "number" : null;
}
-function directNumericFieldReadExpr(
- typeInfo: TypeInfo,
- builder: CodecBuilder,
-): string | null {
+function directNumericFieldReadExpr(typeInfo: TypeInfo, builder: CodecBuilder): string | null {
if (
- toRefMode(typeInfo.trackingRef, typeInfo.nullable) !== RefMode.NONE
- || !builder.resolver.isMonomorphic(typeInfo, typeInfo.dynamic)
- || getCompatibleScalarReadAction(typeInfo) !== undefined
+ toRefMode(typeInfo.trackingRef, typeInfo.nullable) !== RefMode.NONE ||
+ !builder.resolver.isMonomorphic(typeInfo, typeInfo.dynamic) ||
+ getCompatibleScalarReadAction(typeInfo) !== undefined
) {
return null;
}
@@ -194,11 +185,7 @@ function compatibleScalarFieldReadExpr(
builder: CodecBuilder,
): string | null {
const converter = builder.getExternal(CompatibleScalarConverter.name);
- const remoteRead = compatibleScalarRemoteReadExpr(
- remoteTypeId,
- builder,
- converter,
- );
+ const remoteRead = compatibleScalarRemoteReadExpr(remoteTypeId, builder, converter);
if (remoteRead === null) {
return null;
}
@@ -222,22 +209,12 @@ function compatibleScalarFieldReadExpr(
case TypeId.UINT16:
case TypeId.UINT32:
case TypeId.UINT64:
- return scalarToIntegerExpr(
- remoteCanonical,
- localCanonical,
- remoteRead,
- converter,
- );
+ return scalarToIntegerExpr(remoteCanonical, localCanonical, remoteRead, converter);
case TypeId.FLOAT16:
case TypeId.BFLOAT16:
case TypeId.FLOAT32:
case TypeId.FLOAT64:
- return scalarToFloatExpr(
- remoteCanonical,
- localCanonical,
- remoteRead,
- converter,
- );
+ return scalarToFloatExpr(remoteCanonical, localCanonical, remoteRead, converter);
default:
return null;
}
@@ -314,11 +291,7 @@ function compatibleScalarRemoteReadExpr(
}
}
-function scalarToBoolExpr(
- remoteTypeId: number,
- value: string,
- converter: string,
-): string | null {
+function scalarToBoolExpr(remoteTypeId: number, value: string, converter: string): string | null {
switch (remoteTypeId) {
case TypeId.BOOL:
return value;
@@ -336,11 +309,7 @@ function scalarToBoolExpr(
}
}
-function scalarToStringExpr(
- remoteTypeId: number,
- value: string,
- converter: string,
-): string | null {
+function scalarToStringExpr(remoteTypeId: number, value: string, converter: string): string | null {
switch (remoteTypeId) {
case TypeId.BOOL:
return `(${value} ? "true" : "false")`;
@@ -456,26 +425,31 @@ function integerRangeFits(remoteTypeId: number, localTypeId: number): boolean {
case TypeId.INT16:
return remoteTypeId === TypeId.INT8 || remoteTypeId === TypeId.UINT8;
case TypeId.INT32:
- return remoteTypeId === TypeId.INT8
- || remoteTypeId === TypeId.INT16
- || remoteTypeId === TypeId.UINT8
- || remoteTypeId === TypeId.UINT16;
+ return (
+ remoteTypeId === TypeId.INT8 ||
+ remoteTypeId === TypeId.INT16 ||
+ remoteTypeId === TypeId.UINT8 ||
+ remoteTypeId === TypeId.UINT16
+ );
case TypeId.INT64:
- return remoteTypeId === TypeId.INT8
- || remoteTypeId === TypeId.INT16
- || remoteTypeId === TypeId.INT32
- || remoteTypeId === TypeId.UINT8
- || remoteTypeId === TypeId.UINT16
- || remoteTypeId === TypeId.UINT32;
+ return (
+ remoteTypeId === TypeId.INT8 ||
+ remoteTypeId === TypeId.INT16 ||
+ remoteTypeId === TypeId.INT32 ||
+ remoteTypeId === TypeId.UINT8 ||
+ remoteTypeId === TypeId.UINT16 ||
+ remoteTypeId === TypeId.UINT32
+ );
case TypeId.UINT16:
return remoteTypeId === TypeId.UINT8;
case TypeId.UINT32:
- return remoteTypeId === TypeId.UINT8
- || remoteTypeId === TypeId.UINT16;
+ return remoteTypeId === TypeId.UINT8 || remoteTypeId === TypeId.UINT16;
case TypeId.UINT64:
- return remoteTypeId === TypeId.UINT8
- || remoteTypeId === TypeId.UINT16
- || remoteTypeId === TypeId.UINT32;
+ return (
+ remoteTypeId === TypeId.UINT8 ||
+ remoteTypeId === TypeId.UINT16 ||
+ remoteTypeId === TypeId.UINT32
+ );
default:
return false;
}
@@ -529,26 +503,27 @@ function floatMethod(prefix: string, localTypeId: number): string | null {
}
}
-function integerRangeFitsFloat(
- remoteTypeId: number,
- localTypeId: number,
-): boolean {
+function integerRangeFitsFloat(remoteTypeId: number, localTypeId: number): boolean {
switch (localTypeId) {
case TypeId.FLOAT16:
case TypeId.BFLOAT16:
return remoteTypeId === TypeId.INT8 || remoteTypeId === TypeId.UINT8;
case TypeId.FLOAT32:
- return remoteTypeId === TypeId.INT8
- || remoteTypeId === TypeId.INT16
- || remoteTypeId === TypeId.UINT8
- || remoteTypeId === TypeId.UINT16;
+ return (
+ remoteTypeId === TypeId.INT8 ||
+ remoteTypeId === TypeId.INT16 ||
+ remoteTypeId === TypeId.UINT8 ||
+ remoteTypeId === TypeId.UINT16
+ );
case TypeId.FLOAT64:
- return remoteTypeId === TypeId.INT8
- || remoteTypeId === TypeId.INT16
- || remoteTypeId === TypeId.INT32
- || remoteTypeId === TypeId.UINT8
- || remoteTypeId === TypeId.UINT16
- || remoteTypeId === TypeId.UINT32;
+ return (
+ remoteTypeId === TypeId.INT8 ||
+ remoteTypeId === TypeId.INT16 ||
+ remoteTypeId === TypeId.INT32 ||
+ remoteTypeId === TypeId.UINT8 ||
+ remoteTypeId === TypeId.UINT16 ||
+ remoteTypeId === TypeId.UINT32
+ );
default:
return false;
}
@@ -580,14 +555,22 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
private isDepthFreeStruct(): boolean {
- return this.sortedProps.length > 0
- && this.sortedProps.every(({ typeInfo }) => isDepthFreeField(typeInfo));
+ return (
+ this.sortedProps.length > 0 &&
+ this.sortedProps.every(({ typeInfo }) => isDepthFreeField(typeInfo))
+ );
}
- readField(fieldName: string, fieldTypeInfo: TypeInfo, assignStmt: (expr: string) => string, embedGenerator: SerializerGenerator) {
+ readField(
+ fieldName: string,
+ fieldTypeInfo: TypeInfo,
+ assignStmt: (expr: string) => string,
+ embedGenerator: SerializerGenerator,
+ ) {
const { nullable = false, dynamic, trackingRef } = fieldTypeInfo;
const refMode = toRefMode(trackingRef, nullable);
- const assignCompatible = (expr: string) => assignStmt(compatibleReadTargetExpr(fieldTypeInfo, expr));
+ const assignCompatible = (expr: string) =>
+ assignStmt(compatibleReadTargetExpr(fieldTypeInfo, expr));
if (shouldSkipCompatibleRead(fieldTypeInfo)) {
const discard = (expr: string) => `${expr};`;
if (this.builder.resolver.isMonomorphic(fieldTypeInfo, dynamic)) {
@@ -657,7 +640,12 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
return stmt;
}
- writeField(fieldName: string, fieldTypeInfo: TypeInfo, fieldAccessor: string, embedGenerator: SerializerGenerator) {
+ writeField(
+ fieldName: string,
+ fieldTypeInfo: TypeInfo,
+ fieldAccessor: string,
+ embedGenerator: SerializerGenerator,
+ ) {
const { nullable = false, dynamic, trackingRef } = fieldTypeInfo;
const refMode = toRefMode(trackingRef, nullable);
let stmt = "";
@@ -667,7 +655,7 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
const noneedWrite = this.scope.uniqueName("noneedWrite");
stmt = `
let ${noneedWrite} = false;
- ${embedGenerator.writeRefOrNull(fieldAccessor, expr => `${noneedWrite} = ${expr}`)}
+ ${embedGenerator.writeRefOrNull(fieldAccessor, (expr) => `${noneedWrite} = ${expr}`)}
if (!${noneedWrite}) {
${embedGenerator.write(fieldAccessor)}
}
@@ -727,8 +715,8 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
if (isDirectVarInt32Field(current.typeInfo, this.builder.resolver)) {
let end = i + 1;
while (
- end < this.sortedProps.length
- && isDirectVarInt32Field(this.sortedProps[end].typeInfo, this.builder.resolver)
+ end < this.sortedProps.length &&
+ isDirectVarInt32Field(this.sortedProps[end].typeInfo, this.builder.resolver)
) {
end++;
}
@@ -744,7 +732,9 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
const innerGenerator = new InnerGeneratorClass(current.typeInfo, this.builder, this.scope);
const fieldAccessor = `${accessor}${CodecBuilder.safePropAccessor(current.key)}`;
- fieldWrites.push(this.writeField(current.key, current.typeInfo, fieldAccessor, innerGenerator.writeEmbed()));
+ fieldWrites.push(
+ this.writeField(current.key, current.typeInfo, fieldAccessor, innerGenerator.writeEmbed()),
+ );
i++;
}
return `
@@ -753,10 +743,7 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
`;
}
- private writeVarInt32Run(
- accessor: string,
- fields: { key: string; typeInfo: TypeInfo }[],
- ) {
+ private writeVarInt32Run(accessor: string, fields: { key: string; typeInfo: TypeInfo }[]) {
const cursor = this.scope.uniqueName("cursor");
const buffer = this.scope.uniqueName("buffer");
const dataView = this.scope.uniqueName("dataView");
@@ -770,12 +757,18 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
local: this.scope.uniqueName(key),
};
});
- const checks = locals.map(({ key, local }) => `
+ const checks = locals
+ .map(
+ ({ key, local }) => `
if (${local} === null || ${local} === undefined) {
throw new Error('Field ${CodecBuilder.safeString(key)} is not nullable');
}
- `).join("\n");
- const writes = locals.map(({ local }) => `
+ `,
+ )
+ .join("\n");
+ const writes = locals
+ .map(
+ ({ local }) => `
${value} = ((${local} << 1) ^ (${local} >> 31)) >>> 0;
if (${value} >>> 7 === 0) {
${buffer}[${cursor}++] = ${value};
@@ -797,7 +790,9 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
${dataView}.setUint32(${rawCursor}, ${u32});
}
- `).join("\n");
+ `,
+ )
+ .join("\n");
return `
${locals.map(({ local, fieldAccessor }) => `const ${local} = ${fieldAccessor};`).join("\n")}
${checks}
@@ -824,50 +819,60 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
const directNumericObjectRead = this.readDirectNumericObject(accessor, refState);
if (directNumericObjectRead !== null) {
return `
- ${!this.builder.resolver.isCompatible()
-? `
+ ${
+ !this.builder.resolver.isCompatible()
+ ? `
if(${this.builder.reader.readInt32()} !== ${hash}) {
throw new Error("Read class version is not consistent with ${hash} ")
}
`
-: ""}
+ : ""
+ }
${directNumericObjectRead}
`;
}
return `
- ${!this.builder.resolver.isCompatible()
-? `
+ ${
+ !this.builder.resolver.isCompatible()
+ ? `
if(${this.builder.reader.readInt32()} !== ${hash}) {
throw new Error("Read class version is not consistent with ${hash} ")
}
`
-: ""}
- ${this.typeInfo.options!.withConstructor
- ? `
+ : ""
+ }
+ ${
+ this.typeInfo.options!.withConstructor
+ ? `
const ${result} = new ${this.builder.getOptions("creator")}();
`
- : `
+ : `
const ${result} = {
- ${this.sortedProps.map(({ key }) => {
- if (shouldSkipCompatibleRead(this.typeInfo.options!.props![key])) {
- return "";
- }
- return `${CodecBuilder.safePropName(key)}: null`;
- }).filter(Boolean).join(",\n")}
+ ${this.sortedProps
+ .map(({ key }) => {
+ if (shouldSkipCompatibleRead(this.typeInfo.options!.props![key])) {
+ return "";
+ }
+ return `${CodecBuilder.safePropName(key)}: null`;
+ })
+ .filter(Boolean)
+ .join(",\n")}
};
`
}
${this.maybeReference(result, refState)}
- ${this.sortedProps.map(({ key, typeInfo }) => {
- const InnerGeneratorClass = CodegenRegistry.get(typeInfo.typeId);
- if (!InnerGeneratorClass) {
- throw new Error(`${typeInfo.typeId} generator not exists`);
- }
- const innerGenerator = new InnerGeneratorClass(typeInfo, this.builder, this.scope);
- return `
- ${this.readField(key, typeInfo, expr => `${result}${CodecBuilder.safePropAccessor(key)} = ${expr}`, innerGenerator.readEmbed())}
+ ${this.sortedProps
+ .map(({ key, typeInfo }) => {
+ const InnerGeneratorClass = CodegenRegistry.get(typeInfo.typeId);
+ if (!InnerGeneratorClass) {
+ throw new Error(`${typeInfo.typeId} generator not exists`);
+ }
+ const innerGenerator = new InnerGeneratorClass(typeInfo, this.builder, this.scope);
+ return `
+ ${this.readField(key, typeInfo, (expr) => `${result}${CodecBuilder.safePropAccessor(key)} = ${expr}`, innerGenerator.readEmbed())}
`;
- }).join(";\n")}
+ })
+ .join(";\n")}
${accessor(result)}
`;
}
@@ -889,15 +894,16 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
return null;
}
const scalarAction = getCompatibleScalarReadAction(typeInfo);
- const expr = scalarAction?.remoteNullable === true
- ? null
- : scalarAction
- ? compatibleScalarFieldReadExpr(
- scalarAction.remoteTypeId,
- scalarAction.localTypeId,
- this.builder,
- )
- : directNumericFieldReadExpr(typeInfo, this.builder);
+ const expr =
+ scalarAction?.remoteNullable === true
+ ? null
+ : scalarAction
+ ? compatibleScalarFieldReadExpr(
+ scalarAction.remoteTypeId,
+ scalarAction.localTypeId,
+ this.builder,
+ )
+ : directNumericFieldReadExpr(typeInfo, this.builder);
if (expr === null) {
return null;
}
@@ -917,10 +923,7 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
accessor: (expr: string) => string,
refState: string,
): string | null {
- if (
- this.typeInfo.options!.withConstructor
- || this.sortedProps.length === 0
- ) {
+ if (this.typeInfo.options!.withConstructor || this.sortedProps.length === 0) {
return null;
}
const fields = [];
@@ -945,7 +948,9 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
const byte = this.scope.uniqueName("byte");
const value = this.scope.uniqueName("value");
const result = this.scope.uniqueName("result");
- const reads = fields.map(({ local, kind }) => `
+ const reads = fields
+ .map(
+ ({ local, kind }) => `
if (${byteLength} - ${cursor} >= 5) {
${fourByteValue} = ${dataView}.getUint32(${cursor}, true);
${cursor}++;
@@ -986,7 +991,9 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
}
const ${local} = ${kind === "bigint" ? "BigInt(" : ""}(${value} >>> 1) ^ -(${value} & 1)${kind === "bigint" ? ")" : ""};
- `).join("\n");
+ `,
+ )
+ .join("\n");
return `
let ${cursor} = ${this.builder.reader.readGetCursor()};
const ${dataView} = ${this.builder.reader.getDataView()};
@@ -1021,7 +1028,7 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
const result = this.scope.uniqueName("result");
if (!this.typeInfo.options?.props || Object.keys(this.typeInfo.options.props).length === 0) {
return this.readTypeInfoThen(
- changedSerializer => `
+ (changedSerializer) => `
${assignStmt(`${changedSerializer}.read(${refState})`)};
`,
() => `
@@ -1035,25 +1042,25 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
if (this.isDepthFreeStruct()) {
return this.readTypeInfoThen(
- changedSerializer => `
+ (changedSerializer) => `
${assignStmt(`${changedSerializer}.read(${refState})`)};
`,
() => `
let ${result};
- ${this.read(v => `${result} = ${v}`, refState)};
+ ${this.read((v) => `${result} = ${v}`, refState)};
${assignStmt(result)};
`,
true,
);
}
return this.readTypeInfoThen(
- changedSerializer => `
+ (changedSerializer) => `
${assignStmt(`${changedSerializer}.read(${refState})`)};
`,
() => `
${this.builder.getReadContextName()}.incReadDepth();
let ${result};
- ${this.read(v => `${result} = ${v}`, refState)};
+ ${this.read((v) => `${result} = ${v}`, refState)};
${this.builder.getReadContextName()}.decReadDepth();
${assignStmt(result)};
`,
@@ -1102,12 +1109,8 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
case TypeId.NAMED_STRUCT:
if (!this.builder.resolver.isCompatible()) {
namesStmt = `
- ${
- this.builder.metaStringResolver.readNamespace()
- };
- ${
- this.builder.metaStringResolver.readTypeName()
- };
+ ${this.builder.metaStringResolver.readNamespace()};
+ ${this.builder.metaStringResolver.readTypeName()};
`;
} else {
typeMetaStmt = readCompatibleTypeMeta();
@@ -1120,16 +1123,10 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
break;
}
return `
- ${
- this.builder.reader.readUint8()
- };
+ ${this.builder.reader.readUint8()};
${readUserTypeIdStmt}
- ${
- namesStmt
- }
- ${
- typeMetaStmt
- }
+ ${namesStmt}
+ ${typeMetaStmt}
${typeMetaStmt && !metaChangedExits ? "" : unchangedStmt}
`;
}
@@ -1143,9 +1140,10 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
const builder = this.builder;
const internalTypeId = this.getInternalTypeId();
const serializer = builder.resolver.getSerializerByTypeInfo(this.typeInfo);
- const canInlineCompatibleTypeInfo = internalTypeId === TypeId.COMPATIBLE_STRUCT
- || internalTypeId === TypeId.NAMED_COMPATIBLE_STRUCT
- || (internalTypeId === TypeId.NAMED_STRUCT && builder.resolver.isCompatible());
+ const canInlineCompatibleTypeInfo =
+ internalTypeId === TypeId.COMPATIBLE_STRUCT ||
+ internalTypeId === TypeId.NAMED_COMPATIBLE_STRUCT ||
+ (internalTypeId === TypeId.NAMED_STRUCT && builder.resolver.isCompatible());
const canUseHeaderCacheFastPath = canInlineCompatibleTypeInfo && serializer?._initialized;
const inlineCompatibleTypeInfo = (
onMetaChanged: (changedSerializer: string) => string,
@@ -1174,14 +1172,16 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
`;
};
- return new Proxy({}, {
- get: (target, prop: string) => {
- if (prop === "readNoRef") {
- return (accessor: (expr: string) => string, refState: string) => {
- const result = scope.uniqueName("result");
- return `
+ return new Proxy(
+ {},
+ {
+ get: (target, prop: string) => {
+ if (prop === "readNoRef") {
+ return (accessor: (expr: string) => string, refState: string) => {
+ const result = scope.uniqueName("result");
+ return `
${inlineCompatibleTypeInfo(
- changedSerializer => `${accessor(`${changedSerializer}.read(${refState})`)};`,
+ (changedSerializer) => `${accessor(`${changedSerializer}.read(${refState})`)};`,
() => `
${builder.getReadContextName()}.incReadDepth();
let ${result} = ${hoisted}.read(${refState});
@@ -1190,13 +1190,13 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
`,
)}
`;
- };
- }
- if (prop === "readRef") {
- return (accessor: (expr: string) => string) => {
- const refFlag = scope.uniqueName("refFlag");
- const result = scope.uniqueName("result");
- return `
+ };
+ }
+ if (prop === "readRef") {
+ return (accessor: (expr: string) => string) => {
+ const refFlag = scope.uniqueName("refFlag");
+ const result = scope.uniqueName("result");
+ return `
const ${refFlag} = ${builder.reader.readInt8()};
let ${result};
if (${refFlag} === ${RefFlags.NullFlag}) {
@@ -1205,7 +1205,8 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
${result} = ${builder.referenceResolver.getReadRef(builder.reader.readVarUInt32())};
} else {
${inlineCompatibleTypeInfo(
- changedSerializer => `${result} = ${changedSerializer}.read(${refFlag} === ${RefFlags.RefValueFlag});`,
+ (changedSerializer) =>
+ `${result} = ${changedSerializer}.read(${refFlag} === ${RefFlags.RefValueFlag});`,
() => `
${builder.getReadContextName()}.incReadDepth();
${result} = ${hoisted}.read(${refFlag} === ${RefFlags.RefValueFlag});
@@ -1215,24 +1216,25 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
}
${accessor(result)};
`;
- };
- }
- if (prop === "readWithDepth") {
- return (accessor: (expr: string) => string, refState: string) => {
- const result = scope.uniqueName("result");
- return `
+ };
+ }
+ if (prop === "readWithDepth") {
+ return (accessor: (expr: string) => string, refState: string) => {
+ const result = scope.uniqueName("result");
+ return `
${builder.getReadContextName()}.incReadDepth();
let ${result} = ${hoisted}.read(${refState});
${builder.getReadContextName()}.decReadDepth();
${accessor(result)};
`;
+ };
+ }
+ return (accessor: (expr: string) => string, ...args: string[]) => {
+ return accessor(`${hoisted}.${prop}(${args.join(",")})`);
};
- }
- return (accessor: (expr: string) => string, ...args: string[]) => {
- return accessor(`${hoisted}.${prop}(${args.join(",")})`);
- };
+ },
},
- });
+ );
}
writeEmbed() {
@@ -1240,36 +1242,39 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
// the parent struct whose factory runs after child serializers exist.
const hoisted = this.scope.declare("ser", this.serializerExpr);
const scope = this.scope;
- return new Proxy({}, {
- get: (target, prop: string) => {
- if (prop === "writeNoRef") {
- return (accessor: string) => {
- return `
+ return new Proxy(
+ {},
+ {
+ get: (target, prop: string) => {
+ if (prop === "writeNoRef") {
+ return (accessor: string) => {
+ return `
${hoisted}.writeTypeInfo(${accessor});
${hoisted}.write(${accessor});
`;
- };
- }
- if (prop === "writeRef") {
- return (accessor: string) => {
- const noneedWrite = scope.uniqueName("noneedWrite");
- return `
+ };
+ }
+ if (prop === "writeRef") {
+ return (accessor: string) => {
+ const noneedWrite = scope.uniqueName("noneedWrite");
+ return `
let ${noneedWrite} = ${hoisted}.writeRefOrNull(${accessor});
if (!${noneedWrite}) {
${hoisted}.writeTypeInfo(${accessor});
${hoisted}.write(${accessor});
}
`;
- };
- }
- return (accessor: string, ...args: any) => {
- if (prop === "writeRefOrNull") {
- return args[0](`${hoisted}.${prop}(${accessor})`);
+ };
}
- return `${hoisted}.${prop}(${accessor})`;
- };
+ return (accessor: string, ...args: any) => {
+ if (prop === "writeRefOrNull") {
+ return args[0](`${hoisted}.${prop}(${accessor})`);
+ }
+ return `${hoisted}.${prop}(${accessor})`;
+ };
+ },
},
- });
+ );
}
writeTypeInfo(): string {
@@ -1291,15 +1296,28 @@ class StructSerializerGenerator extends BaseSerializerGenerator {
{
if (!this.builder.resolver.isCompatible()) {
const typeInfo = this.typeInfo;
- const nsBytes = this.scope.declare("nsBytes", this.builder.metaStringResolver.encodeNamespace(CodecBuilder.replaceBackslashAndQuote(typeInfo.namespace)));
- const typeNameBytes = this.scope.declare("typeNameBytes", this.builder.metaStringResolver.encodeTypeName(CodecBuilder.replaceBackslashAndQuote(typeInfo.typeName)));
+ const nsBytes = this.scope.declare(
+ "nsBytes",
+ this.builder.metaStringResolver.encodeNamespace(
+ CodecBuilder.replaceBackslashAndQuote(typeInfo.namespace),
+ ),
+ );
+ const typeNameBytes = this.scope.declare(
+ "typeNameBytes",
+ this.builder.metaStringResolver.encodeTypeName(
+ CodecBuilder.replaceBackslashAndQuote(typeInfo.typeName),
+ ),
+ );
typeMeta = `
${this.builder.metaStringResolver.writeBytes(nsBytes)}
${this.builder.metaStringResolver.writeBytes(typeNameBytes)}
`;
} else {
const bytes = this.typeMetaBytesExpr();
- typeMeta = this.builder.typeMetaResolver.writeTypeMeta(this.builder.getTypeInfo(), bytes);
+ typeMeta = this.builder.typeMetaResolver.writeTypeMeta(
+ this.builder.getTypeInfo(),
+ bytes,
+ );
}
}
break;
diff --git a/javascript/packages/core/lib/gen/typedArray.ts b/javascript/packages/core/lib/gen/typedArray.ts
index 562f31c63..cb905d670 100644
--- a/javascript/packages/core/lib/gen/typedArray.ts
+++ b/javascript/packages/core/lib/gen/typedArray.ts
@@ -25,11 +25,7 @@ import { Scope } from "./scope";
import { TypeId } from "../type";
import { BFloat16Array } from "../types/bfloat16";
import { BoolArray } from "../types/boolArray";
-import {
- createFloat16Array,
- createFloat16ArrayFromRaw,
- getFloat16Raw,
-} from "../types/float16";
+import { createFloat16Array, createFloat16ArrayFromRaw, getFloat16Raw } from "../types/float16";
const endianProbe = new Uint16Array([0x00ff]);
const IS_LITTLE_ENDIAN = new Uint8Array(endianProbe.buffer)[0] === 0xff;
@@ -394,10 +390,7 @@ CodegenRegistry.register(
build(Type.uint64(), `BigUint64Array`, 8, "readUint64", "writeUint64"),
);
CodegenRegistry.register(TypeId.FLOAT16_ARRAY, Float16ArraySerializerGenerator);
-CodegenRegistry.register(
- TypeId.BFLOAT16_ARRAY,
- BFloat16ArraySerializerGenerator,
-);
+CodegenRegistry.register(TypeId.BFLOAT16_ARRAY, BFloat16ArraySerializerGenerator);
CodegenRegistry.register(
TypeId.FLOAT32_ARRAY,
build(Type.float32(), `Float32Array`, 4, "readFloat32", "writeFloat32"),
diff --git a/javascript/packages/core/lib/gen/union.ts b/javascript/packages/core/lib/gen/union.ts
index c95bf1008..9799363cd 100644
--- a/javascript/packages/core/lib/gen/union.ts
+++ b/javascript/packages/core/lib/gen/union.ts
@@ -47,7 +47,9 @@ class UnionSerializerGenerator extends BaseSerializerGenerator {
const ti = caseTypeInfo as TypeInfo;
const isNamed = TypeId.isNamedType(ti._typeId);
const named = isNamed ? `"${ti.named}"` : "null";
- caseEntries.push(`${caseIdx}: { typeId: ${ti.typeId}, userTypeId: ${ti.userTypeId ?? -1}, named: ${named} }`);
+ caseEntries.push(
+ `${caseIdx}: { typeId: ${ti.typeId}, userTypeId: ${ti.userTypeId ?? -1}, named: ${named} }`,
+ );
this.caseGenerators.set(
caseIdx,
CodegenRegistry.newGeneratorByTypeInfo(ti, this.builder, this.scope),
@@ -115,11 +117,13 @@ class UnionSerializerGenerator extends BaseSerializerGenerator {
if (this.caseGenerators.size === 0) {
return this.writeDynamicCaseValue(unionValue, caseInfo);
}
- const caseStatements = Array.from(this.caseGenerators.entries()).map(([caseIdx, caseGenerator]) => `
+ const caseStatements = Array.from(this.caseGenerators.entries()).map(
+ ([caseIdx, caseGenerator]) => `
case ${caseIdx}:
${this.writeCaseValue(caseGenerator, unionValue)}
break;
- `);
+ `,
+ );
return `
if (${caseInfo}) {
switch (${caseIndex}) {
@@ -159,15 +163,22 @@ class UnionSerializerGenerator extends BaseSerializerGenerator {
`;
}
- private readDeclaredCases(caseIndex: string, unionValue: string, refFlag: string, caseInfo: string) {
+ private readDeclaredCases(
+ caseIndex: string,
+ unionValue: string,
+ refFlag: string,
+ caseInfo: string,
+ ) {
if (this.caseGenerators.size === 0) {
return this.readDynamicCaseValue(unionValue, refFlag);
}
- const caseStatements = Array.from(this.caseGenerators.entries()).map(([caseIdx, caseGenerator]) => `
+ const caseStatements = Array.from(this.caseGenerators.entries()).map(
+ ([caseIdx, caseGenerator]) => `
case ${caseIdx}:
${caseGenerator.readEmbed().readNoRef((v: string) => `${unionValue} = ${v}`, `${refFlag} === ${RefFlags.RefValueFlag}`)}
break;
- `);
+ `,
+ );
return `
const ${caseInfo} = ${this.caseTypesVar} ? ${this.caseTypesVar}[${caseIndex}] : null;
if (${caseInfo}) {
@@ -215,12 +226,28 @@ class UnionSerializerGenerator extends BaseSerializerGenerator {
break;
case TypeId.NAMED_UNION:
if (this.builder.resolver.isCompatible()) {
- const bytes = this.scope.declare("unionTypeInfoBytes", `new Uint8Array([${TypeMeta.fromTypeInfo(this.typeInfo).toBytes().join(",")}])`);
+ const bytes = this.scope.declare(
+ "unionTypeInfoBytes",
+ `new Uint8Array([${TypeMeta.fromTypeInfo(this.typeInfo).toBytes().join(",")}])`,
+ );
const serializerExpr = `${this.builder.getTypeResolverName()}.getSerializerByName("${CodecBuilder.replaceBackslashAndQuote(this.typeInfo.named!)}")`;
- typeMeta = this.builder.typeMetaResolver.writeTypeMeta(`${serializerExpr}.getTypeInfo()`, bytes);
+ typeMeta = this.builder.typeMetaResolver.writeTypeMeta(
+ `${serializerExpr}.getTypeInfo()`,
+ bytes,
+ );
} else {
- const nsBytes = this.scope.declare("unionNsBytes", this.builder.metaStringResolver.encodeNamespace(CodecBuilder.replaceBackslashAndQuote(this.typeInfo.namespace)));
- const typeNameBytes = this.scope.declare("unionTypeNameBytes", this.builder.metaStringResolver.encodeTypeName(CodecBuilder.replaceBackslashAndQuote(this.typeInfo.typeName)));
+ const nsBytes = this.scope.declare(
+ "unionNsBytes",
+ this.builder.metaStringResolver.encodeNamespace(
+ CodecBuilder.replaceBackslashAndQuote(this.typeInfo.namespace),
+ ),
+ );
+ const typeNameBytes = this.scope.declare(
+ "unionTypeNameBytes",
+ this.builder.metaStringResolver.encodeTypeName(
+ CodecBuilder.replaceBackslashAndQuote(this.typeInfo.typeName),
+ ),
+ );
typeMeta = `
${this.builder.metaStringResolver.writeBytes(nsBytes)}
${this.builder.metaStringResolver.writeBytes(typeNameBytes)}
diff --git a/javascript/packages/core/lib/meta/MetaString.ts b/javascript/packages/core/lib/meta/MetaString.ts
index eb30755d1..940b1aed8 100644
--- a/javascript/packages/core/lib/meta/MetaString.ts
+++ b/javascript/packages/core/lib/meta/MetaString.ts
@@ -44,7 +44,12 @@ export class MetaString {
* @param bytes The encoded string data as a byte array.
*/
public constructor(
- string: string, encoding: Encoding, specialChar1: string, specialChar2: string, bytes: Uint8Array) {
+ string: string,
+ encoding: Encoding,
+ specialChar1: string,
+ specialChar2: string,
+ bytes: Uint8Array,
+ ) {
this.string = string;
this.encoding = encoding;
this.specialChar1 = specialChar1;
@@ -119,18 +124,18 @@ export class MetaStringDecoder {
const stripLastChar = (data[0] & 0x80) != 0; // Check the first bit of the first byte
const bitMask = 0b11111; // 5 bits for the mask
let bitIndex = 1; // Start from the second bit
- while (bitIndex + 5 <= totalBits && !(stripLastChar && (bitIndex + 2 * 5 > totalBits))) {
+ while (bitIndex + 5 <= totalBits && !(stripLastChar && bitIndex + 2 * 5 > totalBits)) {
const byteIndex = Math.floor(bitIndex / 8);
const intraByteIndex = bitIndex % 8;
// Extract the 5-bit character value across byte boundaries if needed
let charValue;
if (intraByteIndex > 3) {
- charValue
- = ((data[byteIndex] & 0xFF) << 8)
- | (byteIndex + 1 < data.length ? (data[byteIndex + 1] & 0xFF) : 0);
- charValue = ((charValue >> (11 - intraByteIndex)) & bitMask);
+ charValue =
+ ((data[byteIndex] & 0xff) << 8) |
+ (byteIndex + 1 < data.length ? data[byteIndex + 1] & 0xff : 0);
+ charValue = (charValue >> (11 - intraByteIndex)) & bitMask;
} else {
- charValue = data[byteIndex] >> (3 - intraByteIndex) & bitMask;
+ charValue = (data[byteIndex] >> (3 - intraByteIndex)) & bitMask;
}
bitIndex += 5;
decoded.push(this.decodeLowerSpecialChar(charValue));
@@ -144,19 +149,19 @@ export class MetaStringDecoder {
const stripLastChar = (data[0] & 0x80) != 0; // Check the first bit of the first byte
const bitMask = 0b111111; // 6 bits for mask
const numBits = data.length * 8;
- while (bitIndex + 6 <= numBits && !(stripLastChar && (bitIndex + 2 * 6 > numBits))) {
+ while (bitIndex + 6 <= numBits && !(stripLastChar && bitIndex + 2 * 6 > numBits)) {
const byteIndex = Math.floor(bitIndex / 8);
const intraByteIndex = bitIndex % 8;
// Extract the 6-bit character value across byte boundaries if needed
let charValue;
if (intraByteIndex > 2) {
- charValue
- = ((data[byteIndex] & 0xFF) << 8)
- | (byteIndex + 1 < data.length ? (data[byteIndex + 1] & 0xFF) : 0);
- charValue = (((charValue >> (10 - intraByteIndex)) & bitMask));
+ charValue =
+ ((data[byteIndex] & 0xff) << 8) |
+ (byteIndex + 1 < data.length ? data[byteIndex + 1] & 0xff : 0);
+ charValue = (charValue >> (10 - intraByteIndex)) & bitMask;
} else {
- charValue = data[byteIndex] >> (2 - intraByteIndex) & bitMask;
+ charValue = (data[byteIndex] >> (2 - intraByteIndex)) & bitMask;
}
bitIndex += 6;
decoded.push(this.decodeLowerUpperDigitSpecialChar(charValue));
@@ -194,8 +199,7 @@ export class MetaStringDecoder {
} else if (charValue === 63) {
return this.specialChar2;
} else {
- throw new Error(
- "Invalid character value for LOWER_UPPER_DIGIT_SPECIAL: " + charValue);
+ throw new Error("Invalid character value for LOWER_UPPER_DIGIT_SPECIAL: " + charValue);
}
}
@@ -232,10 +236,8 @@ class StringStatistics {
public digitCount: number,
public upperCount: number,
public canLowerSpecialEncoded: boolean,
- public canLowerUpperDigitSpecialEncoded: boolean
- ) {
-
- }
+ public canLowerUpperDigitSpecialEncoded: boolean,
+ ) {}
}
/** Encodes plain text strings into MetaString objects with specified encoding mechanisms. */
@@ -262,7 +264,13 @@ export class MetaStringEncoder {
* @return A MetaString object representing the encoded string.
*/
public encode(input: string): MetaString {
- return this.encodeByEncodings(input, [Encoding.ALL_TO_LOWER_SPECIAL, Encoding.FIRST_TO_LOWER_SPECIAL, Encoding.LOWER_SPECIAL, Encoding.LOWER_UPPER_DIGIT_SPECIAL, Encoding.UTF_8]);
+ return this.encodeByEncodings(input, [
+ Encoding.ALL_TO_LOWER_SPECIAL,
+ Encoding.FIRST_TO_LOWER_SPECIAL,
+ Encoding.LOWER_SPECIAL,
+ Encoding.LOWER_UPPER_DIGIT_SPECIAL,
+ Encoding.UTF_8,
+ ]);
}
public isLatin1(str: string) {
@@ -271,7 +279,13 @@ export class MetaStringEncoder {
public encodeByEncodings(input: string, encodings: Encoding[]) {
if (!input) {
- return new MetaString(input, Encoding.UTF_8, this.specialChar1, this.specialChar2, new Uint8Array());
+ return new MetaString(
+ input,
+ Encoding.UTF_8,
+ this.specialChar1,
+ this.specialChar2,
+ new Uint8Array(),
+ );
}
if (!this.isLatin1(input)) {
return new MetaString(
@@ -279,7 +293,8 @@ export class MetaStringEncoder {
Encoding.UTF_8,
this.specialChar1,
this.specialChar2,
- new TextEncoder().encode(input));
+ new TextEncoder().encode(input),
+ );
}
const encoding = this.computeEncodingByEncodings(input, encodings);
return this.encodeByEncoding(input, encoding);
@@ -297,7 +312,13 @@ export class MetaStringEncoder {
throw new Error("Non-ASCII characters in meta string are not allowed");
}
if (!input) {
- return new MetaString(input, Encoding.UTF_8, this.specialChar1, this.specialChar2, new Uint8Array());
+ return new MetaString(
+ input,
+ Encoding.UTF_8,
+ this.specialChar1,
+ this.specialChar2,
+ new Uint8Array(),
+ );
}
let bytes: Uint8Array;
switch (encoding) {
@@ -310,8 +331,7 @@ export class MetaStringEncoder {
case Encoding.FIRST_TO_LOWER_SPECIAL:
bytes = this.encodeFirstToLowerSpecial([...input]);
return new MetaString(input, encoding, this.specialChar1, this.specialChar2, bytes);
- case Encoding.ALL_TO_LOWER_SPECIAL:
- {
+ case Encoding.ALL_TO_LOWER_SPECIAL: {
const chars = [...input];
const upperCount = this.countUppers(chars);
bytes = this.encodeAllToLowerSpecial(chars, upperCount);
@@ -324,7 +344,13 @@ export class MetaStringEncoder {
}
public computeEncoding(input: string) {
- return this.computeEncodingByEncodings(input, [Encoding.ALL_TO_LOWER_SPECIAL, Encoding.FIRST_TO_LOWER_SPECIAL, Encoding.LOWER_SPECIAL, Encoding.LOWER_UPPER_DIGIT_SPECIAL, Encoding.UTF_8]);
+ return this.computeEncodingByEncodings(input, [
+ Encoding.ALL_TO_LOWER_SPECIAL,
+ Encoding.FIRST_TO_LOWER_SPECIAL,
+ Encoding.LOWER_SPECIAL,
+ Encoding.LOWER_UPPER_DIGIT_SPECIAL,
+ Encoding.UTF_8,
+ ]);
}
public computeEncodingByEncodings(input: string, encodings: Encoding[]) {
@@ -353,7 +379,7 @@ export class MetaStringEncoder {
return Encoding.FIRST_TO_LOWER_SPECIAL;
}
}
- if ((chars.length + upperCount) * 5 < (chars.length * 6)) {
+ if ((chars.length + upperCount) * 5 < chars.length * 6) {
if (encodingSet.has(Encoding.ALL_TO_LOWER_SPECIAL)) {
return Encoding.ALL_TO_LOWER_SPECIAL;
}
@@ -392,16 +418,19 @@ export class MetaStringEncoder {
let upperCount = 0;
for (const c of chars) {
if (canLowerUpperDigitSpecialEncoded) {
- if (!((c >= "a" && c <= "z")
- || (c >= "A" && c <= "Z")
- || (c >= "0" && c <= "9")
- || (c === this.specialChar1 || c === this.specialChar2))) {
+ if (!(
+ (c >= "a" && c <= "z") ||
+ (c >= "A" && c <= "Z") ||
+ (c >= "0" && c <= "9") ||
+ c === this.specialChar1 ||
+ c === this.specialChar2
+ )) {
// Character outside of LOWER_UPPER_DIGIT_SPECIAL set
canLowerUpperDigitSpecialEncoded = false;
}
}
if (canLowerSpecialEncoded) {
- if (!((c >= "a" && c <= "z") || (c === "." || c === "_" || c === "$" || c === "|"))) {
+ if (!((c >= "a" && c <= "z") || c === "." || c === "_" || c === "$" || c === "|")) {
// Character outside of LOWER_SPECIAL set
canLowerSpecialEncoded = false;
}
@@ -414,7 +443,11 @@ export class MetaStringEncoder {
}
}
return new StringStatistics(
- digitCount, upperCount, canLowerSpecialEncoded, canLowerUpperDigitSpecialEncoded);
+ digitCount,
+ upperCount,
+ canLowerSpecialEncoded,
+ canLowerUpperDigitSpecialEncoded,
+ );
}
private countUppers(chars: string[]) {
@@ -460,22 +493,24 @@ export class MetaStringEncoder {
const bytes = new Uint8Array(byteLength).fill(0);
let currentBit = 1;
for (const c of chars) {
- const value
- = (bitsPerChar === 5) ? this.charToValueLowerSpecial(c) : this.charToValueLowerUpperDigitSpecial(c);
+ const value =
+ bitsPerChar === 5
+ ? this.charToValueLowerSpecial(c)
+ : this.charToValueLowerUpperDigitSpecial(c);
// Encode the value in bitsPerChar bits
for (let i = bitsPerChar - 1; i >= 0; i--) {
if ((value & (1 << i)) != 0) {
// Set the bit in the byte array
const bytePos = Math.floor(currentBit / 8);
const bitPos = currentBit % 8;
- bytes[bytePos] |= (1 << (7 - bitPos));
+ bytes[bytePos] |= 1 << (7 - bitPos);
}
currentBit++;
}
}
const stripLastChar = bytes.length * 8 >= totalBits + bitsPerChar;
if (stripLastChar) {
- bytes[0] = (bytes[0] | 0x80);
+ bytes[0] = bytes[0] | 0x80;
}
return bytes;
}
@@ -510,8 +545,7 @@ export class MetaStringEncoder {
} else if (c === this.specialChar2.charCodeAt(0)) {
return 63;
} else {
- throw new Error(
- "Unsupported character for LOWER_UPPER_DIGIT_SPECIAL encoding: " + c);
+ throw new Error("Unsupported character for LOWER_UPPER_DIGIT_SPECIAL encoding: " + c);
}
}
}
diff --git a/javascript/packages/core/lib/meta/TypeMeta.ts b/javascript/packages/core/lib/meta/TypeMeta.ts
index 00d4785c9..1d5be62f6 100644
--- a/javascript/packages/core/lib/meta/TypeMeta.ts
+++ b/javascript/packages/core/lib/meta/TypeMeta.ts
@@ -77,10 +77,8 @@ export const isPrimitiveTypeId = (typeId: number): boolean => {
export const refTrackingUnableTypeId = (typeId: number): boolean => {
return (
- PRIMITIVE_TYPE_IDS.includes(typeId as any)
- || [TypeId.DURATION, TypeId.DATE, TypeId.TIMESTAMP, TypeId.STRING].includes(
- typeId as any,
- )
+ PRIMITIVE_TYPE_IDS.includes(typeId as any) ||
+ [TypeId.DURATION, TypeId.DATE, TypeId.TIMESTAMP, TypeId.STRING].includes(typeId as any)
);
};
@@ -175,11 +173,7 @@ export class FieldInfo {
return this.fieldId;
}
- static writeTypeId(
- writer: BinaryWriter,
- typeInfo: InnerFieldInfo,
- writeFlags = false,
- ) {
+ static writeTypeId(writer: BinaryWriter, typeInfo: InnerFieldInfo, writeFlags = false) {
let { typeId } = typeInfo;
if (typeId === TypeId.NAMED_ENUM) {
typeId = TypeId.ENUM;
@@ -332,9 +326,7 @@ export class TypeMeta {
this.computeFieldTypeFingerprint(field, true, true),
]);
}
- fieldInfos = fieldInfos.sort((a, b) =>
- TypeMeta.compareFieldSortKey(a[0], b[0]),
- );
+ fieldInfos = fieldInfos.sort((a, b) => TypeMeta.compareFieldSortKey(a[0], b[0]));
let result = "";
for (const fieldInfo of fieldInfos) {
result += `${fieldInfo[1]},${fieldInfo[2]};`;
@@ -362,10 +354,10 @@ export class TypeMeta {
private fingerprintTypeId(typeId: number) {
if (
- TypeId.userDefinedType(typeId)
- || typeId === TypeId.UNION
- || typeId === TypeId.TYPED_UNION
- || typeId === TypeId.NAMED_UNION
+ TypeId.userDefinedType(typeId) ||
+ typeId === TypeId.UNION ||
+ typeId === TypeId.TYPED_UNION ||
+ typeId === TypeId.NAMED_UNION
) {
return TypeId.UNKNOWN;
}
@@ -386,48 +378,39 @@ export class TypeMeta {
if (TypeId.structType(typeInfo.typeId)) {
const structTypeInfo = typeInfo;
const usedFieldIds = new Set<number>();
- fieldInfo = Object.entries(structTypeInfo.options!.props!).map(
- ([fieldName, typeInfo]) => {
- let fieldTypeId = typeResolver
- ? typeResolver.computeTypeId(typeInfo)
- : typeInfo.typeId;
- if (fieldTypeId === TypeId.NAMED_ENUM) {
- fieldTypeId = TypeId.ENUM;
- } else if (
- fieldTypeId === TypeId.NAMED_UNION
- || fieldTypeId === TypeId.TYPED_UNION
- ) {
- fieldTypeId = TypeId.UNION;
- }
- const { trackingRef, nullable, id, userTypeId, options } = typeInfo;
- if (typeof id === "number" && id < 0) {
- throw new Error(`Field id for ${fieldName} must be non-negative`);
- }
- const fieldId = typeof id === "number" ? id : undefined;
- if (fieldId !== undefined) {
- if (usedFieldIds.has(fieldId)) {
- throw new Error(`Duplicate field id ${fieldId}`);
- }
- usedFieldIds.add(fieldId);
+ fieldInfo = Object.entries(structTypeInfo.options!.props!).map(([fieldName, typeInfo]) => {
+ let fieldTypeId = typeResolver ? typeResolver.computeTypeId(typeInfo) : typeInfo.typeId;
+ if (fieldTypeId === TypeId.NAMED_ENUM) {
+ fieldTypeId = TypeId.ENUM;
+ } else if (fieldTypeId === TypeId.NAMED_UNION || fieldTypeId === TypeId.TYPED_UNION) {
+ fieldTypeId = TypeId.UNION;
+ }
+ const { trackingRef, nullable, id, userTypeId, options } = typeInfo;
+ if (typeof id === "number" && id < 0) {
+ throw new Error(`Field id for ${fieldName} must be non-negative`);
+ }
+ const fieldId = typeof id === "number" ? id : undefined;
+ if (fieldId !== undefined) {
+ if (usedFieldIds.has(fieldId)) {
+ throw new Error(`Duplicate field id ${fieldId}`);
}
- return new FieldInfo(
- fieldName,
- fieldTypeId,
- userTypeId,
- trackingRef,
- nullable,
- options!,
- fieldId,
- );
- },
- );
+ usedFieldIds.add(fieldId);
+ }
+ return new FieldInfo(
+ fieldName,
+ fieldTypeId,
+ userTypeId,
+ trackingRef,
+ nullable,
+ options!,
+ fieldId,
+ );
+ });
}
fieldInfo = TypeMeta.groupFieldsByType(fieldInfo);
return new TypeMeta(fieldInfo, {
- typeId: typeResolver
- ? typeResolver.computeTypeId(typeInfo)
- : typeInfo.typeId,
+ typeId: typeResolver ? typeResolver.computeTypeId(typeInfo) : typeInfo.typeId,
namespace: typeInfo.namespace,
typeName: typeInfo.typeName,
userTypeId: typeInfo.userTypeId ?? -1,
@@ -499,9 +482,7 @@ export class TypeMeta {
registerByName = (classHeader & REGISTER_BY_NAME_FLAG) !== 0;
const compatible = (classHeader & COMPATIBLE_TYPEDEF_FLAG) !== 0;
if (registerByName) {
- typeId = compatible
- ? TypeId.NAMED_COMPATIBLE_STRUCT
- : TypeId.NAMED_STRUCT;
+ typeId = compatible ? TypeId.NAMED_COMPATIBLE_STRUCT : TypeId.NAMED_STRUCT;
} else {
typeId = compatible ? TypeId.COMPATIBLE_STRUCT : TypeId.STRUCT;
}
@@ -548,14 +529,9 @@ export class TypeMeta {
const consumed = reader.readGetCursor() - bodyStart;
if (consumed !== metaSize) {
- throw new Error(
- `unexpected TypeMeta body size: expected ${metaSize}, consumed ${consumed}`,
- );
+ throw new Error(`unexpected TypeMeta body size: expected ${metaSize}, consumed ${consumed}`);
}
- TypeMeta.validateParsedBodyHash(
- header,
- reader.bufferRefAt(bodyStart, metaSize),
- );
+ TypeMeta.validateParsedBodyHash(header, reader.bufferRefAt(bodyStart, metaSize));
return new TypeMeta(fields, typeInfo, headerHash, compressed);
}
@@ -570,16 +546,10 @@ export class TypeMeta {
}
private static readMetaSize(reader: BinaryReader, header: bigint): number {
- return TypeMeta.readMetaSizeFromLow(
- reader,
- Number(header & BigInt(META_SIZE_MASKS)),
- );
+ return TypeMeta.readMetaSizeFromLow(reader, Number(header & BigInt(META_SIZE_MASKS)));
}
- private static readMetaSizeFromLow(
- reader: BinaryReader,
- headerLow: number,
- ): number {
+ private static readMetaSizeFromLow(reader: BinaryReader, headerLow: number): number {
let metaSize = headerLow & META_SIZE_MASKS;
if (metaSize === META_SIZE_MASKS) {
metaSize += reader.readVarUInt32();
@@ -587,14 +557,11 @@ export class TypeMeta {
return metaSize;
}
- private static checkTypeMetaBytes(
- metaSize: number,
- maxTypeMetaBytes: number,
- ) {
+ private static checkTypeMetaBytes(metaSize: number, maxTypeMetaBytes: number) {
if (metaSize > maxTypeMetaBytes) {
throw new Error(
- `Type metadata body size ${metaSize} exceeds maxTypeMetaBytes ${maxTypeMetaBytes}. `
- + "The data may be malicious. If the data is not malicious, please increase maxTypeMetaBytes.",
+ `Type metadata body size ${metaSize} exceeds maxTypeMetaBytes ${maxTypeMetaBytes}. ` +
+ "The data may be malicious. If the data is not malicious, please increase maxTypeMetaBytes.",
);
}
}
@@ -602,17 +569,14 @@ export class TypeMeta {
private static checkTypeFields(numFields: number, maxTypeFields: number) {
if (numFields > maxTypeFields) {
throw new Error(
- `Type metadata field count ${numFields} exceeds maxTypeFields ${maxTypeFields}. `
- + "The data may be malicious. If the data is not malicious, please increase maxTypeFields.",
+ `Type metadata field count ${numFields} exceeds maxTypeFields ${maxTypeFields}. ` +
+ "The data may be malicious. If the data is not malicious, please increase maxTypeFields.",
);
}
}
private static validateParsedBodyHash(header: bigint, body: Uint8Array) {
- const expectedHeaderHash = TypeMeta.headerHashBits(
- body,
- header & ~HEADER_HASH_MASK,
- );
+ const expectedHeaderHash = TypeMeta.headerHashBits(body, header & ~HEADER_HASH_MASK);
const actualHeaderHash = header & HEADER_HASH_MASK;
if (expectedHeaderHash !== actualHeaderHash) {
throw new Error("TypeMeta metadata hash mismatch");
@@ -642,34 +606,16 @@ export class TypeMeta {
// Read field name
const encoding = FieldInfo.u8ToEncoding(encodingFlags);
- fieldName = fieldDecoder.decode(
- reader,
- size + 1,
- encoding || Encoding.UTF_8,
- );
+ fieldName = fieldDecoder.decode(reader, size + 1, encoding || Encoding.UTF_8);
fieldName = TypeMeta.lowerUnderscoreToLowerCamelCase(fieldName);
}
- return new FieldInfo(
- fieldName,
- typeId,
- userTypeId,
- trackingRef,
- nullable,
- options,
- fieldId,
- );
+ return new FieldInfo(fieldName, typeId, userTypeId, trackingRef, nullable, options, fieldId);
}
- private static readTypeId(
- reader: BinaryReader,
- readFlag = false,
- depth = 0,
- ): InnerFieldInfo {
+ private static readTypeId(reader: BinaryReader, readFlag = false, depth = 0): InnerFieldInfo {
if (depth > MAX_TYPE_META_NESTING) {
- throw new Error(
- `TypeMeta nesting depth limit exceeded: ${depth} > ${MAX_TYPE_META_NESTING}`,
- );
+ throw new Error(`TypeMeta nesting depth limit exceeded: ${depth} > ${MAX_TYPE_META_NESTING}`);
}
const options: InnerFieldInfoOptions = {};
let nullable = false;
@@ -681,10 +627,7 @@ export class TypeMeta {
typeId = typeId >> 2;
if (typeId === TypeId.NAMED_ENUM) {
typeId = TypeId.ENUM;
- } else if (
- typeId === TypeId.NAMED_UNION
- || typeId === TypeId.TYPED_UNION
- ) {
+ } else if (typeId === TypeId.NAMED_UNION || typeId === TypeId.TYPED_UNION) {
typeId = TypeId.UNION;
}
this.readNestedTypeInfo(reader, typeId, options, depth);
@@ -767,9 +710,7 @@ export class TypeMeta {
return this.fields;
}
- remapFieldNames(
- localProps: Record<string, TypeInfo> | undefined,
- ): FieldInfo[] {
+ remapFieldNames(localProps: Record<string, TypeInfo> | undefined): FieldInfo[] {
if (!localProps) {
return this.fields;
}
@@ -832,19 +773,16 @@ export class TypeMeta {
writer.writeUint8(-1); // placeholder for header, update later
const isStruct = TypeId.structType(this.type.typeId);
if (!isStruct && this.fields.length !== 0) {
- throw new Error(
- `non-struct TypeMeta ${this.type.typeId} cannot carry field metadata`,
- );
+ throw new Error(`non-struct TypeMeta ${this.type.typeId} cannot carry field metadata`);
}
let currentClassHeader: number;
if (isStruct) {
- currentClassHeader
- = STRUCT_TYPEDEF_FLAG
- | Math.min(this.fields.length, SMALL_NUM_FIELDS_THRESHOLD);
+ currentClassHeader =
+ STRUCT_TYPEDEF_FLAG | Math.min(this.fields.length, SMALL_NUM_FIELDS_THRESHOLD);
if (
- this.type.typeId === TypeId.COMPATIBLE_STRUCT
- || this.type.typeId === TypeId.NAMED_COMPATIBLE_STRUCT
+ this.type.typeId === TypeId.COMPATIBLE_STRUCT ||
+ this.type.typeId === TypeId.NAMED_COMPATIBLE_STRUCT
) {
currentClassHeader |= COMPATIBLE_TYPEDEF_FLAG;
}
@@ -892,10 +830,7 @@ export class TypeMeta {
}
writeTypeName(writer: BinaryWriter, typeName: string) {
- const metaString = typeNameEncoder.encodeByEncodings(
- typeName,
- typeNameEncoding,
- );
+ const metaString = typeNameEncoder.encodeByEncodings(typeName, typeNameEncoding);
const encoded = metaString.getBytes();
const encoding = metaString.getEncoding();
this.writeName(writer, encoded, typeNameEncoding.indexOf(encoding));
@@ -936,13 +871,8 @@ export class TypeMeta {
encodingFlags = 3; // TAG_ID encoding
} else {
// Convert camelCase to snake_case for xlang compatibility
- const fieldName = TypeMeta.lowerCamelToLowerUnderscore(
- fieldInfo.getFieldName(),
- );
- const metaString = fieldEncoder.encodeByEncodings(
- fieldName,
- fieldNameEncoding,
- );
+ const fieldName = TypeMeta.lowerCamelToLowerUnderscore(fieldInfo.getFieldName());
+ const metaString = fieldEncoder.encodeByEncodings(fieldName, fieldNameEncoding);
encodingFlags = fieldNameEncoding.indexOf(metaString.getEncoding());
encoded = metaString.getBytes();
size = encoded.length - 1;
@@ -1032,8 +962,7 @@ export class TypeMeta {
if (isCompressed) {
headerLowBits |= COMPRESS_META_FLAG;
}
- const header
- = TypeMeta.headerHashBits(buffer, headerLowBits) | headerLowBits;
+ const header = TypeMeta.headerHashBits(buffer, headerLowBits) | headerLowBits;
return {
header: BigInt.asUintN(64, header),
headerHash: Number(header >> HASH_SHIFT_BITS),
@@ -1055,10 +984,7 @@ export class TypeMeta {
// is set -- unsigned BigInt can't go negative, so its sign-check
// is always false and the abs is a no-op. Signed int64 here
// matches the canonical behaviour of the other xlang bindings.
- let header = BigInt.asIntN(
- 64,
- hash.getBigInt64(0, false) << HASH_SHIFT_BITS,
- );
+ let header = BigInt.asIntN(64, hash.getBigInt64(0, false) << HASH_SHIFT_BITS);
if (header < 0n) {
header = -header;
}
@@ -1090,9 +1016,8 @@ export class TypeMeta {
if (c >= "A" && c <= "Z") {
if (i > 0) {
const prevUpper = chars[i - 1] >= "A" && chars[i - 1] <= "Z";
- const nextUpperOrEnd
- = i + 1 >= chars.length
- || (chars[i + 1] >= "A" && chars[i + 1] <= "Z");
+ const nextUpperOrEnd =
+ i + 1 >= chars.length || (chars[i + 1] >= "A" && chars[i + 1] <= "Z");
if (!prevUpper || !nextUpperOrEnd) {
result.push("_");
@@ -1125,12 +1050,12 @@ export class TypeMeta {
b: { fieldName: string; fieldId?: number },
) {
if (
- a.fieldId !== undefined
- && a.fieldId !== null
- && a.fieldId >= 0
- && b.fieldId !== undefined
- && b.fieldId !== null
- && b.fieldId >= 0
+ a.fieldId !== undefined &&
+ a.fieldId !== null &&
+ a.fieldId >= 0 &&
+ b.fieldId !== undefined &&
+ b.fieldId !== null &&
+ b.fieldId >= 0
) {
return a.fieldId - b.fieldId;
}
@@ -1140,10 +1065,7 @@ export class TypeMeta {
if (b.fieldId !== undefined && b.fieldId !== null && b.fieldId >= 0) {
return 1;
}
- return TypeMeta.compareOrdinal(
- TypeMeta.getFieldSortKey(a),
- TypeMeta.getFieldSortKey(b),
- );
+ return TypeMeta.compareOrdinal(TypeMeta.getFieldSortKey(a), TypeMeta.getFieldSortKey(b));
}
static groupFieldsByType<
@@ -1210,10 +1132,6 @@ export class TypeMeta {
nullablePrimitiveFields.sort(primitiveComparator);
nonPrimitiveFields.sort(nameSorter);
- return [
- primitiveFields,
- nullablePrimitiveFields,
- nonPrimitiveFields,
- ].flat();
+ return [primitiveFields, nullablePrimitiveFields, nonPrimitiveFields].flat();
}
}
diff --git a/javascript/packages/core/lib/murmurHash3.ts b/javascript/packages/core/lib/murmurHash3.ts
index b08c07508..01879aaa7 100644
--- a/javascript/packages/core/lib/murmurHash3.ts
+++ b/javascript/packages/core/lib/murmurHash3.ts
@@ -7,13 +7,11 @@
* +----------------------------------------------------------------------------------+
*/
-
-type Brand<Name, Type> = Type & {_type?: Name};
-export type u32 = Brand<'u32', number>;
-export type u64 = Brand<'u64', [u32, u32]>;
+type Brand<Name, Type> = Type & { _type?: Name };
+export type u32 = Brand<"u32", number>;
+export type u64 = Brand<"u64", [u32, u32]>;
// 16bit chunks in big endian as u32s to allow carrying of overflows.
-type u64spill = Brand<'u64spill', [u32, u32, u32, u32]>;
-
+type u64spill = Brand<"u64spill", [u32, u32, u32, u32]>;
const hexLUT = Array.from({ length: 256 }, (_, i) => `00${i.toString(16)}`.slice(-2));
@@ -22,31 +20,30 @@ export function bufToHex(buf: Uint8Array = new Uint8Array(0)): string {
for (let i = 0; i < buf.byteLength; i++) {
str += hexLUT[buf[i]];
}
-
+
return str;
}
-
function add64(m: u64, n: u64): u64 {
const ms: u64spill = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];
const ns: u64spill = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];
const os: u64spill = [0x0, 0x0, 0x0, 0x0];
-
+
os[3] += ms[3] + ns[3];
os[2] += os[3] >>> 16;
os[3] &= 0xffff;
-
+
os[2] += ms[2] + ns[2];
os[1] += os[2] >>> 16;
os[2] &= 0xffff;
-
+
os[1] += ms[1] + ns[1];
os[0] += os[1] >>> 16;
os[1] &= 0xffff;
-
+
os[0] += ms[0] + ns[0];
os[0] &= 0xffff;
-
+
return [(os[0] << 16) | os[1], (os[2] << 16) | os[3]];
}
@@ -54,60 +51,54 @@ function mul64(m: u64, n: u64): u64 {
const ms: u64spill = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];
const ns: u64spill = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];
const os: u64spill = [0x0, 0x0, 0x0, 0x0];
-
+
os[3] += ms[3] * ns[3];
os[2] += os[3] >>> 16;
os[3] &= 0xffff;
-
+
os[2] += ms[2] * ns[3];
os[1] += os[2] >>> 16;
os[2] &= 0xffff;
-
+
os[2] += ms[3] * ns[2];
os[1] += os[2] >>> 16;
os[2] &= 0xffff;
-
+
os[1] += ms[1] * ns[3];
os[0] += os[1] >>> 16;
os[1] &= 0xffff;
-
+
os[1] += ms[2] * ns[2];
os[0] += os[1] >>> 16;
os[1] &= 0xffff;
-
+
os[1] += ms[3] * ns[1];
os[0] += os[1] >>> 16;
os[1] &= 0xffff;
-
- os[0] += (ms[0] * ns[3]) + (ms[1] * ns[2]) + (ms[2] * ns[1]) + (ms[3] * ns[0]);
+
+ os[0] += ms[0] * ns[3] + ms[1] * ns[2] + ms[2] * ns[1] + ms[3] * ns[0];
os[0] &= 0xffff;
-
+
return [(os[0] << 16) | os[1], (os[2] << 16) | os[3]];
}
function rol64(n: u64, r: number): u64 {
r %= 64;
-
+
// istanbul ignore if: here for completeness but never used.
if (r === 32) {
return [n[1], n[0]];
} else if (r < 32) {
- return [
- (n[0] << r) | (n[1] >>> (32 - r)),
- (n[1] << r) | (n[0] >>> (32 - r)),
- ];
+ return [(n[0] << r) | (n[1] >>> (32 - r)), (n[1] << r) | (n[0] >>> (32 - r))];
} else {
r -= 32;
- return [
- (n[1] << r) | (n[0] >>> (32 - r)),
- (n[0] << r) | (n[1] >>> (32 - r)),
- ];
+ return [(n[1] << r) | (n[0] >>> (32 - r)), (n[0] << r) | (n[1] >>> (32 - r))];
}
}
function shl64(n: u64, s: number): u64 {
s %= 64;
-
+
// istanbul ignore if: here for completeness but never used.
if (s === 0) {
return n;
@@ -122,16 +113,12 @@ function xor64(a: u64, b: u64): u64 {
return [a[0] ^ b[0], a[1] ^ b[1]];
}
-
-
-
export type x86hash32State = {
- h1: u32,
- len: number,
- rem: Uint8Array,
+ h1: u32;
+ len: number;
+ rem: Uint8Array;
};
-
function x64fmix64(h: u64): u64 {
// [0x0, h[0] >>> 1] is a 33 bit shr.
h = xor64(h, [0x0, h[0] >>> 1]);
@@ -139,11 +126,10 @@ function x64fmix64(h: u64): u64 {
h = xor64(h, [0x0, h[0] >>> 1]);
h = mul64(h, [0xc4ceb9fe, 0x1a85ec53]);
h = xor64(h, [0x0, h[0] >>> 1]);
-
+
return h;
}
-
const x64hash128c1: u64 = [0x87c37b91, 0x114253d5];
const x64hash128c2: u64 = [0x4cf5ad43, 0x2745937f];
@@ -152,41 +138,36 @@ function x64mix128(h1: u64, h2: u64, k1: u64, k2: u64): [u64, u64] {
k1 = rol64(k1, 31);
k1 = mul64(k1, x64hash128c2);
h1 = xor64(h1, k1);
-
+
h1 = rol64(h1, 27);
h1 = add64(h1, h2);
h1 = add64(mul64(h1, [0x0, 5]), [0x0, 0x52dce729]);
-
+
k2 = mul64(k2, x64hash128c2);
k2 = rol64(k2, 33);
k2 = mul64(k2, x64hash128c1);
h2 = xor64(h2, k2);
-
+
h2 = rol64(h2, 31);
h2 = add64(h2, h1);
h2 = add64(mul64(h2, [0x0, 5]), [0x0, 0x38495ab5]);
-
+
return [h1, h2];
}
export type x64hash128State = {
- h1: u64,
- h2: u64,
- len: number,
- rem: Uint8Array,
+ h1: u64;
+ h2: u64;
+ len: number;
+ rem: Uint8Array;
};
-
-
-export function x64hash128(
- buf: Uint8Array = new Uint8Array(0),
- state: u32 = 0x0,
-): DataView {
+export function x64hash128(buf: Uint8Array = new Uint8Array(0), state: u32 = 0x0): DataView {
let h1: u64;
let h2: u64;
let i: number;
let len: number;
- if (typeof state === 'number') {
+ if (typeof state === "number") {
h1 = [0x0, state];
h2 = [0x0, state];
i = 0;
@@ -194,20 +175,21 @@ export function x64hash128(
} else {
({ h1, h2, len } = state as x64hash128State);
const rem = (state as x64hash128State).rem;
-
+
if (rem.byteLength === 0) {
i = 0;
} else if (rem.byteLength + buf.byteLength >= 16) {
len += 16;
i = 16 - rem.byteLength;
-
+
const blk = new Uint8Array(16);
const dtv = new DataView(blk.buffer);
blk.set(rem);
blk.set(buf.subarray(0, i), rem.byteLength);
-
+
[h1, h2] = x64mix128(
- h1, h2,
+ h1,
+ h2,
[dtv.getUint32(4, true), dtv.getUint32(0, true)],
[dtv.getUint32(12, true), dtv.getUint32(8, true)],
);
@@ -219,45 +201,59 @@ export function x64hash128(
i = 0;
}
}
-
+
const dtv = new DataView(buf.buffer, buf.byteOffset);
const remainder = (buf.byteLength - i) % 16;
const bytes = buf.byteLength - i - remainder;
len += bytes;
-
+
for (; i < bytes; i += 16) {
[h1, h2] = x64mix128(
- h1, h2,
+ h1,
+ h2,
[dtv.getUint32(i + 4, true), dtv.getUint32(i, true)],
[dtv.getUint32(i + 12, true), dtv.getUint32(i + 8, true)],
);
}
-
+
{
len += remainder;
let k1: u64 = [0x0, 0x0];
let k2: u64 = [0x0, 0x0];
-
+
switch (remainder) {
- case 15: k2 = xor64(k2, shl64([0x0, buf[i + 14]], 48));
- case 14: k2 = xor64(k2, shl64([0x0, buf[i + 13]], 40));
- case 13: k2 = xor64(k2, shl64([0x0, buf[i + 12]], 32));
- case 12: k2 = xor64(k2, shl64([0x0, buf[i + 11]], 24));
- case 11: k2 = xor64(k2, shl64([0x0, buf[i + 10]], 16));
- case 10: k2 = xor64(k2, shl64([0x0, buf[i + 9]], 8));
+ case 15:
+ k2 = xor64(k2, shl64([0x0, buf[i + 14]], 48));
+ case 14:
+ k2 = xor64(k2, shl64([0x0, buf[i + 13]], 40));
+ case 13:
+ k2 = xor64(k2, shl64([0x0, buf[i + 12]], 32));
+ case 12:
+ k2 = xor64(k2, shl64([0x0, buf[i + 11]], 24));
+ case 11:
+ k2 = xor64(k2, shl64([0x0, buf[i + 10]], 16));
+ case 10:
+ k2 = xor64(k2, shl64([0x0, buf[i + 9]], 8));
case 9:
k2 = xor64(k2, [0x0, buf[i + 8]]);
k2 = mul64(k2, x64hash128c2);
k2 = rol64(k2, 33);
k2 = mul64(k2, x64hash128c1);
h2 = xor64(h2, k2);
- case 8: k1 = xor64(k1, shl64([0x0, buf[i + 7]], 56));
- case 7: k1 = xor64(k1, shl64([0x0, buf[i + 6]], 48));
- case 6: k1 = xor64(k1, shl64([0x0, buf[i + 5]], 40));
- case 5: k1 = xor64(k1, shl64([0x0, buf[i + 4]], 32));
- case 4: k1 = xor64(k1, shl64([0x0, buf[i + 3]], 24));
- case 3: k1 = xor64(k1, shl64([0x0, buf[i + 2]], 16));
- case 2: k1 = xor64(k1, shl64([0x0, buf[i + 1]], 8));
+ case 8:
+ k1 = xor64(k1, shl64([0x0, buf[i + 7]], 56));
+ case 7:
+ k1 = xor64(k1, shl64([0x0, buf[i + 6]], 48));
+ case 6:
+ k1 = xor64(k1, shl64([0x0, buf[i + 5]], 40));
+ case 5:
+ k1 = xor64(k1, shl64([0x0, buf[i + 4]], 32));
+ case 4:
+ k1 = xor64(k1, shl64([0x0, buf[i + 3]], 24));
+ case 3:
+ k1 = xor64(k1, shl64([0x0, buf[i + 2]], 16));
+ case 2:
+ k1 = xor64(k1, shl64([0x0, buf[i + 1]], 8));
case 1:
k1 = xor64(k1, [0x0, buf[i]]);
k1 = mul64(k1, x64hash128c1);
@@ -265,25 +261,25 @@ export function x64hash128(
k1 = mul64(k1, x64hash128c2);
h1 = xor64(h1, k1);
}
-
+
h1 = xor64(h1, [0x0, len & 0xffffffff]);
h2 = xor64(h2, [0x0, len & 0xffffffff]);
-
+
h1 = add64(h1, h2);
h2 = add64(h2, h1);
-
+
h1 = x64fmix64(h1);
h2 = x64fmix64(h2);
-
+
h1 = add64(h1, h2);
h2 = add64(h2, h1);
-
+
const hash = new DataView(new ArrayBuffer(16));
hash.setUint32(0, h1[0], false);
hash.setUint32(4, h1[1], false);
hash.setUint32(8, h2[0], false);
hash.setUint32(12, h2[1], false);
-
+
return hash;
}
}
diff --git a/javascript/packages/core/lib/platformBuffer.ts b/javascript/packages/core/lib/platformBuffer.ts
index 2cecadacd..d2c523cf4 100644
--- a/javascript/packages/core/lib/platformBuffer.ts
+++ b/javascript/packages/core/lib/platformBuffer.ts
@@ -48,8 +48,8 @@ export class BrowserBuffer extends Uint8Array implements PlatformBuffer {
private ucs2Write(string: string, offset: number): void {
for (let i = 0; i < string.length; i++) {
const codePoint = string.charCodeAt(i);
- this[offset++] = codePoint & 0xFF;
- this[offset++] = (codePoint >> 8) & 0xFF;
+ this[offset++] = codePoint & 0xff;
+ this[offset++] = (codePoint >> 8) & 0xff;
}
}
@@ -115,15 +115,12 @@ export class BrowserBuffer extends Uint8Array implements PlatformBuffer {
let c = 0;
for (let i = 0; i < str.length; ++i) {
c = str.charCodeAt(i);
- if (c < 128)
- len += 1;
- else if (c < 2048)
- len += 2;
- else if ((c & 0xFC00) === 0xD800 && (str.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
+ if (c < 128) len += 1;
+ else if (c < 2048) len += 2;
+ else if ((c & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
++i;
len += 4;
- } else
- len += 3;
+ } else len += 3;
}
return len;
}
@@ -134,19 +131,20 @@ export const fromUint8Array = hasBuffer
if (!Buffer.isBuffer(ab)) {
// https://nodejs.org/docs/latest/api/buffer.html#static-method-bufferfromarraybuffer-byteoffset-length
// Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
- return (Buffer.from(ab.buffer, ab.byteOffset, ab.byteLength) as unknown as PlatformBuffer);
+ return Buffer.from(ab.buffer, ab.byteOffset, ab.byteLength) as unknown as PlatformBuffer;
} else {
return ab as unknown as PlatformBuffer;
}
}
: (ab: Buffer | Uint8Array) => new BrowserBuffer(ab);
-export const alloc = (hasBuffer ? Buffer.allocUnsafe : BrowserBuffer.alloc) as unknown as (size: number) => PlatformBuffer;
+export const alloc = (hasBuffer ? Buffer.allocUnsafe : BrowserBuffer.alloc) as unknown as (
+ size: number,
+) => PlatformBuffer;
export const strByteLength = hasBuffer ? Buffer.byteLength : BrowserBuffer.byteLength;
-export const fromString
-= hasBuffer
+export const fromString = hasBuffer
? (str: string) => Buffer.from(str) as unknown as PlatformBuffer
: (str: string) => {
return new BrowserBuffer(utf8Encoder.encode(str));
diff --git a/javascript/packages/core/lib/reader/index.ts b/javascript/packages/core/lib/reader/index.ts
index d39acd693..94282c24f 100644
--- a/javascript/packages/core/lib/reader/index.ts
+++ b/javascript/packages/core/lib/reader/index.ts
@@ -44,24 +44,16 @@ export class BinaryReader {
// Reuse DataView when the underlying ArrayBuffer, byteOffset, and byteLength are unchanged.
const buf = this.platformBuffer.buffer;
if (
- buf !== this.cachedArrayBuffer
- || !this.dataView
- || this.dataView.byteOffset !== this.platformBuffer.byteOffset
- || this.dataView.byteLength !== this.byteLength
+ buf !== this.cachedArrayBuffer ||
+ !this.dataView ||
+ this.dataView.byteOffset !== this.platformBuffer.byteOffset ||
+ this.dataView.byteLength !== this.byteLength
) {
- this.dataView = new DataView(
- buf,
- this.platformBuffer.byteOffset,
- this.byteLength,
- );
+ this.dataView = new DataView(buf, this.platformBuffer.byteOffset, this.byteLength);
this.cachedArrayBuffer = buf;
}
if (this.sliceStringEnable) {
- this.bigString = this.platformBuffer.toString(
- "latin1",
- 0,
- this.byteLength,
- );
+ this.bigString = this.platformBuffer.toString("latin1", 0, this.byteLength);
}
this.cursor = 0;
}
@@ -224,11 +216,7 @@ export class BinaryReader {
if ((len & 1) !== 0) {
throw new Error("UTF-16LE string length must be even");
}
- const result = this.platformBuffer.toString(
- "utf16le",
- this.cursor,
- this.cursor + len,
- );
+ const result = this.platformBuffer.toString("utf16le", this.cursor, this.cursor + len);
this.cursor += len;
return result;
}
@@ -378,11 +366,7 @@ export class BinaryReader {
}
}
- private continueReadVarUint32(
- readIdx: number,
- bulkRead: number,
- value: number,
- ): number {
+ private continueReadVarUint32(readIdx: number, bulkRead: number, value: number): number {
readIdx++;
value |= (bulkRead >>> 2) & 0x1fc000;
if ((bulkRead & 0x800000) !== 0) {
@@ -422,11 +406,7 @@ export class BinaryReader {
}
}
- private continueReadVarUint36(
- readIdx: number,
- fourByteValue: number,
- result: number,
- ): number {
+ private continueReadVarUint36(readIdx: number, fourByteValue: number, result: number): number {
readIdx++;
result |= (fourByteValue >>> 2) & 0x1fc000;
if ((fourByteValue & 0x800000) !== 0) {
diff --git a/javascript/packages/core/lib/reader/string.ts b/javascript/packages/core/lib/reader/string.ts
index c8bc4869c..06c70e8bd 100644
--- a/javascript/packages/core/lib/reader/string.ts
+++ b/javascript/packages/core/lib/reader/string.ts
@@ -29,40 +29,166 @@ const read3 = (buffer: Uint8Array, cursor: number) => {
return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2]);
};
const read4 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ );
};
const read5 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ );
};
const read6 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ );
};
const read7 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ );
};
const read8 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ );
};
const read9 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ );
};
const read10 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8], buffer[cursor + 9]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ buffer[cursor + 9],
+ );
};
const read11 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8], buffer[cursor + 9], buffer[cursor + 10]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ buffer[cursor + 9],
+ buffer[cursor + 10],
+ );
};
const read12 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8], buffer[cursor + 9], buffer[cursor + 10], buffer[cursor + 11]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ buffer[cursor + 9],
+ buffer[cursor + 10],
+ buffer[cursor + 11],
+ );
};
const read13 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8], buffer[cursor + 9], buffer[cursor + 10], buffer[cursor + 11], buffer[cursor + 12]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ buffer[cursor + 9],
+ buffer[cursor + 10],
+ buffer[cursor + 11],
+ buffer[cursor + 12],
+ );
};
const read14 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8], buffer[cursor + 9], buffer[cursor + 10], buffer[cursor + 11], buffer[cursor + 12], buffer[cursor + 13]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ buffer[cursor + 9],
+ buffer[cursor + 10],
+ buffer[cursor + 11],
+ buffer[cursor + 12],
+ buffer[cursor + 13],
+ );
};
const read15 = (buffer: Uint8Array, cursor: number) => {
- return String.fromCharCode(buffer[cursor], buffer[cursor + 1], buffer[cursor + 2], buffer[cursor + 3], buffer[cursor + 4], buffer[cursor + 5], buffer[cursor + 6], buffer[cursor + 7], buffer[cursor + 8], buffer[cursor + 9], buffer[cursor + 10], buffer[cursor + 11], buffer[cursor + 12], buffer[cursor + 13], buffer[cursor + 14]);
+ return String.fromCharCode(
+ buffer[cursor],
+ buffer[cursor + 1],
+ buffer[cursor + 2],
+ buffer[cursor + 3],
+ buffer[cursor + 4],
+ buffer[cursor + 5],
+ buffer[cursor + 6],
+ buffer[cursor + 7],
+ buffer[cursor + 8],
+ buffer[cursor + 9],
+ buffer[cursor + 10],
+ buffer[cursor + 11],
+ buffer[cursor + 12],
+ buffer[cursor + 13],
+ buffer[cursor + 14],
+ );
};
export const readLatin1String = (buffer: PlatformBuffer, len: number, cursor: number) => {
@@ -100,6 +226,6 @@ export const readLatin1String = (buffer: PlatformBuffer, len: number, cursor: nu
case 15:
return read15(buffer, cursor);
default:
- return buffer.toString("latin1", cursor, cursor + len,);
+ return buffer.toString("latin1", cursor, cursor + len);
}
};
diff --git a/javascript/packages/core/lib/type.ts b/javascript/packages/core/lib/type.ts
index bfb4a942f..ddbef54ec 100644
--- a/javascript/packages/core/lib/type.ts
+++ b/javascript/packages/core/lib/type.ts
@@ -174,12 +174,12 @@ export const TypeId = {
},
userDefinedType(id: number) {
return (
- this.structType(id)
- || this.extType(id)
- || this.enumType(id)
- || id == TypeId.UNION
- || id == TypeId.TYPED_UNION
- || id == TypeId.NAMED_UNION
+ this.structType(id) ||
+ this.extType(id) ||
+ this.enumType(id) ||
+ id == TypeId.UNION ||
+ id == TypeId.TYPED_UNION ||
+ id == TypeId.NAMED_UNION
);
},
isBuiltin(id: number) {
@@ -216,8 +216,7 @@ export const TypeId = {
// NONE(36), DURATION(37), TIMESTAMP(38), DATE(39), DECIMAL(40), BINARY(41)
if (typeId >= TypeId.NONE && typeId <= TypeId.BINARY) return true;
// Typed arrays BOOL_ARRAY(43)..FLOAT64_ARRAY(56)
- if (typeId >= TypeId.BOOL_ARRAY && typeId <= TypeId.FLOAT64_ARRAY)
- return true;
+ if (typeId >= TypeId.BOOL_ARRAY && typeId <= TypeId.FLOAT64_ARRAY) return true;
return false;
},
} as const;
diff --git a/javascript/packages/core/lib/typeInfo.ts b/javascript/packages/core/lib/typeInfo.ts
index 253500480..2f3363999 100644
--- a/javascript/packages/core/lib/typeInfo.ts
+++ b/javascript/packages/core/lib/typeInfo.ts
@@ -23,7 +23,6 @@ import { BoolArray } from "./types/boolArray";
import { Float16Array } from "./types/float16";
import { Decimal } from "./types/decimal";
-
const targetFields = new WeakMap<new () => any, { [key: string]: TypeInfo }>();
const addField = (target: new () => any, key: string, des: TypeInfo) => {
@@ -117,25 +116,25 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
target.prototype = {};
}
if (!this.options) {
- this.options = {}
+ this.options = {};
}
this.options!.withConstructor = true;
this.options!.creator = target;
if (!this.options!.props) {
this.options!.props = {};
}
- Object.assign(this.options!.props, targetFields.get(target) || {})
+ Object.assign(this.options!.props, targetFields.get(target) || {});
const that = this;
Object.defineProperties(target.prototype, {
[ForyTypeInfoSymbol]: {
get() {
return {
- structTypeInfo: that
+ structTypeInfo: that,
};
},
enumerable: false,
set(_) {
- throw new Error("fory type info is readonly")
+ throw new Error("fory type info is readonly");
},
},
});
@@ -143,14 +142,14 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
public freeze() {
Object.defineProperties(this, {
- 'named': { writable: false, configurable: false },
- 'namespace': { writable: false, configurable: false },
- 'typeName': { writable: false, configurable: false },
- 'userTypeId': { writable: false, configurable: false },
- 'evolving': { writable: false, configurable: false },
- 'options': { writable: false, configurable: false },
- '_typeId': { writable: false, configurable: false },
- 'nullable': { writable: false, configurable: false },
+ named: { writable: false, configurable: false },
+ namespace: { writable: false, configurable: false },
+ typeName: { writable: false, configurable: false },
+ userTypeId: { writable: false, configurable: false },
+ evolving: { writable: false, configurable: false },
+ options: { writable: false, configurable: false },
+ _typeId: { writable: false, configurable: false },
+ nullable: { writable: false, configurable: false },
});
Object.freeze(this.options);
if (this.options?.props) {
@@ -176,7 +175,7 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
// eslint-disable-next-line
const that = this;
if (userTypeId !== -1) {
- if (!Number.isInteger(userTypeId) || userTypeId < 0 || userTypeId > 0xFFFFFFFE) {
+ if (!Number.isInteger(userTypeId) || userTypeId < 0 || userTypeId > 0xfffffffe) {
throw new Error("userTypeId must be in range [0, 0xfffffffe]");
}
}
@@ -199,7 +198,6 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
return result;
}
-
get typeId() {
return this._typeId;
}
@@ -214,15 +212,21 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
}>(typeId);
}
- static fromExt<T = any>(nameInfo: {
- typeId?: number;
- namespace?: string;
- typeName?: string;
- } | string | number, {
- withConstructor = false,
- }: {
- withConstructor?: boolean;
- } = {}) {
+ static fromExt<T = any>(
+ nameInfo:
+ | {
+ typeId?: number;
+ namespace?: string;
+ typeName?: string;
+ }
+ | string
+ | number,
+ {
+ withConstructor = false,
+ }: {
+ withConstructor?: boolean;
+ } = {},
+ ) {
let typeId: number | undefined;
let namespace: string | undefined;
let typeName: string | undefined;
@@ -256,7 +260,7 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
} else {
finalTypeId = TypeId.NAMED_EXT;
}
- const typeInfo = new TypeInfo<T>(finalTypeId, userTypeId)
+ const typeInfo = new TypeInfo<T>(finalTypeId, userTypeId);
typeInfo.options = {
withConstructor,
};
@@ -266,16 +270,23 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
return typeInfo as TypeInfo<T>;
}
- static fromStruct<T = any>(nameInfo: {
- typeId?: number;
- namespace?: string;
- typeName?: string;
- evolving?: boolean;
- } | string | number, props?: Record<string, TypeInfo>, {
- withConstructor = false,
- }: {
- withConstructor?: boolean;
- } = {}) {
+ static fromStruct<T = any>(
+ nameInfo:
+ | {
+ typeId?: number;
+ namespace?: string;
+ typeName?: string;
+ evolving?: boolean;
+ }
+ | string
+ | number,
+ props?: Record<string, TypeInfo>,
+ {
+ withConstructor = false,
+ }: {
+ withConstructor?: boolean;
+ } = {},
+ ) {
let typeId: number | undefined;
let namespace: string | undefined;
let typeName: string | undefined;
@@ -332,11 +343,17 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
return typeInfo;
}
- static fromEnum<T>(nameInfo: {
- typeId?: number;
- namespace?: string;
- typeName?: string;
- } | string | number, props?: { [key: string]: any }) {
+ static fromEnum<T>(
+ nameInfo:
+ | {
+ typeId?: number;
+ namespace?: string;
+ typeName?: string;
+ }
+ | string
+ | number,
+ props?: { [key: string]: any },
+ ) {
let typeId: number | undefined;
let namespace: string | undefined;
let typeName: string | undefined;
@@ -378,7 +395,7 @@ export class TypeInfo<T = unknown> extends ExtensibleFunction {
export enum Dynamic {
TRUE = "TRUE",
FALSE = "FALSE",
- AUTO = "AUTO"
+ AUTO = "AUTO",
}
type ScalarEncoding = "fixed" | "varint" | "tagged";
@@ -387,10 +404,7 @@ type IntegerEncodingOptions = {
encoding?: ScalarEncoding;
};
-const scalarTypeInfo = <T extends number>(
- typeId: T,
- scalarEncoding?: ScalarEncoding,
-) => {
+const scalarTypeInfo = <T extends number>(typeId: T, scalarEncoding?: ScalarEncoding) => {
const typeInfo = TypeInfo.fromNonParam<T>(typeId);
if (scalarEncoding !== undefined) {
typeInfo.options = { scalarEncoding };
@@ -446,9 +460,8 @@ const typeIdForUInt64Encoding = (options?: IntegerEncodingOptions) => {
}
};
-const isDenseArrayTypeId = (typeId: number) => (
- typeId >= TypeId.BOOL_ARRAY && typeId <= TypeId.FLOAT64_ARRAY
-);
+const isDenseArrayTypeId = (typeId: number) =>
+ typeId >= TypeId.BOOL_ARRAY && typeId <= TypeId.FLOAT64_ARRAY;
const denseArrayTypeInfo = <T extends number>(typeId: T) => TypeInfo.fromNonParam<T>(typeId);
@@ -458,8 +471,8 @@ type Props<T> = T extends {
};
}
? {
- [P in keyof T2]?: (InputType<T2[P]> | null);
- }
+ [P in keyof T2]?: InputType<T2[P]> | null;
+ }
: unknown;
type InnerProps<T> = T extends {
@@ -479,7 +492,6 @@ type MapProps<T> = T extends {
? Map<InputType<T2>, InputType<T3> | null>
: unknown;
-
type Value<T> = T extends { [s: string]: infer T2 } ? T2 : unknown;
type EnumProps<T> = T extends {
@@ -495,266 +507,269 @@ type SetProps<T> = T extends {
key: infer T2 extends TypeInfo;
};
}
- ? Set<(InputType<T2> | null)>
+ ? Set<InputType<T2> | null>
: unknown;
export type InputType<T> = T extends TypeInfo<infer M> ? HintInput<M> : unknown;
-
export type HintInput<T> = T extends {
type: typeof TypeId.STRUCT;
}
? Props<T>
: T extends {
- type: typeof TypeId.STRING;
- }
- ? string
- : T extends {
- type:
- | typeof TypeId["INT8"]
- | typeof TypeId.INT16
- | typeof TypeId.INT32
- | typeof TypeId.VARINT32
- | typeof TypeId.UINT8
- | typeof TypeId.UINT16
- | typeof TypeId.UINT32
- | typeof TypeId.UINT64
- | typeof TypeId.VAR_UINT64
- | typeof TypeId.VAR_UINT32
- | typeof TypeId.FLOAT8
- | typeof TypeId.FLOAT16
- | typeof TypeId.BFLOAT16
- | typeof TypeId.FLOAT32
- | typeof TypeId.FLOAT64;
- }
- ? number
-
- : T extends {
- type: typeof TypeId.VARINT64
- | typeof TypeId.TAGGED_INT64
- | typeof TypeId.INT64
- | typeof TypeId.UINT64
- | typeof TypeId.VAR_UINT64
- | typeof TypeId.TAGGED_UINT64;
- }
- ? bigint
- : T extends {
- type: typeof TypeId.MAP;
- }
- ? MapProps<T>
- : T extends {
- type: typeof TypeId.SET;
- }
- ? SetProps<T>
- : T extends {
- type: typeof TypeId.LIST;
- }
- ? InnerProps<T>
- : T extends {
- type: typeof TypeId.BOOL;
- }
- ? boolean
- : T extends {
- type: typeof TypeId.DURATION;
- }
- ? Date
- : T extends {
- type: typeof TypeId.DECIMAL;
- }
- ? Decimal
- : T extends {
- type: typeof TypeId.TIMESTAMP;
- }
- ? number
- : T extends {
- type: typeof TypeId.BINARY;
- }
- ? Uint8Array
- : T extends {
- type: typeof TypeId.BOOL_ARRAY;
- }
- ? BoolArray | boolean[]
- : T extends {
- type: typeof TypeId.INT8_ARRAY;
- }
- ? Int8Array
- : T extends {
- type: typeof TypeId.INT16_ARRAY;
- }
- ? Int16Array
- : T extends {
- type: typeof TypeId.INT32_ARRAY;
- }
- ? Int32Array
- : T extends {
- type: typeof TypeId.INT64_ARRAY;
- }
- ? BigInt64Array
- : T extends {
- type: typeof TypeId.UINT8_ARRAY;
- }
- ? Uint8Array
- : T extends {
- type: typeof TypeId.UINT16_ARRAY;
- }
- ? Uint16Array
- : T extends {
- type: typeof TypeId.UINT32_ARRAY;
- }
- ? Uint32Array
- : T extends {
- type: typeof TypeId.UINT64_ARRAY;
- }
- ? BigUint64Array
- : T extends {
- type: typeof TypeId.FLOAT16_ARRAY;
- }
- ? Float16Array | number[]
- : T extends {
- type: typeof TypeId.BFLOAT16_ARRAY;
- }
- ? BFloat16Array | number[]
- : T extends {
- type: typeof TypeId.FLOAT32_ARRAY;
- }
- ? Float32Array
- : T extends {
- type: typeof TypeId.FLOAT64_ARRAY;
- }
- ? Float64Array
- : T extends {
- type: typeof TypeId.ENUM;
- }
- ? EnumProps<T> : any;
+ type: typeof TypeId.STRING;
+ }
+ ? string
+ : T extends {
+ type:
+ | (typeof TypeId)["INT8"]
+ | typeof TypeId.INT16
+ | typeof TypeId.INT32
+ | typeof TypeId.VARINT32
+ | typeof TypeId.UINT8
+ | typeof TypeId.UINT16
+ | typeof TypeId.UINT32
+ | typeof TypeId.UINT64
+ | typeof TypeId.VAR_UINT64
+ | typeof TypeId.VAR_UINT32
+ | typeof TypeId.FLOAT8
+ | typeof TypeId.FLOAT16
+ | typeof TypeId.BFLOAT16
+ | typeof TypeId.FLOAT32
+ | typeof TypeId.FLOAT64;
+ }
+ ? number
+ : T extends {
+ type:
+ | typeof TypeId.VARINT64
+ | typeof TypeId.TAGGED_INT64
+ | typeof TypeId.INT64
+ | typeof TypeId.UINT64
+ | typeof TypeId.VAR_UINT64
+ | typeof TypeId.TAGGED_UINT64;
+ }
+ ? bigint
+ : T extends {
+ type: typeof TypeId.MAP;
+ }
+ ? MapProps<T>
+ : T extends {
+ type: typeof TypeId.SET;
+ }
+ ? SetProps<T>
+ : T extends {
+ type: typeof TypeId.LIST;
+ }
+ ? InnerProps<T>
+ : T extends {
+ type: typeof TypeId.BOOL;
+ }
+ ? boolean
+ : T extends {
+ type: typeof TypeId.DURATION;
+ }
+ ? Date
+ : T extends {
+ type: typeof TypeId.DECIMAL;
+ }
+ ? Decimal
+ : T extends {
+ type: typeof TypeId.TIMESTAMP;
+ }
+ ? number
+ : T extends {
+ type: typeof TypeId.BINARY;
+ }
+ ? Uint8Array
+ : T extends {
+ type: typeof TypeId.BOOL_ARRAY;
+ }
+ ? BoolArray | boolean[]
+ : T extends {
+ type: typeof TypeId.INT8_ARRAY;
+ }
+ ? Int8Array
+ : T extends {
+ type: typeof TypeId.INT16_ARRAY;
+ }
+ ? Int16Array
+ : T extends {
+ type: typeof TypeId.INT32_ARRAY;
+ }
+ ? Int32Array
+ : T extends {
+ type: typeof TypeId.INT64_ARRAY;
+ }
+ ? BigInt64Array
+ : T extends {
+ type: typeof TypeId.UINT8_ARRAY;
+ }
+ ? Uint8Array
+ : T extends {
+ type: typeof TypeId.UINT16_ARRAY;
+ }
+ ? Uint16Array
+ : T extends {
+ type: typeof TypeId.UINT32_ARRAY;
+ }
+ ? Uint32Array
+ : T extends {
+ type: typeof TypeId.UINT64_ARRAY;
+ }
+ ? BigUint64Array
+ : T extends {
+ type: typeof TypeId.FLOAT16_ARRAY;
+ }
+ ? Float16Array | number[]
+ : T extends {
+ type: typeof TypeId.BFLOAT16_ARRAY;
+ }
+ ? BFloat16Array | number[]
+ : T extends {
+ type: typeof TypeId.FLOAT32_ARRAY;
+ }
+ ? Float32Array
+ : T extends {
+ type: typeof TypeId.FLOAT64_ARRAY;
+ }
+ ? Float64Array
+ : T extends {
+ type: typeof TypeId.ENUM;
+ }
+ ? EnumProps<T>
+ : any;
export type ResultType<T> = T extends TypeInfo<infer M> ? HintResult<M> : HintResult<T>;
-export type HintResult<T> = T extends never ? any : T extends {
- type: typeof TypeId.STRUCT;
-}
- ? Props<T>
- : T extends {
- type: typeof TypeId.STRING;
- }
- ? string
- : T extends {
- type:
- | typeof TypeId.INT8
- | typeof TypeId.INT16
- | typeof TypeId.INT32
- | typeof TypeId.VARINT32
- | typeof TypeId.UINT8
- | typeof TypeId.UINT16
- | typeof TypeId.UINT32
- | typeof TypeId.VAR_UINT32
- | typeof TypeId.FLOAT8
- | typeof TypeId.FLOAT16
- | typeof TypeId.BFLOAT16
- | typeof TypeId.FLOAT32
- | typeof TypeId.FLOAT64;
- }
- ? number
-
- : T extends {
- type: typeof TypeId.TAGGED_INT64
- | typeof TypeId.INT64
- | typeof TypeId.UINT64
- | typeof TypeId.VAR_UINT64
- | typeof TypeId.TAGGED_UINT64;
- }
- ? bigint
- : T extends {
- type: typeof TypeId.MAP;
- }
- ? MapProps<T>
- : T extends {
- type: typeof TypeId.SET;
- }
- ? SetProps<T>
- : T extends {
- type: typeof TypeId.LIST;
- }
- ? InnerProps<T>
- : T extends {
- type: typeof TypeId.BOOL;
- }
- ? boolean
- : T extends {
- type: typeof TypeId.DURATION;
- }
- ? number
- : T extends {
- type: typeof TypeId.DECIMAL;
- }
- ? Decimal
+export type HintResult<T> = T extends never
+ ? any
: T extends {
- type: typeof TypeId.DATE;
- }
- ? (Date | number)
- : T extends {
- type: typeof TypeId.TIMESTAMP;
- }
- ? number
- : T extends {
- type: typeof TypeId.BINARY;
- }
- ? Uint8Array
- : T extends {
- type: typeof TypeId.BOOL_ARRAY;
- }
- ? BoolArray
- : T extends {
- type: typeof TypeId.INT8_ARRAY;
- }
- ? Int8Array
- : T extends {
- type: typeof TypeId.INT16_ARRAY;
- }
- ? Int16Array
- : T extends {
- type: typeof TypeId.INT32_ARRAY;
- }
- ? Int32Array
- : T extends {
- type: typeof TypeId.INT64_ARRAY;
- }
- ? BigInt64Array
- : T extends {
- type: typeof TypeId.UINT8_ARRAY;
- }
- ? Uint8Array
- : T extends {
- type: typeof TypeId.UINT16_ARRAY;
- }
- ? Uint16Array
- : T extends {
- type: typeof TypeId.UINT32_ARRAY;
- }
- ? Uint32Array
- : T extends {
- type: typeof TypeId.UINT64_ARRAY;
- }
- ? BigUint64Array
- : T extends {
- type: typeof TypeId.FLOAT16_ARRAY;
- }
- ? Float16Array
- : T extends {
- type: typeof TypeId.BFLOAT16_ARRAY;
- }
- ? BFloat16Array
- : T extends {
- type: typeof TypeId.FLOAT32_ARRAY;
- }
- ? Float32Array
- : T extends {
- type: typeof TypeId.FLOAT64_ARRAY;
- }
- ? Float64Array
- : T extends {
- type: typeof TypeId.ENUM;
- }
- ? EnumProps<T> : unknown;
+ type: typeof TypeId.STRUCT;
+ }
+ ? Props<T>
+ : T extends {
+ type: typeof TypeId.STRING;
+ }
+ ? string
+ : T extends {
+ type:
+ | typeof TypeId.INT8
+ | typeof TypeId.INT16
+ | typeof TypeId.INT32
+ | typeof TypeId.VARINT32
+ | typeof TypeId.UINT8
+ | typeof TypeId.UINT16
+ | typeof TypeId.UINT32
+ | typeof TypeId.VAR_UINT32
+ | typeof TypeId.FLOAT8
+ | typeof TypeId.FLOAT16
+ | typeof TypeId.BFLOAT16
+ | typeof TypeId.FLOAT32
+ | typeof TypeId.FLOAT64;
+ }
+ ? number
+ : T extends {
+ type:
+ | typeof TypeId.TAGGED_INT64
+ | typeof TypeId.INT64
+ | typeof TypeId.UINT64
+ | typeof TypeId.VAR_UINT64
+ | typeof TypeId.TAGGED_UINT64;
+ }
+ ? bigint
+ : T extends {
+ type: typeof TypeId.MAP;
+ }
+ ? MapProps<T>
+ : T extends {
+ type: typeof TypeId.SET;
+ }
+ ? SetProps<T>
+ : T extends {
+ type: typeof TypeId.LIST;
+ }
+ ? InnerProps<T>
+ : T extends {
+ type: typeof TypeId.BOOL;
+ }
+ ? boolean
+ : T extends {
+ type: typeof TypeId.DURATION;
+ }
+ ? number
+ : T extends {
+ type: typeof TypeId.DECIMAL;
+ }
+ ? Decimal
+ : T extends {
+ type: typeof TypeId.DATE;
+ }
+ ? Date | number
+ : T extends {
+ type: typeof TypeId.TIMESTAMP;
+ }
+ ? number
+ : T extends {
+ type: typeof TypeId.BINARY;
+ }
+ ? Uint8Array
+ : T extends {
+ type: typeof TypeId.BOOL_ARRAY;
+ }
+ ? BoolArray
+ : T extends {
+ type: typeof TypeId.INT8_ARRAY;
+ }
+ ? Int8Array
+ : T extends {
+ type: typeof TypeId.INT16_ARRAY;
+ }
+ ? Int16Array
+ : T extends {
+ type: typeof TypeId.INT32_ARRAY;
+ }
+ ? Int32Array
+ : T extends {
+ type: typeof TypeId.INT64_ARRAY;
+ }
+ ? BigInt64Array
+ : T extends {
+ type: typeof TypeId.UINT8_ARRAY;
+ }
+ ? Uint8Array
+ : T extends {
+ type: typeof TypeId.UINT16_ARRAY;
+ }
+ ? Uint16Array
+ : T extends {
+ type: typeof TypeId.UINT32_ARRAY;
+ }
+ ? Uint32Array
+ : T extends {
+ type: typeof TypeId.UINT64_ARRAY;
+ }
+ ? BigUint64Array
+ : T extends {
+ type: typeof TypeId.FLOAT16_ARRAY;
+ }
+ ? Float16Array
+ : T extends {
+ type: typeof TypeId.BFLOAT16_ARRAY;
+ }
+ ? BFloat16Array
+ : T extends {
+ type: typeof TypeId.FLOAT32_ARRAY;
+ }
+ ? Float32Array
+ : T extends {
+ type: typeof TypeId.FLOAT64_ARRAY;
+ }
+ ? Float64Array
+ : T extends {
+ type: typeof TypeId.ENUM;
+ }
+ ? EnumProps<T>
+ : unknown;
export const Type = {
any() {
@@ -765,33 +780,42 @@ export const Type = {
inner,
});
},
- map<T1 extends TypeInfo, T2 extends TypeInfo>(
- key: T1,
- value: T2
- ) {
+ map<T1 extends TypeInfo, T2 extends TypeInfo>(key: T1, value: T2) {
if (isDenseArrayTypeId(key.typeId)) {
throw new Error("Dense array schema is not valid as a map key type");
}
- return TypeInfo.fromWithOptions<typeof TypeId.MAP, {
- key: T1,
- value: T2
- }>(TypeId.MAP, {
+ return TypeInfo.fromWithOptions<
+ typeof TypeId.MAP,
+ {
+ key: T1;
+ value: T2;
+ }
+ >(TypeId.MAP, {
key,
value,
});
},
set<T extends TypeInfo>(key: T) {
- return TypeInfo.fromWithOptions<typeof TypeId.SET, {
- key: T
- }>(TypeId.SET, {
+ return TypeInfo.fromWithOptions<
+ typeof TypeId.SET,
+ {
+ key: T;
+ }
+ >(TypeId.SET, {
key,
});
},
- enum<T1 extends { [key: string]: any }>(nameInfo: {
- typeId?: number;
- namespace?: string;
- typeName?: string;
- } | string | number, t1?: T1) {
+ enum<T1 extends { [key: string]: any }>(
+ nameInfo:
+ | {
+ typeId?: number;
+ namespace?: string;
+ typeName?: string;
+ }
+ | string
+ | number,
+ t1?: T1,
+ ) {
return TypeInfo.fromEnum<{
type: typeof TypeId.ENUM;
options: {
@@ -799,15 +823,21 @@ export const Type = {
};
}>(nameInfo, t1);
},
- ext<T extends { [key: string]: TypeInfo }>(nameInfo: {
- typeId?: number;
- namespace?: string;
- typeName?: string;
- } | string | number, {
- withConstructor = false,
- }: {
- withConstructor?: boolean;
- } = {}) {
+ ext<T extends { [key: string]: TypeInfo }>(
+ nameInfo:
+ | {
+ typeId?: number;
+ namespace?: string;
+ typeName?: string;
+ }
+ | string
+ | number,
+ {
+ withConstructor = false,
+ }: {
+ withConstructor?: boolean;
+ } = {},
+ ) {
return TypeInfo.fromExt<{
type: typeof TypeId.EXT;
options: {
@@ -817,16 +847,23 @@ export const Type = {
withConstructor,
});
},
- struct<T extends { [key: string]: TypeInfo }>(nameInfo: {
- typeId?: number;
- namespace?: string;
- typeName?: string;
- evolving?: boolean;
- } | string | number, props?: T, {
- withConstructor = false,
- }: {
- withConstructor?: boolean;
- } = {}) {
+ struct<T extends { [key: string]: TypeInfo }>(
+ nameInfo:
+ | {
+ typeId?: number;
+ namespace?: string;
+ typeName?: string;
+ evolving?: boolean;
+ }
+ | string
+ | number,
+ props?: T,
+ {
+ withConstructor = false,
+ }: {
+ withConstructor?: boolean;
+ } = {},
+ ) {
return TypeInfo.fromStruct<{
type: typeof TypeId.STRUCT;
options: {
@@ -836,7 +873,14 @@ export const Type = {
withConstructor,
});
},
- union(idOrCases?: number | string | { namespace?: string; typeName?: string } | { [caseIndex: number]: TypeInfo }, cases?: { [caseIndex: number]: TypeInfo }) {
+ union(
+ idOrCases?:
+ | number
+ | string
+ | { namespace?: string; typeName?: string }
+ | { [caseIndex: number]: TypeInfo },
+ cases?: { [caseIndex: number]: TypeInfo },
+ ) {
let typeInfo: TypeInfo;
if (typeof idOrCases === "number") {
typeInfo = new TypeInfo<typeof TypeId.TYPED_UNION>(TypeId.TYPED_UNION);
@@ -875,25 +919,16 @@ export const Type = {
return typeInfo;
},
string() {
- return TypeInfo.fromNonParam<typeof TypeId.STRING>(
- (TypeId.STRING),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.STRING>(TypeId.STRING);
},
bool() {
- return TypeInfo.fromNonParam<typeof TypeId.BOOL>(
- (TypeId.BOOL),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.BOOL>(TypeId.BOOL);
},
int8() {
- return TypeInfo.fromNonParam<typeof TypeId.INT8>(
- (TypeId.INT8),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.INT8>(TypeId.INT8);
},
int16() {
- return TypeInfo.fromNonParam<typeof TypeId.INT16>(
- (TypeId.INT16),
-
- );
+ return TypeInfo.fromNonParam<typeof TypeId.INT16>(TypeId.INT16);
},
int32(options?: IntegerEncodingOptions) {
return scalarTypeInfo(typeIdForInt32Encoding(options), options?.encoding);
@@ -902,38 +937,22 @@ export const Type = {
return scalarTypeInfo(typeIdForInt64Encoding(options), options?.encoding);
},
float16() {
- return TypeInfo.fromNonParam<typeof TypeId.FLOAT16>(
- (TypeId.FLOAT16),
-
- );
+ return TypeInfo.fromNonParam<typeof TypeId.FLOAT16>(TypeId.FLOAT16);
},
bfloat16() {
- return TypeInfo.fromNonParam<typeof TypeId.BFLOAT16>(
- (TypeId.BFLOAT16),
-
- );
+ return TypeInfo.fromNonParam<typeof TypeId.BFLOAT16>(TypeId.BFLOAT16);
},
float32() {
- return TypeInfo.fromNonParam<typeof TypeId.FLOAT32>(
- (TypeId.FLOAT32),
-
- );
+ return TypeInfo.fromNonParam<typeof TypeId.FLOAT32>(TypeId.FLOAT32);
},
float64() {
- return TypeInfo.fromNonParam<typeof TypeId.FLOAT64>(
- (TypeId.FLOAT64),
-
- );
+ return TypeInfo.fromNonParam<typeof TypeId.FLOAT64>(TypeId.FLOAT64);
},
uint8() {
- return TypeInfo.fromNonParam<typeof TypeId.UINT8>(
- (TypeId.UINT8),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.UINT8>(TypeId.UINT8);
},
uint16() {
- return TypeInfo.fromNonParam<typeof TypeId.UINT16>(
- (TypeId.UINT16),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.UINT16>(TypeId.UINT16);
},
uint32(options?: IntegerEncodingOptions) {
return scalarTypeInfo(typeIdForUInt32Encoding(options), options?.encoding);
@@ -942,30 +961,19 @@ export const Type = {
return scalarTypeInfo(typeIdForUInt64Encoding(options), options?.encoding);
},
binary() {
- return TypeInfo.fromNonParam<typeof TypeId.BINARY>(
- (TypeId.BINARY),
-
- );
+ return TypeInfo.fromNonParam<typeof TypeId.BINARY>(TypeId.BINARY);
},
duration() {
- return TypeInfo.fromNonParam<typeof TypeId.DURATION>(
- (TypeId.DURATION),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.DURATION>(TypeId.DURATION);
},
date() {
- return TypeInfo.fromNonParam<typeof TypeId.DATE>(
- (TypeId.DATE),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.DATE>(TypeId.DATE);
},
timestamp() {
- return TypeInfo.fromNonParam<typeof TypeId.TIMESTAMP>(
- (TypeId.TIMESTAMP),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.TIMESTAMP>(TypeId.TIMESTAMP);
},
decimal() {
- return TypeInfo.fromNonParam<typeof TypeId.DECIMAL>(
- (TypeId.DECIMAL),
- );
+ return TypeInfo.fromNonParam<typeof TypeId.DECIMAL>(TypeId.DECIMAL);
},
boolArray() {
return denseArrayTypeInfo<typeof TypeId.BOOL_ARRAY>(TypeId.BOOL_ARRAY);
diff --git a/javascript/packages/core/lib/typeResolver.ts b/javascript/packages/core/lib/typeResolver.ts
index c9936be86..214311512 100644
--- a/javascript/packages/core/lib/typeResolver.ts
+++ b/javascript/packages/core/lib/typeResolver.ts
@@ -17,7 +17,15 @@
* under the License.
*/
-import { ForyTypeInfoSymbol, WithForyClsInfo, Serializer, TypeId, MaxInt32, MinInt32, Config } from "./type";
+import {
+ ForyTypeInfoSymbol,
+ WithForyClsInfo,
+ Serializer,
+ TypeId,
+ MaxInt32,
+ MinInt32,
+ Config,
+} from "./type";
import { Gen } from "./gen";
import { Dynamic, Type, TypeInfo } from "./typeInfo";
import { ReadContext, WriteContext } from "./context";
@@ -154,7 +162,11 @@ export default class TypeResolver {
if (TypeId.enumType(typeInfo.typeId)) {
return true;
}
- if (typeInfo.typeId === TypeId.UNION || typeInfo.typeId === TypeId.TYPED_UNION || typeInfo.typeId === TypeId.NAMED_UNION) {
+ if (
+ typeInfo.typeId === TypeId.UNION ||
+ typeInfo.typeId === TypeId.TYPED_UNION ||
+ typeInfo.typeId === TypeId.NAMED_UNION
+ ) {
return true;
}
if (this.isCompatible()) {
@@ -260,7 +272,7 @@ export default class TypeResolver {
}
return this.customSerializer.get(key);
}
- if (typeId <= 0xFF) {
+ if (typeId <= 0xff) {
if (this.internalSerializer[typeId]) {
Object.assign(this.internalSerializer[typeId], serializer);
} else {
diff --git a/javascript/packages/core/lib/types/boolArray.ts b/javascript/packages/core/lib/types/boolArray.ts
index e7419fecd..61ac10195 100644
--- a/javascript/packages/core/lib/types/boolArray.ts
+++ b/javascript/packages/core/lib/types/boolArray.ts
@@ -70,7 +70,7 @@ export class BoolArray {
data = new Uint8Array(this._length);
let bits = this._packedBits;
for (let i = 0; i < this._length; i++) {
- data[i] = bits & 0xFF;
+ data[i] = bits & 0xff;
bits >>>= 8;
}
this._data = data;
@@ -83,7 +83,7 @@ export class BoolArray {
if (data !== null) {
return data[index] !== 0;
}
- return ((this._packedBits >>> (index * 8)) & 0xFF) !== 0;
+ return ((this._packedBits >>> (index * 8)) & 0xff) !== 0;
}
at(index: number): boolean | undefined {
@@ -150,9 +150,7 @@ export class BoolArray {
return {
next(): IteratorResult<boolean> {
if (i < len) {
- const value = data === null
- ? ((bits >>> ((i++) * 8)) & 0xFF) !== 0
- : data[i++] !== 0;
+ const value = data === null ? ((bits >>> (i++ * 8)) & 0xff) !== 0 : data[i++] !== 0;
return { value, done: false };
}
return { value: undefined as unknown as boolean, done: true };
diff --git a/javascript/packages/core/lib/types/decimal.ts b/javascript/packages/core/lib/types/decimal.ts
index fa967500c..5a64f49eb 100644
--- a/javascript/packages/core/lib/types/decimal.ts
+++ b/javascript/packages/core/lib/types/decimal.ts
@@ -38,9 +38,9 @@ export class Decimal {
equals(other: unknown): boolean {
return (
- other instanceof Decimal
- && other.scale === this.scale
- && other.unscaledValue === this.unscaledValue
+ other instanceof Decimal &&
+ other.scale === this.scale &&
+ other.unscaledValue === this.unscaledValue
);
}
diff --git a/javascript/packages/core/lib/types/float16.ts b/javascript/packages/core/lib/types/float16.ts
index e346236d5..de2fc9100 100644
--- a/javascript/packages/core/lib/types/float16.ts
+++ b/javascript/packages/core/lib/types/float16.ts
@@ -173,22 +173,25 @@ export class ForyFloat16Array {
}
type NativeFloat16ArrayConstructor = {
- new(length: number): ArrayLike<number>;
- new(source: ArrayLike<number>): ArrayLike<number>;
+ new (length: number): ArrayLike<number>;
+ new (source: ArrayLike<number>): ArrayLike<number>;
readonly BYTES_PER_ELEMENT: number;
};
-const NativeFloat16Array = (globalThis as unknown as { Float16Array?: NativeFloat16ArrayConstructor }).Float16Array;
+const NativeFloat16Array = (
+ globalThis as unknown as { Float16Array?: NativeFloat16ArrayConstructor }
+).Float16Array;
export type Float16Array = ForyFloat16Array | ArrayLike<number>;
-export const Float16Array = (
- NativeFloat16Array ?? ForyFloat16Array
-) as NativeFloat16ArrayConstructor | typeof ForyFloat16Array;
+export const Float16Array = (NativeFloat16Array ?? ForyFloat16Array) as
+ NativeFloat16ArrayConstructor | typeof ForyFloat16Array;
export function isFloat16Array(value: unknown): boolean {
- return value instanceof ForyFloat16Array
- || (NativeFloat16Array !== undefined && value instanceof NativeFloat16Array);
+ return (
+ value instanceof ForyFloat16Array ||
+ (NativeFloat16Array !== undefined && value instanceof NativeFloat16Array)
+ );
}
export function getFloat16Raw(value: unknown): Uint16Array | null {
diff --git a/javascript/packages/core/lib/util.ts b/javascript/packages/core/lib/util.ts
index e0a87b7bd..42abca256 100644
--- a/javascript/packages/core/lib/util.ts
+++ b/javascript/packages/core/lib/util.ts
@@ -17,11 +17,11 @@
* under the License.
*/
-export const isNodeEnv: boolean
- = typeof process !== "undefined"
- && process.versions != null
- && process.env.ECMA_ONLY !== "true"
- && process.versions.node != null;
+export const isNodeEnv: boolean =
+ typeof process !== "undefined" &&
+ process.versions != null &&
+ process.env.ECMA_ONLY !== "true" &&
+ process.versions.node != null;
export const hasBuffer = isNodeEnv && typeof Buffer !== "undefined";
diff --git a/javascript/packages/core/lib/writer/index.ts b/javascript/packages/core/lib/writer/index.ts
index 6f6eed717..f82cad30f 100644
--- a/javascript/packages/core/lib/writer/index.ts
+++ b/javascript/packages/core/lib/writer/index.ts
@@ -33,7 +33,9 @@ function getInternalStringDetector() {
if (typeof isStringOneByteRepresentation === "function") {
return isStringOneByteRepresentation;
}
- } catch { /* not available */ }
+ } catch {
+ /* not available */
+ }
return null;
}
@@ -49,22 +51,24 @@ export class BinaryWriter {
};
private hpsEnable = false;
- private internalStringDetector: (((content: string) => boolean) | null) = null;
+ private internalStringDetector: ((content: string) => boolean) | null = null;
private writeNonEmptyStringWithHeader: (v: string) => void;
- constructor(config: {
- hps?: Hps;
- } = {}) {
+ constructor(
+ config: {
+ hps?: Hps;
+ } = {},
+ ) {
this.initPoll();
this.config = config;
this.hpsEnable = Boolean(config?.hps);
this.internalStringDetector = getInternalStringDetector();
if (this.hpsEnable) {
- this.writeNonEmptyStringWithHeader = v => this.stringWithHeaderFast(v);
+ this.writeNonEmptyStringWithHeader = (v) => this.stringWithHeaderFast(v);
} else if (this.internalStringDetector !== null) {
- this.writeNonEmptyStringWithHeader = v => this.stringWithHeaderWithDetector(v);
+ this.writeNonEmptyStringWithHeader = (v) => this.stringWithHeaderWithDetector(v);
} else {
- this.writeNonEmptyStringWithHeader = v => this.stringWithHeaderCompatibly(v);
+ this.writeNonEmptyStringWithHeader = (v) => this.stringWithHeaderCompatibly(v);
}
}
@@ -266,8 +270,8 @@ export class BinaryWriter {
this.dataView.setUint16(offset, (u1 << 8) | u2);
offset += 2;
} else if (
- (c1 & 0xfc00) === 0xd800
- && ((c2 = string.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
+ (c1 & 0xfc00) === 0xd800 &&
+ ((c2 = string.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
) {
c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
++i;
@@ -365,7 +369,7 @@ export class BinaryWriter {
}
writeVarUInt32(value: number) {
- value = (value >>> 0) & 0xFFFFFFFF; // keep only the lower 32 bits
+ value = (value >>> 0) & 0xffffffff; // keep only the lower 32 bits
if (value >>> 7 == 0) {
this.platformBuffer[this.cursor++] = value;
@@ -374,16 +378,27 @@ export class BinaryWriter {
const rawCursor = this.cursor;
let u32 = 0;
if (value >>> 14 == 0) {
- u32 = ((value & 0x7f | 0x80) << 24) | ((value >>> 7) << 16);
+ u32 = (((value & 0x7f) | 0x80) << 24) | ((value >>> 7) << 16);
this.cursor += 2;
} else if (value >>> 21 == 0) {
- u32 = ((value & 0x7f | 0x80) << 24) | ((value >>> 7 & 0x7f | 0x80) << 16) | ((value >>> 14) << 8);
+ u32 =
+ (((value & 0x7f) | 0x80) << 24) |
+ ((((value >>> 7) & 0x7f) | 0x80) << 16) |
+ ((value >>> 14) << 8);
this.cursor += 3;
} else if (value >>> 28 == 0) {
- u32 = ((value & 0x7f | 0x80) << 24) | ((value >>> 7 & 0x7f | 0x80) << 16) | ((value >>> 14 & 0x7f | 0x80) << 8) | (value >>> 21);
+ u32 =
+ (((value & 0x7f) | 0x80) << 24) |
+ ((((value >>> 7) & 0x7f) | 0x80) << 16) |
+ ((((value >>> 14) & 0x7f) | 0x80) << 8) |
+ (value >>> 21);
this.cursor += 4;
} else {
- u32 = ((value & 0x7f | 0x80) << 24) | ((value >>> 7 & 0x7f | 0x80) << 16) | ((value >>> 14 & 0x7f | 0x80) << 8) | (value >>> 21 & 0x7f | 0x80);
+ u32 =
+ (((value & 0x7f) | 0x80) << 24) |
+ ((((value >>> 7) & 0x7f) | 0x80) << 16) |
+ ((((value >>> 14) & 0x7f) | 0x80) << 8) |
+ (((value >>> 21) & 0x7f) | 0x80);
this.platformBuffer[rawCursor + 4] = value >>> 28;
this.cursor += 5;
}
@@ -399,8 +414,8 @@ export class BinaryWriter {
}
private continueWriteVarUint32Small7(value: number) {
- let encoded = (value & 0x7F);
- encoded |= (((value & 0x3f80) << 1) | 0x80);
+ let encoded = value & 0x7f;
+ encoded |= ((value & 0x3f80) << 1) | 0x80;
const writerIdx = this.cursor;
if (value >>> 14 === 0) {
this.dataView.setUint32(writerIdx, encoded, true);
@@ -411,7 +426,7 @@ export class BinaryWriter {
private continuePutVarInt36(index: number, encoded: number, value: number): number {
// 0x1fc000: 0b1111111 << 14
- encoded |= (((value & 0x1fc000) << 2) | 0x8000);
+ encoded |= ((value & 0x1fc000) << 2) | 0x8000;
if (value >>> 21 === 0) {
this.dataView.setUint32(index, encoded, true);
return 3;
@@ -461,13 +476,13 @@ export class BinaryWriter {
}
val = BigInt(val);
}
- val = val & 0xFFFFFFFFFFFFFFFFn; // keep only the lower 64 bits
+ val = val & 0xffffffffffffffffn; // keep only the lower 64 bits
// Match Java's 1-9 byte varuint64 encoding:
// - 7 bits per byte for the first 8 bytes
// - the 9th byte (if present) uses full 8 bits, allowing values with the 64th bit set
for (let i = 0; i < 8; i++) {
- if ((val >> 7n) === 0n) {
+ if (val >> 7n === 0n) {
this.platformBuffer[this.cursor++] = Number(val);
return;
}
diff --git a/javascript/test/any.test.ts b/javascript/test/any.test.ts
index a290a445f..7a977301e 100644
--- a/javascript/test/any.test.ts
+++ b/javascript/test/any.test.ts
@@ -17,99 +17,102 @@
* under the License.
*/
-import Fory, { Type } from '../packages/core/index';
-import { describe, expect, test } from '@jest/globals';
+import Fory, { Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
-describe('bool', () => {
- test('should write null work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(null);
- expect(fory.deserialize(bin)).toBe(null)
- });
- test('should write undefined work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(undefined);
- expect(fory.deserialize(bin)).toBe(null)
- });
+describe("bool", () => {
+ test("should write null work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(null);
+ expect(fory.deserialize(bin)).toBe(null);
+ });
+ test("should write undefined work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(undefined);
+ expect(fory.deserialize(bin)).toBe(null);
+ });
- test('should write number work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(123);
- expect(fory.deserialize(bin)).toBe(123)
- });
+ test("should write number work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(123);
+ expect(fory.deserialize(bin)).toBe(123);
+ });
- test('should write NaN work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(NaN);
- expect(fory.deserialize(bin)).toBe(NaN)
- });
+ test("should write NaN work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(NaN);
+ expect(fory.deserialize(bin)).toBe(NaN);
+ });
- test('should write big number work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(3000000000);
- expect(fory.deserialize(bin)).toBe(3000000000n);
- });
+ test("should write big number work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(3000000000);
+ expect(fory.deserialize(bin)).toBe(3000000000n);
+ });
- test('should write INFINITY work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(Number.NEGATIVE_INFINITY);
- expect(fory.deserialize(bin)).toBe(Number.NEGATIVE_INFINITY)
- });
+ test("should write INFINITY work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(Number.NEGATIVE_INFINITY);
+ expect(fory.deserialize(bin)).toBe(Number.NEGATIVE_INFINITY);
+ });
- test('should write float work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(123.123);
- expect(fory.deserialize(bin).toFixed(3)).toBe("123.123")
- });
+ test("should write float work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(123.123);
+ expect(fory.deserialize(bin).toFixed(3)).toBe("123.123");
+ });
- test('should write bigint work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(BigInt(123));
- expect(fory.deserialize(bin)).toBe(BigInt(123))
- });
+ test("should write bigint work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(BigInt(123));
+ expect(fory.deserialize(bin)).toBe(BigInt(123));
+ });
- test('should write true work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(true);
- expect(fory.deserialize(bin)).toBe(true)
- });
+ test("should write true work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(true);
+ expect(fory.deserialize(bin)).toBe(true);
+ });
- test('should write false work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize(false);
- expect(fory.deserialize(bin)).toBe(false)
- });
+ test("should write false work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize(false);
+ expect(fory.deserialize(bin)).toBe(false);
+ });
- test('should write date work', () => {
- const fory = new Fory({ compatible: false });
- const dt = new Date();
- const bin = fory.serialize(dt);
- const ret = fory.deserialize(bin);
- expect(ret instanceof Date).toBe(true)
- expect(ret.toUTCString()).toBe(dt.toUTCString())
- });
+ test("should write date work", () => {
+ const fory = new Fory({ compatible: false });
+ const dt = new Date();
+ const bin = fory.serialize(dt);
+ const ret = fory.deserialize(bin);
+ expect(ret instanceof Date).toBe(true);
+ expect(ret.toUTCString()).toBe(dt.toUTCString());
+ });
- test('should write string work', () => {
- const fory = new Fory({ compatible: false });
- const bin = fory.serialize("hello");
- expect(fory.deserialize(bin)).toBe("hello")
- });
+ test("should write string work", () => {
+ const fory = new Fory({ compatible: false });
+ const bin = fory.serialize("hello");
+ expect(fory.deserialize(bin)).toBe("hello");
+ });
- test('should write map work', () => {
- const fory = new Fory({ compatible: false });
- const obj = new Map([[1, 2], [3, 4]]);
- const bin = fory.serialize(obj);
- const ret = fory.deserialize(bin);
- expect(ret instanceof Map).toBe(true)
- expect([...ret.values()]).toEqual([...obj.values()])
- expect([...ret.keys()]).toEqual([...obj.keys()])
- });
+ test("should write map work", () => {
+ const fory = new Fory({ compatible: false });
+ const obj = new Map([
+ [1, 2],
+ [3, 4],
+ ]);
+ const bin = fory.serialize(obj);
+ const ret = fory.deserialize(bin);
+ expect(ret instanceof Map).toBe(true);
+ expect([...ret.values()]).toEqual([...obj.values()]);
+ expect([...ret.keys()]).toEqual([...obj.keys()]);
+ });
- test('should root any work', () => {
- const fory = new Fory({ compatible: false });
- const { serialize, deserialize } = fory.register(Type.any());
- const bin = serialize("hello");
- const result = deserialize(bin);
- expect(result).toEqual("hello")
- });
+ test("should root any work", () => {
+ const fory = new Fory({ compatible: false });
+ const { serialize, deserialize } = fory.register(Type.any());
+ const bin = serialize("hello");
+ const result = deserialize(bin);
+ expect(result).toEqual("hello");
+ });
});
diff --git a/javascript/test/array.test.ts b/javascript/test/array.test.ts
index ef6d84f70..ca1191f6a 100644
--- a/javascript/test/array.test.ts
+++ b/javascript/test/array.test.ts
@@ -23,68 +23,86 @@ import Fory, {
BoolArray,
Float16Array,
ForyFloat16Array,
-} from '../packages/core/index';
-import { TypeId } from '../packages/core/lib/type';
-import { describe, expect, test } from '@jest/globals';
-import * as beautify from 'js-beautify';
+} from "../packages/core/index";
+import { TypeId } from "../packages/core/lib/type";
+import { describe, expect, test } from "@jest/globals";
+import * as beautify from "js-beautify";
-describe('array', () => {
- test('should distinguish list and dense array schema builders', () => {
+describe("array", () => {
+ test("should distinguish list and dense array schema builders", () => {
expect(Type.list(Type.int32()).typeId).toBe(TypeId.LIST);
expect(Type.int32Array().typeId).toBe(TypeId.INT32_ARRAY);
expect(Type.uint8Array().typeId).toBe(TypeId.UINT8_ARRAY);
expect(Type.boolArray().typeId).toBe(TypeId.BOOL_ARRAY);
});
- test('should expose dense arrays only through element-specific builders', () => {
+ test("should expose dense arrays only through element-specific builders", () => {
expect((Type as Record<string, unknown>).array).toBeUndefined();
- expect(() => Type.map(Type.uint8Array(), Type.string())).toThrow('map key');
+ expect(() => Type.map(Type.uint8Array(), Type.string())).toThrow("map key");
});
- test('should array work', () => {
-
-
- const typeinfo = Type.struct({
- typeName: "example.bar"
- }, {
- c: Type.list(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.string()
- }))
- });
- const fory = new Fory({ compatible: false, ref: true, hooks: {
+ test("should array work", () => {
+ const typeinfo = Type.struct(
+ {
+ typeName: "example.bar",
+ },
+ {
+ c: Type.list(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.string(),
+ },
+ ),
+ ),
+ },
+ );
+ const fory = new Fory({
+ compatible: false,
+ ref: true,
+ hooks: {
afterCodeGenerated: (code: string) => {
- return beautify.js(code, { indent_size: 2, space_in_empty_paren: true, indent_empty_lines: true });
- }
- } });
+ return beautify.js(code, {
+ indent_size: 2,
+ space_in_empty_paren: true,
+ indent_empty_lines: true,
+ });
+ },
+ },
+ });
const { serialize, deserialize } = fory.register(typeinfo);
const o = { a: "123" };
- expect(deserialize(serialize({ c: [o, o] }))).toEqual({ c: [o, o] })
+ expect(deserialize(serialize({ c: [o, o] }))).toEqual({ c: [o, o] });
});
- test('should typedarray work', () => {
- const typeinfo = Type.struct({
- typeName: "example.foo",
- }, {
- a: Type.boolArray(),
- a2: Type.int16Array(),
- a3: Type.int32Array(),
- a4: Type.int64Array(),
- a6: Type.float64Array()
- });
+ test("should typedarray work", () => {
+ const typeinfo = Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.boolArray(),
+ a2: Type.int16Array(),
+ a3: Type.int32Array(),
+ a4: Type.int64Array(),
+ a6: Type.float64Array(),
+ },
+ );
const fory = new Fory({ compatible: false, ref: true });
const serializer = fory.register(typeinfo).serializer;
- const input = fory.serialize({
- a: [true, false],
- a2: new Int16Array([1, 2, 3]),
- a3: new Int32Array([3, 5, 76]),
- a4: new BigInt64Array([634n, 564n, 76n]),
- a6: new Float64Array([234243.555, 55654.679]),
- }, serializer);
- const result = fory.deserialize(
- input
+ const input = fory.serialize(
+ {
+ a: [true, false],
+ a2: new Int16Array([1, 2, 3]),
+ a3: new Int32Array([3, 5, 76]),
+ a4: new BigInt64Array([634n, 564n, 76n]),
+ a6: new Float64Array([234243.555, 55654.679]),
+ },
+ serializer,
);
+ const result = fory.deserialize(input);
expect(result.a).toBeInstanceOf(BoolArray);
expect(Array.from(result.a)).toEqual([true, false]);
expect(result.a2).toEqual(new Int16Array([1, 2, 3]));
@@ -93,57 +111,72 @@ describe('array', () => {
expect(result.a6).toEqual(new Float64Array([234243.555, 55654.679]));
});
+ test("should floatarray work", () => {
+ const typeinfo = Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a5: Type.float32Array(),
+ },
+ );
- test('should floatarray work', () => {
- const typeinfo = Type.struct({
- typeName: "example.foo"
- }, {
- a5: Type.float32Array(),
- })
-
- const fory = new Fory({ compatible: false, ref: true }); const serialize = fory.register(typeinfo).serializer;
- const input = fory.serialize({
- a5: new Float32Array([2.43, 654.4, 55]),
- }, serialize);
- const result = fory.deserialize(
- input
+ const fory = new Fory({ compatible: false, ref: true });
+ const serialize = fory.register(typeinfo).serializer;
+ const input = fory.serialize(
+ {
+ a5: new Float32Array([2.43, 654.4, 55]),
+ },
+ serialize,
);
- expect(result.a5[0]).toBeCloseTo(2.43)
- expect(result.a5[1]).toBeCloseTo(654.4)
- expect(result.a5[2]).toBeCloseTo(55)
+ const result = fory.deserialize(input);
+ expect(result.a5[0]).toBeCloseTo(2.43);
+ expect(result.a5[1]).toBeCloseTo(654.4);
+ expect(result.a5[2]).toBeCloseTo(55);
});
- test('should float16Array work', () => {
- const typeinfo = Type.struct({
- typeName: "example.foo"
- }, {
- a6: Type.float16Array(),
- })
+ test("should float16Array work", () => {
+ const typeinfo = Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a6: Type.float16Array(),
+ },
+ );
- const fory = new Fory({ compatible: false, ref: true }); const serialize = fory.register(typeinfo).serializer;
- const input = fory.serialize({
- a6: [1.5, 2.5, -4.5],
- }, serialize);
- const result = fory.deserialize(
- input
+ const fory = new Fory({ compatible: false, ref: true });
+ const serialize = fory.register(typeinfo).serializer;
+ const input = fory.serialize(
+ {
+ a6: [1.5, 2.5, -4.5],
+ },
+ serialize,
);
+ const result = fory.deserialize(input);
expect(result.a6).toBeInstanceOf(Float16Array as any);
- expect(Array.from(result.a6 as Iterable<number>)[0]).toBeCloseTo(1.5, 1)
- expect(Array.from(result.a6 as Iterable<number>)[1]).toBeCloseTo(2.5, 1)
- expect(Array.from(result.a6 as Iterable<number>)[2]).toBeCloseTo(-4.5, 1)
+ expect(Array.from(result.a6 as Iterable<number>)[0]).toBeCloseTo(1.5, 1);
+ expect(Array.from(result.a6 as Iterable<number>)[1]).toBeCloseTo(2.5, 1);
+ expect(Array.from(result.a6 as Iterable<number>)[2]).toBeCloseTo(-4.5, 1);
});
- test('should bfloat16Array work', () => {
- const typeinfo = Type.struct({
- typeName: "example.foo"
- }, {
- a7: Type.bfloat16Array(),
- });
+ test("should bfloat16Array work", () => {
+ const typeinfo = Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a7: Type.bfloat16Array(),
+ },
+ );
const fory = new Fory({ compatible: false, ref: true });
const serialize = fory.register(typeinfo).serializer;
- const input = fory.serialize({
- a7: [1.5, 2.5, -4.5],
- }, serialize);
+ const input = fory.serialize(
+ {
+ a7: [1.5, 2.5, -4.5],
+ },
+ serialize,
+ );
const result = fory.deserialize(input);
expect(result.a7).toBeInstanceOf(BFloat16Array);
expect(result.a7).toHaveLength(3);
@@ -152,12 +185,15 @@ describe('array', () => {
expect(result.a7.get(2)).toBeCloseTo(-4.5, 2);
});
- test('should bfloat16Array accept BFloat16Array', () => {
- const typeinfo = Type.struct({
- typeName: "example.foo"
- }, {
- a7: Type.bfloat16Array(),
- });
+ test("should bfloat16Array accept BFloat16Array", () => {
+ const typeinfo = Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a7: Type.bfloat16Array(),
+ },
+ );
const fory = new Fory({ compatible: false, ref: true });
const serialize = fory.register(typeinfo).serializer;
const arr = new BFloat16Array([1.25, -2.5, 0]);
@@ -170,7 +206,7 @@ describe('array', () => {
expect(result.a7.get(2)).toBe(0);
});
- test('should expose bool and reduced-precision array carriers', () => {
+ test("should expose bool and reduced-precision array carriers", () => {
const bools = new BoolArray([true, false, true]);
bools.setValue(1, true);
expect(Array.from(bools)).toEqual([true, true, true]);
@@ -184,41 +220,58 @@ describe('array', () => {
expect(Array.from(bf16)).toEqual([1.5, -2]);
});
- test('should write dense array protocol bytes in little-endian order', () => {
+ test("should write dense array protocol bytes in little-endian order", () => {
const fory = new Fory({ compatible: false, ref: true });
- const uint16Type = Type.struct({ typeName: 'example.uint16array' }, {
- values: Type.uint16Array(),
- });
+ const uint16Type = Type.struct(
+ { typeName: "example.uint16array" },
+ {
+ values: Type.uint16Array(),
+ },
+ );
const uint16Serializer = fory.register(uint16Type).serializer;
- const uint16Bytes = fory.serialize({
- values: new Uint16Array([0x1234, 0xabcd]),
- }, uint16Serializer);
+ const uint16Bytes = fory.serialize(
+ {
+ values: new Uint16Array([0x1234, 0xabcd]),
+ },
+ uint16Serializer,
+ );
expect(containsBytes(uint16Bytes, [0x34, 0x12, 0xcd, 0xab])).toBe(true);
- const float16Type = Type.struct({ typeName: 'example.float16array' }, {
- values: Type.float16Array(),
- });
+ const float16Type = Type.struct(
+ { typeName: "example.float16array" },
+ {
+ values: Type.float16Array(),
+ },
+ );
const float16Serializer = fory.register(float16Type).serializer;
- const float16Bytes = fory.serialize({
- values: new ForyFloat16Array([1, -2]),
- }, float16Serializer);
+ const float16Bytes = fory.serialize(
+ {
+ values: new ForyFloat16Array([1, -2]),
+ },
+ float16Serializer,
+ );
expect(containsBytes(float16Bytes, [0x00, 0x3c, 0x00, 0xc0])).toBe(true);
- const bfloat16Type = Type.struct({ typeName: 'example.bfloat16array' }, {
- values: Type.bfloat16Array(),
- });
+ const bfloat16Type = Type.struct(
+ { typeName: "example.bfloat16array" },
+ {
+ values: Type.bfloat16Array(),
+ },
+ );
const bfloat16Serializer = fory.register(bfloat16Type).serializer;
- const bfloat16Bytes = fory.serialize({
- values: new BFloat16Array([1, -2]),
- }, bfloat16Serializer);
+ const bfloat16Bytes = fory.serialize(
+ {
+ values: new BFloat16Array([1, -2]),
+ },
+ bfloat16Serializer,
+ );
expect(containsBytes(bfloat16Bytes, [0x80, 0x3f, 0x00, 0xc0])).toBe(true);
});
});
function containsBytes(bytes: Uint8Array, needle: number[]) {
- outer:
- for (let i = 0; i <= bytes.length - needle.length; i++) {
+ outer: for (let i = 0; i <= bytes.length - needle.length; i++) {
for (let j = 0; j < needle.length; j++) {
if (bytes[i + j] !== needle[j]) {
continue outer;
diff --git a/javascript/test/binary.test.ts b/javascript/test/binary.test.ts
index 5506e222b..164a008de 100644
--- a/javascript/test/binary.test.ts
+++ b/javascript/test/binary.test.ts
@@ -17,26 +17,22 @@
* under the License.
*/
-import Fory, { Type } from '../packages/core/index';
-import { describe, expect, test } from '@jest/globals';
+import Fory, { Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
-
-describe('binary', () => {
- test('should binary work', () => {
- const typeinfo = Type.struct("example.foo", {
- a: Type.binary()
- })
-
- const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(typeinfo).serializer;
- const input = fory.serialize({ a: new Uint8Array([1, 2, 3]) }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result instanceof Uint8Array)
- expect(result.a[0] === 1);
- expect(result.a[1] === 2);
- expect(result.a[2] === 3);
+describe("binary", () => {
+ test("should binary work", () => {
+ const typeinfo = Type.struct("example.foo", {
+ a: Type.binary(),
});
-});
+ const fory = new Fory({ compatible: false, ref: true });
+ const serializer = fory.register(typeinfo).serializer;
+ const input = fory.serialize({ a: new Uint8Array([1, 2, 3]) }, serializer);
+ const result = fory.deserialize(input);
+ expect(result instanceof Uint8Array);
+ expect(result.a[0] === 1);
+ expect(result.a[1] === 2);
+ expect(result.a[2] === 3);
+ });
+});
diff --git a/javascript/test/bool.test.ts b/javascript/test/bool.test.ts
index 482c63fa9..1ba88bf3b 100644
--- a/javascript/test/bool.test.ts
+++ b/javascript/test/bool.test.ts
@@ -17,27 +17,20 @@
* under the License.
*/
-import Fory from '../packages/core/index';
-import {describe, expect, test} from '@jest/globals';
-
-describe('bool', () => {
- test('should false work', () => {
+import Fory from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
+describe("bool", () => {
+ test("should false work", () => {
const fory = new Fory({ compatible: false, ref: true });
const input = fory.serialize(false);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual(false)
+ const result = fory.deserialize(input);
+ expect(result).toEqual(false);
});
- test('should true work', () => {
-
+ test("should true work", () => {
const fory = new Fory({ compatible: false, ref: true });
const input = fory.serialize(true);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual(true)
+ const result = fory.deserialize(input);
+ expect(result).toEqual(true);
});
});
-
diff --git a/javascript/test/crossLanguage.test.ts b/javascript/test/crossLanguage.test.ts
index e94b96ea3..ef9f88544 100644
--- a/javascript/test/crossLanguage.test.ts
+++ b/javascript/test/crossLanguage.test.ts
@@ -51,10 +51,7 @@ const Long = {
MIN_VALUE: BigInt("-9223372036854775808"),
};
-function decimal(
- unscaledValue: string | bigint | number,
- scale: number,
-): Decimal {
+function decimal(unscaledValue: string | bigint | number, scale: number): Decimal {
return new Decimal(unscaledValue, scale);
}
@@ -269,20 +266,11 @@ describe("bool", () => {
const item = deserializedData[index];
let serializedData;
if (index === 11) {
- serializedData = fory.serialize(
- item,
- fory.typeResolver.getSerializerById(TypeId.FLOAT32),
- );
+ serializedData = fory.serialize(item, fory.typeResolver.getSerializerById(TypeId.FLOAT32));
} else if (index === 12) {
- serializedData = fory.serialize(
- item,
- fory.typeResolver.getSerializerById(TypeId.FLOAT64),
- );
+ serializedData = fory.serialize(item, fory.typeResolver.getSerializerById(TypeId.FLOAT64));
} else if (index === 14) {
- serializedData = fory.serialize(
- item,
- fory.typeResolver.getSerializerById(TypeId.DATE),
- );
+ serializedData = fory.serialize(item, fory.typeResolver.getSerializerById(TypeId.DATE));
} else if (index === 15) {
serializedData = fory.serialize(
item,
@@ -294,10 +282,7 @@ describe("bool", () => {
fory.typeResolver.getSerializerById(TypeId.BOOL_ARRAY),
);
} else if (index === 17) {
- serializedData = fory.serialize(
- item,
- fory.typeResolver.getSerializerById(TypeId.BINARY),
- );
+ serializedData = fory.serialize(item, fory.typeResolver.getSerializerById(TypeId.BINARY));
} else if (index === 26) {
serializedData = colorSerialize(item);
} else {
@@ -815,8 +800,7 @@ describe("bool", () => {
expect(outer.list_field).toBeTruthy();
expect(outer.list_field.length).toBeGreaterThan(0);
const shared = outer.list_field[0];
- const setShared = outer.set_field.values().next()
- .value as RefOverrideElement;
+ const setShared = outer.set_field.values().next().value as RefOverrideElement;
expect(outer.list_field[1]).not.toBe(shared);
expect(setShared).not.toBe(shared);
expect(outer.map_field.get("k1")).not.toBe(shared);
@@ -1788,9 +1772,9 @@ describe("bool", () => {
// Deserialize struct from Java
let cursor = 0;
- const deserializedStruct: InstanceType<
- ReturnType<typeof buildClass>
- > | null = fory.deserialize(content.subarray(cursor));
+ const deserializedStruct: InstanceType<ReturnType<typeof buildClass>> | null = fory.deserialize(
+ content.subarray(cursor),
+ );
cursor += fory.readContext.reader.readGetCursor();
if (deserializedStruct === null) {
@@ -1818,14 +1802,8 @@ describe("bool", () => {
fory.register(RefInner);
@Type.struct(502, {
- inner1: Type.struct(501)
- .setTrackingRef(true)
- .setNullable(true)
- .setDynamic(Dynamic.FALSE),
- inner2: Type.struct(501)
- .setTrackingRef(true)
- .setNullable(true)
- .setDynamic(Dynamic.FALSE),
+ inner1: Type.struct(501).setTrackingRef(true).setNullable(true).setDynamic(Dynamic.FALSE),
+ inner2: Type.struct(501).setTrackingRef(true).setNullable(true).setDynamic(Dynamic.FALSE),
})
class RefOuter {
inner1: RefInner | null = null;
diff --git a/javascript/test/decimal.test.ts b/javascript/test/decimal.test.ts
index 6fef8fed1..c529cfa70 100644
--- a/javascript/test/decimal.test.ts
+++ b/javascript/test/decimal.test.ts
@@ -20,10 +20,7 @@
import Fory, { Decimal, Type } from "../packages/core/index";
import { describe, expect, test } from "@jest/globals";
-function decimal(
- unscaledValue: string | bigint | number,
- scale: number,
-): Decimal {
+function decimal(unscaledValue: string | bigint | number, scale: number): Decimal {
return new Decimal(unscaledValue, scale);
}
@@ -71,10 +68,7 @@ describe("decimal", () => {
note: "principal",
};
- const roundTrip = fory.deserialize(
- fory.serialize(value, serializer),
- serializer,
- ) as {
+ const roundTrip = fory.deserialize(fory.serialize(value, serializer), serializer) as {
amount: Decimal;
note: string;
};
@@ -87,15 +81,9 @@ describe("decimal", () => {
test("rejects non-canonical big decimal payloads", () => {
const fory = new Fory({ compatible: false });
const zeroBigEncoding = Buffer.from([0x01, 0xff, 0x28, 0x00, 0x01]);
- const trailingZeroPayload = Buffer.from([
- 0x01, 0xff, 0x28, 0x00, 0x09, 0x01, 0x00,
- ]);
+ const trailingZeroPayload = Buffer.from([0x01, 0xff, 0x28, 0x00, 0x09, 0x01, 0x00]);
- expect(() => fory.deserialize(zeroBigEncoding)).toThrow(
- /Invalid decimal magnitude length/,
- );
- expect(() => fory.deserialize(trailingZeroPayload)).toThrow(
- /trailing zero byte/,
- );
+ expect(() => fory.deserialize(zeroBigEncoding)).toThrow(/Invalid decimal magnitude length/);
+ expect(() => fory.deserialize(trailingZeroPayload)).toThrow(/trailing zero byte/);
});
});
diff --git a/javascript/test/depthLimit.test.ts b/javascript/test/depthLimit.test.ts
index 73c9bfe7e..d05b71bfd 100644
--- a/javascript/test/depthLimit.test.ts
+++ b/javascript/test/depthLimit.test.ts
@@ -17,69 +17,69 @@
* under the License.
*/
-import Fory, { Type } from '../packages/core/index';
-import { describe, expect, test } from '@jest/globals';
+import Fory, { Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
-describe('depth-limit', () => {
- describe('configuration', () => {
- test('should have default maxDepth of 50', () => {
+describe("depth-limit", () => {
+ describe("configuration", () => {
+ test("should have default maxDepth of 50", () => {
const fory = new Fory({ compatible: false });
expect(fory.readContext.maxDepth).toBe(50);
});
- test('should accept custom maxDepth', () => {
+ test("should accept custom maxDepth", () => {
const fory = new Fory({ compatible: false, maxDepth: 100 });
expect(fory.readContext.maxDepth).toBe(100);
});
- test('should initialize depth counter to 0', () => {
+ test("should initialize depth counter to 0", () => {
const fory = new Fory({ compatible: false });
expect(fory.readContext.depth).toBe(0);
});
- test('should reject maxDepth < 2', () => {
+ test("should reject maxDepth < 2", () => {
expect(() => new Fory({ compatible: false, maxDepth: 1 })).toThrow(
- 'maxDepth must be an integer >= 2 but got 1'
+ "maxDepth must be an integer >= 2 but got 1",
);
});
- test('should reject maxDepth = 0', () => {
+ test("should reject maxDepth = 0", () => {
expect(() => new Fory({ compatible: false, maxDepth: 0 })).toThrow(
- 'maxDepth must be an integer >= 2'
+ "maxDepth must be an integer >= 2",
);
});
- test('should reject negative maxDepth', () => {
+ test("should reject negative maxDepth", () => {
expect(() => new Fory({ compatible: false, maxDepth: -5 })).toThrow(
- 'maxDepth must be an integer >= 2'
+ "maxDepth must be an integer >= 2",
);
});
- test('should reject NaN maxDepth', () => {
+ test("should reject NaN maxDepth", () => {
expect(() => new Fory({ compatible: false, maxDepth: Number.NaN })).toThrow(
- 'maxDepth must be an integer >= 2'
+ "maxDepth must be an integer >= 2",
);
});
- test('should reject non-integer maxDepth', () => {
+ test("should reject non-integer maxDepth", () => {
expect(() => new Fory({ compatible: false, maxDepth: 2.5 })).toThrow(
- 'maxDepth must be an integer >= 2'
+ "maxDepth must be an integer >= 2",
);
});
});
- describe('depth operations', () => {
- test('should have incReadDepth method', () => {
+ describe("depth operations", () => {
+ test("should have incReadDepth method", () => {
const fory = new Fory({ compatible: false });
- expect(typeof fory.readContext.incReadDepth).toBe('function');
+ expect(typeof fory.readContext.incReadDepth).toBe("function");
});
- test('should have decReadDepth method', () => {
+ test("should have decReadDepth method", () => {
const fory = new Fory({ compatible: false });
- expect(typeof fory.readContext.decReadDepth).toBe('function');
+ expect(typeof fory.readContext.decReadDepth).toBe("function");
});
- test('incReadDepth should increment depth', () => {
+ test("incReadDepth should increment depth", () => {
const fory = new Fory({ compatible: false, maxDepth: 100 });
expect(fory.readContext.depth).toBe(0);
fory.readContext.incReadDepth();
@@ -88,7 +88,7 @@ describe('depth-limit', () => {
expect(fory.readContext.depth).toBe(2);
});
- test('decReadDepth should decrement depth', () => {
+ test("decReadDepth should decrement depth", () => {
const fory = new Fory({ compatible: false, maxDepth: 100 });
fory.readContext.incReadDepth();
fory.readContext.incReadDepth();
@@ -99,42 +99,45 @@ describe('depth-limit', () => {
expect(fory.readContext.depth).toBe(0);
});
- test('incReadDepth should throw when depth exceeds limit', () => {
+ test("incReadDepth should throw when depth exceeds limit", () => {
const fory = new Fory({ compatible: false, maxDepth: 2 });
fory.readContext.incReadDepth(); // depth = 1
fory.readContext.incReadDepth(); // depth = 2
expect(() => fory.readContext.incReadDepth()).toThrow(
- 'Deserialization depth limit exceeded: 3 > 2'
+ "Deserialization depth limit exceeded: 3 > 2",
);
});
- test('depth error message should mention limit and hint', () => {
+ test("depth error message should mention limit and hint", () => {
const fory = new Fory({ compatible: false, maxDepth: 5 });
try {
for (let i = 0; i < 6; i++) {
fory.readContext.incReadDepth();
}
- throw new Error('Should have thrown depth limit error');
+ throw new Error("Should have thrown depth limit error");
} catch (e) {
- expect(e.message).toContain('Deserialization depth limit exceeded');
- expect(e.message).toContain('5');
- expect(e.message).toContain('increase maxDepth if needed');
+ expect(e.message).toContain("Deserialization depth limit exceeded");
+ expect(e.message).toContain("5");
+ expect(e.message).toContain("increase maxDepth if needed");
}
});
});
- describe('deserialization with depth tracking', () => {
- test('should deserialize simple struct without depth error', () => {
+ describe("deserialization with depth tracking", () => {
+ test("should deserialize simple struct without depth error", () => {
const fory = new Fory({ compatible: false, maxDepth: 50 });
- const typeInfo = Type.struct({
- typeName: 'simple.struct',
- }, {
- a: Type.int32(),
- b: Type.string(),
- });
+ const typeInfo = Type.struct(
+ {
+ typeName: "simple.struct",
+ },
+ {
+ a: Type.int32(),
+ b: Type.string(),
+ },
+ );
const { serialize, deserialize } = fory.register(typeInfo);
- const data = { a: 42, b: 'hello' };
+ const data = { a: 42, b: "hello" };
const serialized = serialize(data);
const deserialized = deserialize(serialized);
@@ -142,18 +145,24 @@ describe('depth-limit', () => {
expect(fory.readContext.depth).toBe(0); // Should be reset after deserialization
});
- test('should deserialize nested struct within depth limit', () => {
+ test("should deserialize nested struct within depth limit", () => {
const fory = new Fory({ compatible: false, maxDepth: 10 });
- const nestedType = Type.struct({
- typeName: 'nested.outer',
- }, {
- value: Type.int32(),
- inner: Type.struct({
- typeName: 'nested.inner',
- }, {
- innerValue: Type.int32(),
- }).setNullable(true),
- });
+ const nestedType = Type.struct(
+ {
+ typeName: "nested.outer",
+ },
+ {
+ value: Type.int32(),
+ inner: Type.struct(
+ {
+ typeName: "nested.inner",
+ },
+ {
+ innerValue: Type.int32(),
+ },
+ ).setNullable(true),
+ },
+ );
const { serialize, deserialize } = fory.register(nestedType);
const data = { value: 1, inner: { innerValue: 2 } };
@@ -164,7 +173,7 @@ describe('depth-limit', () => {
expect(fory.readContext.depth).toBe(0); // Should be reset after deserialization
});
- test('should deserialize list of primitives within depth limit', () => {
+ test("should deserialize list of primitives within depth limit", () => {
const fory = new Fory({ compatible: false, maxDepth: 10 });
const arrayType = Type.list(Type.int32());
@@ -177,12 +186,15 @@ describe('depth-limit', () => {
expect(fory.readContext.depth).toBe(0); // Should be 0 after deserialization
});
- test('should deserialize map within depth limit', () => {
+ test("should deserialize map within depth limit", () => {
const fory = new Fory({ compatible: false, maxDepth: 10 });
const mapType = Type.map(Type.string(), Type.int32());
const { serialize, deserialize } = fory.register(mapType);
- const data = new Map([['a', 1], ['b', 2]]);
+ const data = new Map([
+ ["a", 1],
+ ["b", 2],
+ ]);
const serialized = serialize(data);
const deserialized = deserialize(serialized);
@@ -190,50 +202,58 @@ describe('depth-limit', () => {
expect(fory.readContext.depth).toBe(0); // Should be 0 after deserialization
});
- test('should throw when nested lists exceed maxDepth', () => {
+ test("should throw when nested lists exceed maxDepth", () => {
const fory = new Fory({ compatible: false, maxDepth: 2 });
const nestedArrayType = Type.list(Type.list(Type.list(Type.int32())));
const { serialize, deserialize } = fory.register(nestedArrayType);
const serialized = serialize([[[1]]]);
- expect(() => deserialize(serialized)).toThrow(
- 'Deserialization depth limit exceeded'
- );
+ expect(() => deserialize(serialized)).toThrow("Deserialization depth limit exceeded");
});
- test('should throw when nested monomorphic struct fields exceed maxDepth', () => {
+ test("should throw when nested monomorphic struct fields exceed maxDepth", () => {
const fory = new Fory({ compatible: false, maxDepth: 2 });
- const leaf = Type.struct({
- typeName: 'depth.leaf',
- }, {
- value: Type.int32(),
- });
- const mid = Type.struct({
- typeName: 'depth.mid',
- }, {
- leaf,
- });
- const root = Type.struct({
- typeName: 'depth.root',
- }, {
- mid,
- });
+ const leaf = Type.struct(
+ {
+ typeName: "depth.leaf",
+ },
+ {
+ value: Type.int32(),
+ },
+ );
+ const mid = Type.struct(
+ {
+ typeName: "depth.mid",
+ },
+ {
+ leaf,
+ },
+ );
+ const root = Type.struct(
+ {
+ typeName: "depth.root",
+ },
+ {
+ mid,
+ },
+ );
const { serialize, deserialize } = fory.register(root);
const serialized = serialize({ mid: { leaf: { value: 7 } } });
- expect(() => deserialize(serialized)).toThrow(
- 'Deserialization depth limit exceeded'
- );
+ expect(() => deserialize(serialized)).toThrow("Deserialization depth limit exceeded");
});
- test('should reset depth at start of each deserialization', () => {
+ test("should reset depth at start of each deserialization", () => {
const fory = new Fory({ compatible: false, maxDepth: 50 });
- const typeInfo = Type.struct({
- typeName: 'test.reset',
- }, {
- a: Type.int32(),
- });
+ const typeInfo = Type.struct(
+ {
+ typeName: "test.reset",
+ },
+ {
+ a: Type.int32(),
+ },
+ );
const { serialize, deserialize } = fory.register(typeInfo);
deserialize(serialize({ a: 1 }));
@@ -246,18 +266,24 @@ describe('depth-limit', () => {
});
});
- describe('cross-serialization depth limits', () => {
- test('should allow serialize with high limit and deserialize with low limit', () => {
- const serializeType = Type.struct({
- typeName: 'cross.test',
- }, {
- value: Type.int32(),
- next: Type.struct({
- typeName: 'cross.inner',
- }, {
- innerValue: Type.int32(),
- }).setNullable(true),
- });
+ describe("cross-serialization depth limits", () => {
+ test("should allow serialize with high limit and deserialize with low limit", () => {
+ const serializeType = Type.struct(
+ {
+ typeName: "cross.test",
+ },
+ {
+ value: Type.int32(),
+ next: Type.struct(
+ {
+ typeName: "cross.inner",
+ },
+ {
+ innerValue: Type.int32(),
+ },
+ ).setNullable(true),
+ },
+ );
// Serialize with high limit
const forySerialize = new Fory({ compatible: false, maxDepth: 100 });
@@ -274,7 +300,7 @@ describe('depth-limit', () => {
expect(deserialized).toEqual(data);
});
- test('should have independent depth tracking per Fory instance', () => {
+ test("should have independent depth tracking per Fory instance", () => {
const fory1 = new Fory({ compatible: false, maxDepth: 50 });
const fory2 = new Fory({ compatible: false, maxDepth: 100 });
@@ -291,25 +317,28 @@ describe('depth-limit', () => {
});
});
- describe('error scenarios', () => {
- test('error message should include helpful suggestion', () => {
+ describe("error scenarios", () => {
+ test("error message should include helpful suggestion", () => {
const fory = new Fory({ compatible: false, maxDepth: 2 });
try {
for (let i = 0; i < 3; i++) {
fory.readContext.incReadDepth();
}
- throw new Error('Should have thrown');
+ throw new Error("Should have thrown");
} catch (e) {
- expect(e.message).toContain('increase maxDepth if needed');
+ expect(e.message).toContain("increase maxDepth if needed");
}
});
- test('should recover after depth error when deserialization resets depth', () => {
- const typeInfo = Type.struct({
- typeName: 'test.recovery',
- }, {
- a: Type.int32(),
- });
+ test("should recover after depth error when deserialization resets depth", () => {
+ const typeInfo = Type.struct(
+ {
+ typeName: "test.recovery",
+ },
+ {
+ a: Type.int32(),
+ },
+ );
const fory = new Fory({ compatible: false, maxDepth: 50 });
const { serialize, deserialize } = fory.register(typeInfo);
@@ -326,13 +355,16 @@ describe('depth-limit', () => {
});
});
- describe('edge cases', () => {
- test('should handle maxDepth exactly equal to required depth', () => {
- const typeInfo = Type.struct({
- typeName: 'edge.exact',
- }, {
- a: Type.int32(),
- });
+ describe("edge cases", () => {
+ test("should handle maxDepth exactly equal to required depth", () => {
+ const typeInfo = Type.struct(
+ {
+ typeName: "edge.exact",
+ },
+ {
+ a: Type.int32(),
+ },
+ );
const fory = new Fory({ compatible: false, maxDepth: 2 });
const { serialize, deserialize } = fory.register(typeInfo);
@@ -341,17 +373,20 @@ describe('depth-limit', () => {
expect(result).toEqual({ a: 42 });
});
- test('should handle large maxDepth values', () => {
+ test("should handle large maxDepth values", () => {
const fory = new Fory({ compatible: false, maxDepth: 10000 });
expect(fory.readContext.maxDepth).toBe(10000);
});
- test('should handle minimum valid maxDepth of 2', () => {
- const typeInfo = Type.struct({
- typeName: 'edge.min',
- }, {
- a: Type.int32(),
- });
+ test("should handle minimum valid maxDepth of 2", () => {
+ const typeInfo = Type.struct(
+ {
+ typeName: "edge.min",
+ },
+ {
+ a: Type.int32(),
+ },
+ );
const fory = new Fory({ compatible: false, maxDepth: 2 });
expect(fory.readContext.maxDepth).toBe(2);
@@ -362,8 +397,8 @@ describe('depth-limit', () => {
});
});
- describe('configuration with other options', () => {
- test('should work with ref enabled', () => {
+ describe("configuration with other options", () => {
+ test("should work with ref enabled", () => {
const fory = new Fory({
compatible: false,
maxDepth: 50,
@@ -372,7 +407,7 @@ describe('depth-limit', () => {
expect(fory.readContext.maxDepth).toBe(50);
});
- test('should work with compatible mode enabled', () => {
+ test("should work with compatible mode enabled", () => {
const fory = new Fory({
maxDepth: 50,
compatible: true,
@@ -380,7 +415,7 @@ describe('depth-limit', () => {
expect(fory.readContext.maxDepth).toBe(50);
});
- test('should work with useSliceString option', () => {
+ test("should work with useSliceString option", () => {
const fory = new Fory({
compatible: false,
maxDepth: 50,
@@ -389,7 +424,7 @@ describe('depth-limit', () => {
expect(fory.readContext.maxDepth).toBe(50);
});
- test('should work with all options combined', () => {
+ test("should work with all options combined", () => {
const fory = new Fory({
maxDepth: 100,
ref: true,
diff --git a/javascript/test/enum.test.ts b/javascript/test/enum.test.ts
index ba01b0301..2a448818d 100644
--- a/javascript/test/enum.test.ts
+++ b/javascript/test/enum.test.ts
@@ -17,55 +17,49 @@
* under the License.
*/
-import Fory, { Type } from '../packages/core/index';
-import {describe, expect, test} from '@jest/globals';
+import Fory, { Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
-describe('enum', () => {
- test('should javascript number enum work', () => {
- const Foo = {
- f1: 1,
- f2: 2
- }
- const fory = new Fory({ compatible: false, ref: true });
- const {serialize, deserialize} = fory.register(Type.enum("example.foo", Foo))
- const input = serialize(Foo.f1);
- const result = deserialize(
- input
- );
- expect(result).toEqual(Foo.f1)
- });
+describe("enum", () => {
+ test("should javascript number enum work", () => {
+ const Foo = {
+ f1: 1,
+ f2: 2,
+ };
+ const fory = new Fory({ compatible: false, ref: true });
+ const { serialize, deserialize } = fory.register(Type.enum("example.foo", Foo));
+ const input = serialize(Foo.f1);
+ const result = deserialize(input);
+ expect(result).toEqual(Foo.f1);
+ });
- test('should javascript string enum work', () => {
- const Foo = {
- f1: "hello",
- f2: "world"
- }
- const fory = new Fory({ compatible: false, ref: true });
- fory.register(Type.enum("example.foo", Foo))
- const input = fory.serialize(Foo.f1);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual(Foo.f1)
- });
- test('should typescript number enum work', () => {
+ test("should javascript string enum work", () => {
+ const Foo = {
+ f1: "hello",
+ f2: "world",
+ };
+ const fory = new Fory({ compatible: false, ref: true });
+ fory.register(Type.enum("example.foo", Foo));
+ const input = fory.serialize(Foo.f1);
+ const result = fory.deserialize(input);
+ expect(result).toEqual(Foo.f1);
+ });
+ test("should typescript number enum work", () => {
enum Foo {
- f1 = 1,
- f2 = 2
+ f1 = 1,
+ f2 = 2,
}
const fory = new Fory({ compatible: false, ref: true });
- const {serialize, deserialize} = fory.register(Type.enum("example.foo", Foo))
+ const { serialize, deserialize } = fory.register(Type.enum("example.foo", Foo));
const input = serialize(Foo.f1);
- const result = deserialize(
- input
- );
- expect(result).toEqual(Foo.f1)
+ const result = deserialize(input);
+ expect(result).toEqual(Foo.f1);
});
- test('should preserve sparse numeric enum values', () => {
+ test("should preserve sparse numeric enum values", () => {
const Foo = {
unknown: 4096,
- ok: 8192
+ ok: 8192,
};
const fory = new Fory({ compatible: false, ref: true });
const { serialize, deserialize } = fory.register(Type.enum("example.foo", Foo));
@@ -74,17 +68,15 @@ describe('enum', () => {
expect(result).toEqual(Foo.ok);
});
- test('should typescript string enum work', () => {
+ test("should typescript string enum work", () => {
enum Foo {
- f1 = "hello",
- f2 = "world"
+ f1 = "hello",
+ f2 = "world",
}
const fory = new Fory({ compatible: false, ref: true });
- fory.register(Type.enum("example.foo", Foo))
+ fory.register(Type.enum("example.foo", Foo));
const input = fory.serialize(Foo.f1);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual(Foo.f1)
+ const result = fory.deserialize(input);
+ expect(result).toEqual(Foo.f1);
});
});
diff --git a/javascript/test/fory.test.ts b/javascript/test/fory.test.ts
index 947f37982..50b9b5194 100644
--- a/javascript/test/fory.test.ts
+++ b/javascript/test/fory.test.ts
@@ -17,79 +17,77 @@
* under the License.
*/
-import Fory, { TypeInfo, Type } from '../packages/core/index';
-import { describe, expect, test } from '@jest/globals';
-import { fromUint8Array } from '../packages/core/lib/platformBuffer';
+import Fory, { TypeInfo, Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
+import { fromUint8Array } from "../packages/core/lib/platformBuffer";
-describe('fory', () => {
- test('defaults to compatible mode unless explicitly set', () => {
- expect(new Fory().config.compatible).toBe(true);
- expect(new Fory({ compatible: false }).config.compatible).toBe(false);
- });
+describe("fory", () => {
+ test("defaults to compatible mode unless explicitly set", () => {
+ expect(new Fory().config.compatible).toBe(true);
+ expect(new Fory({ compatible: false }).config.compatible).toBe(false);
+ });
- test('should deserialize null work', () => {
- const fory = new Fory({ compatible: false });
+ test("should deserialize null work", () => {
+ const fory = new Fory({ compatible: false });
- expect(fory.deserialize(new Uint8Array([1, 253]))).toBe(null)
- });
+ expect(fory.deserialize(new Uint8Array([1, 253]))).toBe(null);
+ });
- test('should deserialize xlang disable work', () => {
- const fory = new Fory({ compatible: false });
- try {
- // bit 0 = xlang flag, bit 1 = oob flag
- // value 0 means xlang is disabled
- fory.deserialize(new Uint8Array([0]))
- throw new Error('unreachable code')
- } catch (error) {
- expect(error.message).toBe('support crosslanguage mode only');
- }
- });
+ test("should deserialize xlang disable work", () => {
+ const fory = new Fory({ compatible: false });
+ try {
+ // bit 0 = xlang flag, bit 1 = oob flag
+ // value 0 means xlang is disabled
+ fory.deserialize(new Uint8Array([0]));
+ throw new Error("unreachable code");
+ } catch (error) {
+ expect(error.message).toBe("support crosslanguage mode only");
+ }
+ });
- test('should deserialize oob mode work', () => {
- const fory = new Fory({ compatible: false });
- try {
- // bit 0 = xlang flag, bit 1 = oob flag
- // value 3 = xlang (1) + oob (2)
- fory.deserialize(new Uint8Array([3]))
- throw new Error('unreachable code')
- } catch (error) {
- expect(error.message).toBe('outofband mode is not supported now');
- }
- });
+ test("should deserialize oob mode work", () => {
+ const fory = new Fory({ compatible: false });
+ try {
+ // bit 0 = xlang flag, bit 1 = oob flag
+ // value 3 = xlang (1) + oob (2)
+ fory.deserialize(new Uint8Array([3]));
+ throw new Error("unreachable code");
+ } catch (error) {
+ expect(error.message).toBe("outofband mode is not supported now");
+ }
+ });
- test('can serialize and deserialize primitive types', () => {
- const typeinfo = Type.int8()
- testTypeInfo(typeinfo, 123)
+ test("can serialize and deserialize primitive types", () => {
+ const typeinfo = Type.int8();
+ testTypeInfo(typeinfo, 123);
- const typeinfo2 = Type.int16()
- testTypeInfo(typeinfo2, 123)
+ const typeinfo2 = Type.int16();
+ testTypeInfo(typeinfo2, 123);
- const typeinfo3 = Type.int32()
- testTypeInfo(typeinfo3, 123)
+ const typeinfo3 = Type.int32();
+ testTypeInfo(typeinfo3, 123);
- const typeinfo4 = Type.bool()
- testTypeInfo(typeinfo4, true)
+ const typeinfo4 = Type.bool();
+ testTypeInfo(typeinfo4, true);
- // has precision problem
- // const typeinfo5 = Type.float()
- // testTypeInfo(typeinfo5, 123.456)
+ // has precision problem
+ // const typeinfo5 = Type.float()
+ // testTypeInfo(typeinfo5, 123.456)
- const typeinfo6 = Type.float64()
- testTypeInfo(typeinfo6, 123.456789)
+ const typeinfo6 = Type.float64();
+ testTypeInfo(typeinfo6, 123.456789);
- const typeinfo7 = Type.binary()
- testTypeInfo(typeinfo7, new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3]));
+ const typeinfo7 = Type.binary();
+ testTypeInfo(typeinfo7, new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3]));
- const typeinfo8 = Type.string()
- testTypeInfo(typeinfo8, '123')
- })
+ const typeinfo8 = Type.string();
+ testTypeInfo(typeinfo8, "123");
+ });
- function testTypeInfo(typeinfo: TypeInfo, input: any, expected?: any) {
- const fory = new Fory({ compatible: false });
- const serialize = fory.register(typeinfo);
- const result = serialize.deserialize(
- serialize.serialize(input)
- );
- expect(result).toEqual(expected ?? input)
- }
+ function testTypeInfo(typeinfo: TypeInfo, input: any, expected?: any) {
+ const fory = new Fory({ compatible: false });
+ const serialize = fory.register(typeinfo);
+ const result = serialize.deserialize(serialize.serialize(input));
+ expect(result).toEqual(expected ?? input);
+ }
});
diff --git a/javascript/test/hps.test.ts b/javascript/test/hps.test.ts
index 189210ae1..471d278e3 100644
--- a/javascript/test/hps.test.ts
+++ b/javascript/test/hps.test.ts
@@ -17,27 +17,26 @@
* under the License.
*/
-import { BinaryReader } from '../packages/core/index';
-import hps from '../packages/hps/index';
-import { describe, expect, test } from '@jest/globals';
+import { BinaryReader } from "../packages/core/index";
+import hps from "../packages/hps/index";
+import { describe, expect, test } from "@jest/globals";
+const skipableDescribe = hps ? describe : describe.skip;
-const skipableDescribe = (hps ? describe : describe.skip);
+skipableDescribe("hps", () => {
+ test("should isLatin1 work", () => {
+ const { serializeString } = hps!;
+ for (let index = 0; index < 10000; index++) {
+ const bf = Buffer.alloc(100);
+ serializeString("hello", bf, 0);
+ var reader = new BinaryReader({});
+ reader.reset(bf);
+ expect(reader.stringWithHeader()).toBe("hello");
-skipableDescribe('hps', () => {
- test('should isLatin1 work', () => {
- const { serializeString } = hps!;
- for (let index = 0; index < 10000; index++) {
- const bf = Buffer.alloc(100);
- serializeString("hello", bf, 0);
- var reader = new BinaryReader({});
- reader.reset(bf);
- expect(reader.stringWithHeader()).toBe("hello")
-
- serializeString("😁", bf, 0);
- var reader = new BinaryReader({});
- reader.reset(bf);
- expect(reader.stringWithHeader()).toBe("😁")
- }
- });
+ serializeString("😁", bf, 0);
+ var reader = new BinaryReader({});
+ reader.reset(bf);
+ expect(reader.stringWithHeader()).toBe("😁");
+ }
+ });
});
diff --git a/javascript/test/io.test.ts b/javascript/test/io.test.ts
index 32049120c..4faea5f0c 100644
--- a/javascript/test/io.test.ts
+++ b/javascript/test/io.test.ts
@@ -17,417 +17,461 @@
* under the License.
*/
-import { fromUint8Array } from '../packages/core/lib/platformBuffer';
-import { BinaryReader } from '../packages/core/lib/reader';
-import { Config, RefFlags, UTF8, UTF16 } from '../packages/core/lib/type';
-import { BinaryWriter } from '../packages/core/lib/writer';
-import { describe, expect, test } from '@jest/globals';
-
+import { fromUint8Array } from "../packages/core/lib/platformBuffer";
+import { BinaryReader } from "../packages/core/lib/reader";
+import { Config, RefFlags, UTF8, UTF16 } from "../packages/core/lib/type";
+import { BinaryWriter } from "../packages/core/lib/writer";
+import { describe, expect, test } from "@jest/globals";
function num2Bin(num: number) {
- return (num >>> 0).toString(2);
+ return (num >>> 0).toString(2);
}
[
- {
- useSliceString: true,
- }
+ {
+ useSliceString: true,
+ },
].forEach((config: Config) => {
- describe('writer', () => {
- test('should unsigned int work', () => {
- const writer = new BinaryWriter(config);
- let len = 0;
- [
- 8,
- 16,
- 32,
- ].forEach((x, y) => {
- {
- writer[`writeUint${x}`](10);
- len += x / 8;
- var ab = writer.dump();
- expect(ab.byteLength).toBe(len);
- if (x === 64) {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getBigUint${x}`](writer.writeGetCursor() - x / 8, true)).toBe(BigInt(10));
- } else {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getUint${x}`](writer.writeGetCursor() - x / 8, true)).toBe(10);
- }
- expect(writer.writeGetCursor()).toBe(len);
- }
-
- {
- writer[`writeUint${x}`](-1);
- len += x / 8;
- var ab = writer.dump();
- expect(ab.byteLength).toBe(len);
- if (x === 64) {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getBigUint${x}`](writer.writeGetCursor() - x / 8, true)).toBe(BigInt(2 ** x) - BigInt(1));
- } else {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getUint${x}`](writer.writeGetCursor() - x / 8, true)).toBe(2 ** x - 1);
- }
- expect(writer.writeGetCursor()).toBe(len);
- }
-
- {
- writer[`writeUint${x}`](2 ** x);
- len += x / 8;
- var ab = writer.dump();
- expect(ab.byteLength).toBe(len);
- if (x === 64) {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getBigUint${x}`](writer.writeGetCursor() - x / 8, true)).toBe(BigInt(0));
- } else {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getUint${x}`](writer.writeGetCursor() - x / 8, true)).toBe(0);
- }
- expect(writer.writeGetCursor()).toBe(len);
- }
- })
-
-
- });
-
- test('should int work', () => {
- const writer = new BinaryWriter(config);
- let len = 0;
- [
- 8,
- 16,
- 32,
- ].forEach((x, y) => {
- {
- writer[`writeInt${x}`](10);
- len += x / 8;
- var ab = writer.dump();
- expect(ab.byteLength).toBe(len);
- if (x === 64) {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getBigInt${x}`](writer.writeGetCursor() - x / 8, true)).toBe(BigInt(10));
- } else {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getInt${x}`](writer.writeGetCursor() - x / 8, true)).toBe(10);
- }
- expect(writer.writeGetCursor()).toBe(len);
- }
-
- {
- writer[`writeInt${x}`](2 ** x);
- len += x / 8;
- var ab = writer.dump();
- expect(ab.byteLength).toBe(len);
- if (x === 64) {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getBigInt${x}`](writer.writeGetCursor() - x / 8, true)).toBe(BigInt(0));
- } else {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getInt${x}`](writer.writeGetCursor() - x / 8, true)).toBe(0);
- }
- expect(writer.writeGetCursor()).toBe(len);
- }
-
- {
- writer[`writeInt${x}`](-1);
- len += x / 8;
- var ab = writer.dump();
- expect(ab.byteLength).toBe(len);
- if (x === 64) {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getBigInt${x}`](writer.writeGetCursor() - x / 8, true)).toBe(BigInt(-1));
- } else {
- expect(new DataView(ab.buffer, ab.byteOffset)[`getInt${x}`](writer.writeGetCursor() - x / 8, true)).toBe(-1);
- }
- expect(writer.writeGetCursor()).toBe(len);
- }
- })
- });
-
- test('should varUInt32 work', () => {
- [
- 1,
- 2,
- 3,
- 4,
- ].forEach(x => {
- {
- const writer = new BinaryWriter(config);
- const value = (2 ** (x * 7)) - 1;
- writer.writeVarUInt32(value);
- const ab = writer.dump();
- expect(ab.byteLength).toBe(x);
- for (let index = 0; index < ab.byteLength - 1; index++) {
- expect(num2Bin(ab[index])).toBe('11111111');
- }
- expect(num2Bin(ab[ab.byteLength - 1])).toBe('1111111');
- const reader = new BinaryReader(config);
- reader.reset(ab);
- const vari32 = reader.readVarUInt32();
- expect(vari32).toBe(value);
- }
- {
- const writer = new BinaryWriter(config);
- const value = (2 ** (x * 7));
- writer.writeVarUInt32(value);
- const ab = writer.dump();
- expect(ab.byteLength).toBe(x + 1);
- for (let index = 0; index < ab.byteLength - 1; index++) {
- expect(num2Bin(ab[index])).toBe('10000000');
- }
- expect(num2Bin(ab[ab.byteLength - 1])).toBe('1');
- const reader = new BinaryReader(config);
- reader.reset(ab);
- const vari32 = reader.readVarUInt32();
- expect(vari32).toBe(value);
- }
- });
- });
-
- test('should varInt32 work', () => {
- const writer = new BinaryWriter(config);
- const value = -1;
- writer.writeVarInt32(value);
- const ab = writer.dump();
- expect(ab.byteLength).toBe(1);
- expect(num2Bin(ab[0])).toBe('1');
- const reader = new BinaryReader(config);
- reader.reset(ab);
- const vari32 = reader.readVarInt32();
- expect(vari32).toBe(value);
- });
-
- test('should short latin1 string work', () => {
- const writer = new BinaryWriter(config);
- writer.stringWithHeader("hello world");
- const ab = writer.dump();
- const reader = new BinaryReader(config);
- reader.reset(ab);
- const header = reader.readVarUint36Small();
- expect(header & 0b11).toBe(0);
- const len = header >>> 2;
- expect(len).toBe(11);
- const str = reader.stringLatin1(11);
- expect(str).toBe("hello world");
- });
-
- test('should long latin1 string work', () => {
- const writer = new BinaryWriter(config);
- const str = new Array(10).fill('hello world').join('');
- writer.stringWithHeader(str);
- const ab = writer.dump();
- const reader = new BinaryReader(config);
- reader.reset(ab);
- const header = reader.readVarUint36Small();
- expect(header & 0b11).toBe(0);
- const len = header >>> 2;
- expect(len).toBe(110);
- expect(reader.stringLatin1(len)).toBe(str);
- });
-
- test('should short utf8 string work', () => {
- const writer = new BinaryWriter(config);
- const str = new Array(1).fill('hello 你好 😁').join('');
- writer.stringWithHeader(str);
- const ab = writer.dump();
- const reader = new BinaryReader(config);
-
- {
- reader.reset(ab);
- const header = reader.readVarUint36Small();
- const type = header & 0b11;
- // Writer may choose UTF8 (2) or UTF16 (1) depending on platform
- expect(type === 1 || type === 2).toBe(true);
- }
- {
- reader.reset(ab);
- expect(reader.stringWithHeader()).toBe(str);
- }
- });
-
- test('should long utf8 string work', () => {
- const writer = new BinaryWriter(config);
- const str = new Array(10).fill('hello 你好 😁').join('');
- writer.stringWithHeader(str);
- const ab = writer.dump();
- const reader = new BinaryReader(config);
- {
- reader.reset(ab);
- const header = reader.readVarUint36Small();
- const type = header & 0b11;
- // Writer may choose UTF8 (2) or UTF16 (1) depending on platform
- expect(type === 1 || type === 2).toBe(true);
- }
- {
- reader.reset(ab);
- expect(reader.stringWithHeader()).toBe(str);
- }
- });
-
- test('should reject malformed string payloads', () => {
- const reader = new BinaryReader(config);
-
- reader.reset(new Uint8Array([(4 << 2) | UTF8, 0x61]));
- expect(() => reader.stringWithHeader()).toThrow(/Insufficient bytes for UTF-8 string/);
-
- reader.reset(new Uint8Array([(1 << 2) | UTF16, 0]));
- expect(() => reader.stringWithHeader()).toThrow(/UTF-16LE string length must be even/);
-
- reader.reset(new Uint8Array([3]));
- expect(() => reader.stringWithHeader()).toThrow(/Unsupported string encoding/);
- });
-
- test('should buffer work', () => {
- const writer = new BinaryWriter(config);
- writer.buffer(new Uint8Array([1, 2, 3, 4, 5]));
- const ab = writer.dump();
- const reader = new BinaryReader(config);
- reader.reset(ab);
- expect(ab.byteLength).toBe(5);
- expect(ab[0]).toBe(1);
- expect(ab[1]).toBe(2);
- expect(ab[2]).toBe(3);
- expect(ab[3]).toBe(4);
- expect(ab[4]).toBe(5);
- });
-
- test('should reject truncated buffer payloads', () => {
- const reader = new BinaryReader(config);
- reader.reset(new Uint8Array([1, 2]));
- expect(() => reader.buffer(3)).toThrow(/Insufficient bytes for buffer/);
- expect(() => reader.bufferRef(3)).toThrow(/Insufficient bytes for buffer reference/);
- expect(() => reader.bufferRefAt(1, 2)).toThrow(/Insufficient bytes for buffer reference/);
- });
-
- test('should bufferWithoutMemCheck work', () => {
- const writer = new BinaryWriter(config);
- writer.bufferWithoutMemCheck(fromUint8Array(new Uint8Array([1, 2, 3, 4, 5])), 5);
- const ab = writer.dump();
- const reader = new BinaryReader(config);
- reader.reset(ab);
- expect(ab.byteLength).toBe(5);
- expect(ab[0]).toBe(1);
- expect(ab[1]).toBe(2);
- expect(ab[2]).toBe(3);
- expect(ab[3]).toBe(4);
- expect(ab[4]).toBe(5);
- });
-
- test('should setUint32Position work', () => {
- const writer = new BinaryWriter(config);
- writer.writeSkip(10);
- writer.setUint32Position(0, 100);
- writer.setUint32Position(5, 100);
- const ab = writer.dump();
- expect(ab.byteLength).toBe(10);
- expect(ab[0]).toBe(100);
- expect(ab[5]).toBe(100);
- });
-
- test('should float work', () => {
- const writer = new BinaryWriter(config);
- writer.writeFloat32(10.01);
- const ab = writer.dump();
- expect(ab.byteLength).toBe(4);
- const reader = new BinaryReader(config);
- reader.reset(ab);
- expect(reader.readFloat32().toFixed(2)).toBe((10.01).toFixed(2));
- });
-
- test('should float64 work', () => {
- const writer = new BinaryWriter(config);
- writer.writeFloat64(10.01);
- const ab = writer.dump();
- expect(ab.byteLength).toBe(8);
- const reader = new BinaryReader(config);
- reader.reset(ab);
- expect(reader.readFloat64().toFixed(2)).toBe((10.01).toFixed(2));
- });
-
- test('should reserve work', () => {
- const writer = new BinaryWriter(config);
- const byteLength = writer.getByteLen();
- const cursor = writer.writeGetCursor();
- const reserved = writer.getReserved();
- writer.reserve(10);
-
- expect(writer.getReserved()).toBe(reserved + 10);
- expect(writer.getByteLen()).toBe(byteLength);
- expect(writer.writeGetCursor()).toBe(cursor);
- });
-
- test('should reserve work', () => {
- const writer = new BinaryWriter(config);
- const byteLength = writer.getByteLen();
- const cursor = writer.writeGetCursor();
- const reserved = writer.getReserved();
- writer.reserve(1024 * 101);
-
- expect(writer.getReserved()).toBe(reserved + 1024 * 101);
- expect(writer.getByteLen()).toBe(byteLength * 2 + 1024 * 101);
- expect(writer.writeGetCursor()).toBe(cursor);
- });
-
- test('should reset work', () => {
- const writer = new BinaryWriter(config);
- writer.writeInt16(100);
- writer.reset();
- expect(writer.writeGetCursor()).toBe(0);
- expect(writer.getReserved()).toBe(0);
- });
-
- test('should int24 work', () => {
- const writer = new BinaryWriter(config);
- writer.writeInt24( (20 << 8) | 10);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readInt8()).toBe(10);
- expect(reader.readInt16()).toBe(20);
- });
-
- test('should varUInt64 work', () => {
- const writer = new BinaryWriter(config);
- writer.writeVarUInt64(2n ** 2n);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readVarUInt64()).toBe(2n ** 2n);
- });
-
- test('should varUInt64 work', () => {
- const writer = new BinaryWriter(config);
- writer.writeVarUInt64(2n ** 63n);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readVarUInt64()).toBe(2n ** 63n);
- });
-
- test('should varInt64 work', () => {
- const writer = new BinaryWriter(config);
- writer.writeVarInt64(2n ** 2n);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readVarInt64()).toBe(2n ** 2n);
- });
-
- test('should varInt64 work', () => {
- const writer = new BinaryWriter(config);
- writer.writeVarInt64(2n ** 62n);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readVarInt64()).toBe(2n ** 62n);
- });
-
- test('should silong work', () => {
- const writer = new BinaryWriter(config);
- writer.writeSliInt64(2n ** 2n);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readSliInt64()).toBe(2n ** 2n);
- });
-
- test('should silong work', () => {
- const writer = new BinaryWriter(config);
- writer.writeSliInt64(2n ** 62n);
- const ab = writer.dump();
- const reader = new BinaryReader({});
- reader.reset(ab)
- expect(reader.readSliInt64()).toBe(2n ** 62n);
- });
+ describe("writer", () => {
+ test("should unsigned int work", () => {
+ const writer = new BinaryWriter(config);
+ let len = 0;
+ [8, 16, 32].forEach((x, y) => {
+ {
+ writer[`writeUint${x}`](10);
+ len += x / 8;
+ var ab = writer.dump();
+ expect(ab.byteLength).toBe(len);
+ if (x === 64) {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getBigUint${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(BigInt(10));
+ } else {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getUint${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(10);
+ }
+ expect(writer.writeGetCursor()).toBe(len);
+ }
+
+ {
+ writer[`writeUint${x}`](-1);
+ len += x / 8;
+ var ab = writer.dump();
+ expect(ab.byteLength).toBe(len);
+ if (x === 64) {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getBigUint${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(BigInt(2 ** x) - BigInt(1));
+ } else {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getUint${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(2 ** x - 1);
+ }
+ expect(writer.writeGetCursor()).toBe(len);
+ }
+
+ {
+ writer[`writeUint${x}`](2 ** x);
+ len += x / 8;
+ var ab = writer.dump();
+ expect(ab.byteLength).toBe(len);
+ if (x === 64) {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getBigUint${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(BigInt(0));
+ } else {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getUint${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(0);
+ }
+ expect(writer.writeGetCursor()).toBe(len);
+ }
+ });
+ });
+
+ test("should int work", () => {
+ const writer = new BinaryWriter(config);
+ let len = 0;
+ [8, 16, 32].forEach((x, y) => {
+ {
+ writer[`writeInt${x}`](10);
+ len += x / 8;
+ var ab = writer.dump();
+ expect(ab.byteLength).toBe(len);
+ if (x === 64) {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getBigInt${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(BigInt(10));
+ } else {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getInt${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(10);
+ }
+ expect(writer.writeGetCursor()).toBe(len);
+ }
+
+ {
+ writer[`writeInt${x}`](2 ** x);
+ len += x / 8;
+ var ab = writer.dump();
+ expect(ab.byteLength).toBe(len);
+ if (x === 64) {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getBigInt${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(BigInt(0));
+ } else {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getInt${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(0);
+ }
+ expect(writer.writeGetCursor()).toBe(len);
+ }
+
+ {
+ writer[`writeInt${x}`](-1);
+ len += x / 8;
+ var ab = writer.dump();
+ expect(ab.byteLength).toBe(len);
+ if (x === 64) {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getBigInt${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(BigInt(-1));
+ } else {
+ expect(
+ new DataView(ab.buffer, ab.byteOffset)[`getInt${x}`](
+ writer.writeGetCursor() - x / 8,
+ true,
+ ),
+ ).toBe(-1);
+ }
+ expect(writer.writeGetCursor()).toBe(len);
+ }
+ });
+ });
+
+ test("should varUInt32 work", () => {
+ [1, 2, 3, 4].forEach((x) => {
+ {
+ const writer = new BinaryWriter(config);
+ const value = 2 ** (x * 7) - 1;
+ writer.writeVarUInt32(value);
+ const ab = writer.dump();
+ expect(ab.byteLength).toBe(x);
+ for (let index = 0; index < ab.byteLength - 1; index++) {
+ expect(num2Bin(ab[index])).toBe("11111111");
+ }
+ expect(num2Bin(ab[ab.byteLength - 1])).toBe("1111111");
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ const vari32 = reader.readVarUInt32();
+ expect(vari32).toBe(value);
+ }
+ {
+ const writer = new BinaryWriter(config);
+ const value = 2 ** (x * 7);
+ writer.writeVarUInt32(value);
+ const ab = writer.dump();
+ expect(ab.byteLength).toBe(x + 1);
+ for (let index = 0; index < ab.byteLength - 1; index++) {
+ expect(num2Bin(ab[index])).toBe("10000000");
+ }
+ expect(num2Bin(ab[ab.byteLength - 1])).toBe("1");
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ const vari32 = reader.readVarUInt32();
+ expect(vari32).toBe(value);
+ }
+ });
+ });
+
+ test("should varInt32 work", () => {
+ const writer = new BinaryWriter(config);
+ const value = -1;
+ writer.writeVarInt32(value);
+ const ab = writer.dump();
+ expect(ab.byteLength).toBe(1);
+ expect(num2Bin(ab[0])).toBe("1");
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ const vari32 = reader.readVarInt32();
+ expect(vari32).toBe(value);
+ });
+
+ test("should short latin1 string work", () => {
+ const writer = new BinaryWriter(config);
+ writer.stringWithHeader("hello world");
+ const ab = writer.dump();
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ const header = reader.readVarUint36Small();
+ expect(header & 0b11).toBe(0);
+ const len = header >>> 2;
+ expect(len).toBe(11);
+ const str = reader.stringLatin1(11);
+ expect(str).toBe("hello world");
+ });
+
+ test("should long latin1 string work", () => {
+ const writer = new BinaryWriter(config);
+ const str = new Array(10).fill("hello world").join("");
+ writer.stringWithHeader(str);
+ const ab = writer.dump();
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ const header = reader.readVarUint36Small();
+ expect(header & 0b11).toBe(0);
+ const len = header >>> 2;
+ expect(len).toBe(110);
+ expect(reader.stringLatin1(len)).toBe(str);
+ });
+
+ test("should short utf8 string work", () => {
+ const writer = new BinaryWriter(config);
+ const str = new Array(1).fill("hello 你好 😁").join("");
+ writer.stringWithHeader(str);
+ const ab = writer.dump();
+ const reader = new BinaryReader(config);
+
+ {
+ reader.reset(ab);
+ const header = reader.readVarUint36Small();
+ const type = header & 0b11;
+ // Writer may choose UTF8 (2) or UTF16 (1) depending on platform
+ expect(type === 1 || type === 2).toBe(true);
+ }
+ {
+ reader.reset(ab);
+ expect(reader.stringWithHeader()).toBe(str);
+ }
+ });
+
+ test("should long utf8 string work", () => {
+ const writer = new BinaryWriter(config);
+ const str = new Array(10).fill("hello 你好 😁").join("");
+ writer.stringWithHeader(str);
+ const ab = writer.dump();
+ const reader = new BinaryReader(config);
+ {
+ reader.reset(ab);
+ const header = reader.readVarUint36Small();
+ const type = header & 0b11;
+ // Writer may choose UTF8 (2) or UTF16 (1) depending on platform
+ expect(type === 1 || type === 2).toBe(true);
+ }
+ {
+ reader.reset(ab);
+ expect(reader.stringWithHeader()).toBe(str);
+ }
+ });
+
+ test("should reject malformed string payloads", () => {
+ const reader = new BinaryReader(config);
+
+ reader.reset(new Uint8Array([(4 << 2) | UTF8, 0x61]));
+ expect(() => reader.stringWithHeader()).toThrow(/Insufficient bytes for UTF-8 string/);
+
+ reader.reset(new Uint8Array([(1 << 2) | UTF16, 0]));
+ expect(() => reader.stringWithHeader()).toThrow(/UTF-16LE string length must be even/);
+
+ reader.reset(new Uint8Array([3]));
+ expect(() => reader.stringWithHeader()).toThrow(/Unsupported string encoding/);
+ });
+
+ test("should buffer work", () => {
+ const writer = new BinaryWriter(config);
+ writer.buffer(new Uint8Array([1, 2, 3, 4, 5]));
+ const ab = writer.dump();
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ expect(ab.byteLength).toBe(5);
+ expect(ab[0]).toBe(1);
+ expect(ab[1]).toBe(2);
+ expect(ab[2]).toBe(3);
+ expect(ab[3]).toBe(4);
+ expect(ab[4]).toBe(5);
+ });
+
+ test("should reject truncated buffer payloads", () => {
+ const reader = new BinaryReader(config);
+ reader.reset(new Uint8Array([1, 2]));
+ expect(() => reader.buffer(3)).toThrow(/Insufficient bytes for buffer/);
+ expect(() => reader.bufferRef(3)).toThrow(/Insufficient bytes for buffer reference/);
+ expect(() => reader.bufferRefAt(1, 2)).toThrow(/Insufficient bytes for buffer reference/);
+ });
+
+ test("should bufferWithoutMemCheck work", () => {
+ const writer = new BinaryWriter(config);
+ writer.bufferWithoutMemCheck(fromUint8Array(new Uint8Array([1, 2, 3, 4, 5])), 5);
+ const ab = writer.dump();
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ expect(ab.byteLength).toBe(5);
+ expect(ab[0]).toBe(1);
+ expect(ab[1]).toBe(2);
+ expect(ab[2]).toBe(3);
+ expect(ab[3]).toBe(4);
+ expect(ab[4]).toBe(5);
+ });
+
+ test("should setUint32Position work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeSkip(10);
+ writer.setUint32Position(0, 100);
+ writer.setUint32Position(5, 100);
+ const ab = writer.dump();
+ expect(ab.byteLength).toBe(10);
+ expect(ab[0]).toBe(100);
+ expect(ab[5]).toBe(100);
+ });
+
+ test("should float work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeFloat32(10.01);
+ const ab = writer.dump();
+ expect(ab.byteLength).toBe(4);
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ expect(reader.readFloat32().toFixed(2)).toBe((10.01).toFixed(2));
+ });
+
+ test("should float64 work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeFloat64(10.01);
+ const ab = writer.dump();
+ expect(ab.byteLength).toBe(8);
+ const reader = new BinaryReader(config);
+ reader.reset(ab);
+ expect(reader.readFloat64().toFixed(2)).toBe((10.01).toFixed(2));
+ });
+
+ test("should reserve work", () => {
+ const writer = new BinaryWriter(config);
+ const byteLength = writer.getByteLen();
+ const cursor = writer.writeGetCursor();
+ const reserved = writer.getReserved();
+ writer.reserve(10);
+
+ expect(writer.getReserved()).toBe(reserved + 10);
+ expect(writer.getByteLen()).toBe(byteLength);
+ expect(writer.writeGetCursor()).toBe(cursor);
+ });
+
+ test("should reserve work", () => {
+ const writer = new BinaryWriter(config);
+ const byteLength = writer.getByteLen();
+ const cursor = writer.writeGetCursor();
+ const reserved = writer.getReserved();
+ writer.reserve(1024 * 101);
+
+ expect(writer.getReserved()).toBe(reserved + 1024 * 101);
+ expect(writer.getByteLen()).toBe(byteLength * 2 + 1024 * 101);
+ expect(writer.writeGetCursor()).toBe(cursor);
+ });
+
+ test("should reset work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeInt16(100);
+ writer.reset();
+ expect(writer.writeGetCursor()).toBe(0);
+ expect(writer.getReserved()).toBe(0);
+ });
+
+ test("should int24 work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeInt24((20 << 8) | 10);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readInt8()).toBe(10);
+ expect(reader.readInt16()).toBe(20);
+ });
+
+ test("should varUInt64 work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeVarUInt64(2n ** 2n);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readVarUInt64()).toBe(2n ** 2n);
+ });
+
+ test("should varUInt64 work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeVarUInt64(2n ** 63n);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readVarUInt64()).toBe(2n ** 63n);
+ });
+
+ test("should varInt64 work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeVarInt64(2n ** 2n);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readVarInt64()).toBe(2n ** 2n);
+ });
+
+ test("should varInt64 work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeVarInt64(2n ** 62n);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readVarInt64()).toBe(2n ** 62n);
+ });
+
+ test("should silong work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeSliInt64(2n ** 2n);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readSliInt64()).toBe(2n ** 2n);
+ });
+
+ test("should silong work", () => {
+ const writer = new BinaryWriter(config);
+ writer.writeSliInt64(2n ** 62n);
+ const ab = writer.dump();
+ const reader = new BinaryReader({});
+ reader.reset(ab);
+ expect(reader.readSliInt64()).toBe(2n ** 62n);
});
-})
+ });
+});
diff --git a/javascript/test/map.test.ts b/javascript/test/map.test.ts
index b03cf01b7..8f598ec6f 100644
--- a/javascript/test/map.test.ts
+++ b/javascript/test/map.test.ts
@@ -17,31 +17,46 @@
* under the License.
*/
-import Fory, { Type } from '../packages/core/index';
-import {describe, expect, test} from '@jest/globals';
-
-describe('map', () => {
- test('should map work', () => {
+import Fory, { Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
+describe("map", () => {
+ test("should map work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const input = fory.serialize(new Map([["foo", "bar"], ["foo2", "bar2"]]));
- const result = fory.deserialize(
- input
+ const input = fory.serialize(
+ new Map([
+ ["foo", "bar"],
+ ["foo2", "bar2"],
+ ]),
+ );
+ const result = fory.deserialize(input);
+ expect(result).toEqual(
+ new Map([
+ ["foo", "bar"],
+ ["foo2", "bar2"],
+ ]),
);
- expect(result).toEqual(new Map([["foo", "bar"],["foo2", "bar2"]]))
});
- test('should map specific type work', () => {
-
+ test("should map specific type work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const { serialize, deserialize } = fory.register(Type.struct("class.foo", {
- f1: Type.map(Type.string(), Type.int32())
- }))
+ const { serialize, deserialize } = fory.register(
+ Type.struct("class.foo", {
+ f1: Type.map(Type.string(), Type.int32()),
+ }),
+ );
const bin = serialize({
- f1: new Map([["hello", 123], ["world", 456]]),
- })
+ f1: new Map([
+ ["hello", 123],
+ ["world", 456],
+ ]),
+ });
const result = deserialize(bin);
- expect(result).toEqual({ f1: new Map([["hello", 123],["world", 456]])})
+ expect(result).toEqual({
+ f1: new Map([
+ ["hello", 123],
+ ["world", 456],
+ ]),
+ });
});
});
-
diff --git a/javascript/test/number.test.ts b/javascript/test/number.test.ts
index 354696425..c1e84754f 100644
--- a/javascript/test/number.test.ts
+++ b/javascript/test/number.test.ts
@@ -17,198 +17,241 @@
* under the License.
*/
-import Fory, { Type } from '../packages/core/index';
-import { describe, expect, test } from '@jest/globals';
-
-describe('number', () => {
- test('should i8 work', () => {
+import Fory, { Type } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
+describe("number", () => {
+ test("should i8 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serialize = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.int8()
- })).serializer;
+ const serialize = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.int8(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1 }, serialize);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual({ a: 1 })
+ const result = fory.deserialize(input);
+ expect(result).toEqual({ a: 1 });
});
- test('should i16 work', () => {
-
+ test("should i16 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serialize = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.int16()
- })).serializer;
+ const serialize = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.int16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1 }, serialize);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual({ a: 1 })
+ const result = fory.deserialize(input);
+ expect(result).toEqual({ a: 1 });
});
- test('should i32 work', () => {
-
+ test("should i32 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.int32()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.int32(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1 }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual({ a: 1 })
+ const result = fory.deserialize(input);
+ expect(result).toEqual({ a: 1 });
});
- test('should i64 work', () => {
-
+ test("should i64 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.int64()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.int64(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1 }, serializer);
- const result = fory.deserialize(
- input
- );
- result.a = Number(result.a)
- expect(result).toEqual({ a: 1 })
+ const result = fory.deserialize(input);
+ result.a = Number(result.a);
+ expect(result).toEqual({ a: 1 });
});
- test('should float32 work', () => {
-
+ test("should float32 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.float32()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.float32(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1.2 }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result.a).toBeCloseTo(1.2)
+ const result = fory.deserialize(input);
+ expect(result.a).toBeCloseTo(1.2);
});
- test('should float64 work', () => {
-
+ test("should float64 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.float64()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.float64(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1.2 }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result.a).toBeCloseTo(1.2)
+ const result = fory.deserialize(input);
+ expect(result.a).toBeCloseTo(1.2);
});
- test('should float16 work', () => {
-
+ test("should float16 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.float16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.float16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1.2 }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result.a).toBeCloseTo(1.2, 1)
+ const result = fory.deserialize(input);
+ expect(result.a).toBeCloseTo(1.2, 1);
});
- test('should float16 NAN work', () => {
-
+ test("should float16 NAN work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.float16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.float16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: NaN }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result.a).toBe(NaN)
+ const result = fory.deserialize(input);
+ expect(result.a).toBe(NaN);
});
- test('should float16 Infinity work', () => {
-
+ test("should float16 Infinity work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.float16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.float16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: Infinity }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result.a).toBeCloseTo(Infinity)
+ const result = fory.deserialize(input);
+ expect(result.a).toBeCloseTo(Infinity);
});
- test('should bfloat16 work', () => {
+ test("should bfloat16 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.bfloat16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.bfloat16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1.5 }, serializer);
const result = fory.deserialize(input);
expect(result.a).toBeCloseTo(1.5, 2);
});
- test('should bfloat16 accept number', () => {
+ test("should bfloat16 accept number", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.bfloat16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.bfloat16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1.5 }, serializer);
const result = fory.deserialize(input);
expect(result.a).toBeCloseTo(1.5, 2);
});
- test('should bfloat16 NaN work', () => {
+ test("should bfloat16 NaN work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.bfloat16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.bfloat16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: NaN }, serializer);
const result = fory.deserialize(input);
expect(Number.isNaN(result.a)).toBe(true);
});
- test('should bfloat16 Infinity work', () => {
+ test("should bfloat16 Infinity work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.bfloat16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.bfloat16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: Infinity }, serializer);
const result = fory.deserialize(input);
expect(result.a).toBe(Infinity);
});
- test('should bfloat16 zero and neg zero round-trip', () => {
+ test("should bfloat16 zero and neg zero round-trip", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.bfloat16(),
- b: Type.bfloat16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.bfloat16(),
+ b: Type.bfloat16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 0, b: -0 }, serializer);
const result = fory.deserialize(input);
expect(result.a).toBe(0);
@@ -217,85 +260,120 @@ describe('number', () => {
expect(1 / result.b).toBe(-Infinity);
});
- test('should uint8 work', () => {
+ test("should uint8 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint8()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint8(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 255 }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 255 });
});
- test('should uint16 work', () => {
+ test("should uint16 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint16()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint16(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 65535 }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 65535 });
});
- test('should uint32 work', () => {
+ test("should uint32 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint32()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint32(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 4294967295 }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 4294967295 });
});
- test('should varUInt32 work', () => {
+ test("should varUInt32 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint32()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint32(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1000000 }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 1000000 });
});
- test('should uint64 work', () => {
+ test("should uint64 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint64()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint64(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 18446744073709551615n }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 18446744073709551615n });
});
- test('should varUInt64 work', () => {
+ test("should varUInt64 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint64()
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint64(),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1n }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 1n });
});
- test('should taggedUInt64 work', () => {
+ test("should taggedUInt64 work", () => {
const fory = new Fory({ compatible: false, ref: true });
- const serializer = fory.register(Type.struct({
- typeName: "example.foo"
- }, {
- a: Type.uint64({ encoding: "tagged" })
- })).serializer;
+ const serializer = fory.register(
+ Type.struct(
+ {
+ typeName: "example.foo",
+ },
+ {
+ a: Type.uint64({ encoding: "tagged" }),
+ },
+ ),
+ ).serializer;
const input = fory.serialize({ a: 1n }, serializer);
const result = fory.deserialize(input);
expect(result).toEqual({ a: 1n });
diff --git a/javascript/test/object.test.ts b/javascript/test/object.test.ts
index b9f926284..0e9a4b8b1 100644
--- a/javascript/test/object.test.ts
+++ b/javascript/test/object.test.ts
@@ -17,14 +17,14 @@
* under the License.
*/
-import Fory, { Type, TypeInfo } from '../packages/core/index';
-import { describe, expect, test } from '@jest/globals';
-import * as beautify from 'js-beautify';
+import Fory, { Type, TypeInfo } from "../packages/core/index";
+import { describe, expect, test } from "@jest/globals";
+import * as beautify from "js-beautify";
-describe('object', () => {
- test('should descoration work', () => {
+describe("object", () => {
+ test("should descoration work", () => {
@Type.struct({
- typeName: "example.foo"
+ typeName: "example.foo",
})
class Foo {
@Type.int32()
@@ -35,16 +35,14 @@ describe('object', () => {
const foo = new Foo();
foo.a = 123;
const input = serialize(foo);
- const result = deserialize(
- input
- );
+ const result = deserialize(input);
expect(result instanceof Foo);
- expect(result).toEqual({ a: 123 })
+ expect(result).toEqual({ a: 123 });
});
- test('should descoration work2', () => {
+ test("should descoration work2", () => {
@Type.struct("example.foo")
class Foo {
@Type.int32()
@@ -55,152 +53,151 @@ describe('object', () => {
const foo = new Foo();
foo.a = 123;
- const input = fory.serialize(foo)
+ const input = fory.serialize(foo);
const result = fory.deserialize(input);
expect(result instanceof Foo);
- expect(result).toEqual({ a: 123 })
+ expect(result).toEqual({ a: 123 });
});
- test('should object work', () => {
+ test("should object work", () => {
const typeInfo = Type.struct("example.foo", {
a: Type.struct("example.bar", {
- b: Type.string()
- })
- })
+ b: Type.string(),
+ }),
+ });
const fory = new Fory({ compatible: false, ref: true });
const { serialize, deserialize } = fory.register(typeInfo);
const input = serialize({ a: { b: "hel" } });
- const result = deserialize(
- input
- );
- expect(result).toEqual({ a: { b: "hel" } })
+ const result = deserialize(input);
+ expect(result).toEqual({ a: { b: "hel" } });
});
-
- test('should null value work', () => {
+ test("should null value work", () => {
const typeInfo = Type.struct("example.foo", {
a: Type.struct("example.bar", {
- b: Type.string()
- }).setNullable(true)
- })
+ b: Type.string(),
+ }).setNullable(true),
+ });
const fory = new Fory({ compatible: false, ref: true });
const { serialize, deserialize } = fory.register(typeInfo);
const input = serialize({ a: null });
- const result = deserialize(
- input
- );
- expect(result).toEqual({ a: null })
+ const result = deserialize(input);
+ expect(result).toEqual({ a: null });
});
- test('should object in array work', () => {
- const typeInfo = Type.struct('example.foo', {
- a: Type.list(Type.struct('example.bar', {
- b: Type.string(),
- c: Type.bool(),
- d: Type.int32(),
- e: Type.int64(),
- f: Type.binary(),
- }))
- })
+ test("should object in array work", () => {
+ const typeInfo = Type.struct("example.foo", {
+ a: Type.list(
+ Type.struct("example.bar", {
+ b: Type.string(),
+ c: Type.bool(),
+ d: Type.int32(),
+ e: Type.int64(),
+ f: Type.binary(),
+ }),
+ ),
+ });
const fory = new Fory({ compatible: false, ref: true });
const serializer = fory.register(typeInfo).serializer;
- const input = fory.serialize({ a: [{ b: "hel", c: true, d: 123, e: 123, f: new Uint8Array([1, 2, 3]) }] }, serializer);
- const result = fory.deserialize(
- input
+ const input = fory.serialize(
+ { a: [{ b: "hel", c: true, d: 123, e: 123, f: new Uint8Array([1, 2, 3]) }] },
+ serializer,
);
- result.a.forEach(x => x.e = Number(x.e))
- expect(result).toEqual({ a: [{ b: "hel", c: true, d: 123, e: 123, f: new Uint8Array([1, 2, 3]) }] })
+ const result = fory.deserialize(input);
+ result.a.forEach((x) => (x.e = Number(x.e)));
+ expect(result).toEqual({
+ a: [{ b: "hel", c: true, d: 123, e: 123, f: new Uint8Array([1, 2, 3]) }],
+ });
});
- test('should write tag and read tag work', () => {
+ test("should write tag and read tag work", () => {
const typeInfo = Type.struct("example.foo", {
a: Type.struct("example.bar", {
- b: Type.string()
+ b: Type.string(),
}),
- a2: Type.struct("example.bar")
+ a2: Type.struct("example.bar"),
});
const fory = new Fory({ compatible: false, ref: true });
const serializer = fory.register(typeInfo).serializer;
const input = fory.serialize({ a: { b: "hel" }, a2: { b: "hel2" } }, serializer);
- const result = fory.deserialize(
- input
- );
- expect(result).toEqual({ a: { b: "hel" }, a2: { b: "hel2" } })
+ const result = fory.deserialize(input);
+ expect(result).toEqual({ a: { b: "hel" }, a2: { b: "hel2" } });
});
- test('should ciycle ref work', () => {
+ test("should ciycle ref work", () => {
const typeInfo = Type.struct("example.foo", {
a: Type.struct("example.bar", {
b: Type.string(),
}),
- a2: Type.struct("example.foo").setTrackingRef(true)
- })
+ a2: Type.struct("example.foo").setTrackingRef(true),
+ });
const fory = new Fory({
compatible: false,
ref: true,
hooks: {
afterCodeGenerated: (code) => {
- return beautify.js(code, { indent_size: 2, space_in_empty_paren: true, indent_empty_lines: true });
- }
- }
+ return beautify.js(code, {
+ indent_size: 2,
+ space_in_empty_paren: true,
+ indent_empty_lines: true,
+ });
+ },
+ },
});
const serialize = fory.register(typeInfo).serializer;
const param: any = {};
param.a = { b: "hel" };
param.a2 = param;
const input = fory.serialize(param, serialize);
- const result = fory.deserialize(
- input
- );
- expect(result.a).toEqual({ b: "hel" })
- expect(result.a2).toEqual(result)
+ const result = fory.deserialize(input);
+ expect(result.a).toEqual({ b: "hel" });
+ expect(result.a2).toEqual(result);
});
- test('should dot prop accessor work', () => {
+ test("should dot prop accessor work", () => {
const typeInfo = Type.struct("example.foo", {
"+a": Type.struct("example.bar", {
- "delete": Type.string(),
- c: Type.list(Type.struct("example.foo2", {
- d: Type.string(),
- }))
+ delete: Type.string(),
+ c: Type.list(
+ Type.struct("example.foo2", {
+ d: Type.string(),
+ }),
+ ),
}),
- })
+ });
const fory = new Fory({ compatible: false, ref: true });
const { serialize, deserialize } = fory.register(typeInfo);
- const input = serialize({ "+a": { "delete": "hel", c: [{ d: "hello" }] } });
- const result = deserialize(
- input
- );
- expect(result).toEqual({ "+a": { "delete": "hel", c: [{ d: "hello" }] } })
+ const input = serialize({ "+a": { delete: "hel", c: [{ d: "hello" }] } });
+ const result = deserialize(input);
+ expect(result).toEqual({ "+a": { delete: "hel", c: [{ d: "hello" }] } });
});
-
- test('should type function tools work', () => {
+ test("should type function tools work", () => {
const typeInfo = Type.struct("example.foo", {
- a: Type.struct("example\".bar", {
+ a: Type.struct('example".bar', {
b: Type.string(),
- c: Type.list(Type.struct("example\\\".foo2", {
- d: Type.string(),
- }))
+ c: Type.list(
+ Type.struct('example\\".foo2', {
+ d: Type.string(),
+ }),
+ ),
}),
- })
+ });
const fory = new Fory({ compatible: false, ref: true });
const { serialize, deserialize } = fory.register(typeInfo);
const input = serialize({ a: { b: "hel", c: [{ d: "hello" }] } });
- const result = deserialize(
- input
- );
- expect(result).toEqual({ a: { b: "hel", c: [{ d: "hello" }] } })
+ const result = deserialize(input);
+ expect(result).toEqual({ a: { b: "hel", c: [{ d: "hello" }] } });
});
test("should partial record work", () => {
const hps = undefined;
- const typeInfo = Type.struct('ws-channel-protocol', {
+ const typeInfo = Type.struct("ws-channel-protocol", {
kind: Type.string(),
path: Type.string().setNullable(true),
});
@@ -211,12 +208,12 @@ describe('object', () => {
kind: "123",
});
const obj = deserialize(bin);
- expect({ kind: "123", path: null }).toEqual(obj)
- })
+ expect({ kind: "123", path: null }).toEqual(obj);
+ });
- test('should handle emojis', () => {
+ test("should handle emojis", () => {
const typeInfo = Type.struct("example.emoji", {
- a: Type.string()
+ a: Type.string(),
});
const fory = new Fory({ compatible: false, ref: true });
@@ -226,19 +223,19 @@ describe('object', () => {
expect(result).toEqual({ a: "Hello, world! 🌍😊" });
});
- test('should support struct evolving override', () => {
+ test("should support struct evolving override", () => {
const fory = new Fory({ compatible: true });
const evolvingType = Type.struct(
{ typeId: 1001 },
{
f1: Type.string(),
- }
+ },
);
const fixedType = Type.struct(
{ typeId: 1002, evolving: false },
{
f1: Type.string(),
- }
+ },
);
const evolvingSerializer = fory.register(evolvingType);
diff --git a/javascript/test/platformBuffer.test.ts b/javascript/test/platformBuffer.test.ts
index 80b4a58e4..50deadbf1 100644
--- a/javascript/test/platformBuffer.test.ts
+++ b/javascript/test/platformBuffer.test.ts
@@ -17,74 +17,76 @@
* under the License.
*/
-import { fromUint8Array, alloc, BrowserBuffer, PlatformBuffer } from '../packages/core/lib/platformBuffer';
-import { describe, expect, test } from '@jest/globals';
-
-describe('platformBuffer', () => {
- test('should fromUint8Array work', () => {
- const bf = fromUint8Array(new Uint8Array([1, 2, 3]));
- expect(Buffer.isBuffer(bf)).toBe(true)
-
- const bf2 = fromUint8Array(Buffer.from([1,2,3]));
- expect(Buffer.isBuffer(bf2)).toBe(true)
- });
-
- test('should alloc work', () => {
- const bf = alloc(10);
- expect(bf.byteLength).toBe(10)
-
- const bf2 = BrowserBuffer.alloc(10);
- expect(bf2.byteLength).toBe(10)
- });
-
-
- test('should latin1Write work', () => {
- const bb = BrowserBuffer.alloc(100);
- bb.write("hello, world", 0, "latin1");
-
- const str = bb.toString("latin1", 0, 12);
- expect(str).toBe("hello, world");
- });
-
-
- test('should utf8Write work', () => {
- const rawStr = "我是Fory, 你好!😁א";
- const bb = BrowserBuffer.alloc(100);
- bb.write(rawStr, 0);
-
- const str = bb.toString("utf8", 0, 27);
- expect(str).toBe(rawStr);
- });
-
- test('should utf8 work', () => {
- const rawStr = "我是Fory, 你好!😁א";
- const bb = BrowserBuffer.alloc(100);
- bb.write(rawStr, 0, 'utf8');
-
- const str2 = bb.toString('utf8', 0, 27);
- expect(str2).toBe(rawStr);
- });
-
-
- test('should byteLength work', () => {
- expect(BrowserBuffer.byteLength("hello, world")).toBe(12);
- expect(BrowserBuffer.byteLength("我是Fory, 你好!😁א")).toBe(27);
- });
-
- test('should copy work', () => {
- const bb = BrowserBuffer.alloc(100);
- bb.write("hello", 0, 'latin1');
- const target = new Uint8Array(5);
- bb.copy(target, 0, 0, 5);
- expect([...target]).toEqual([ 104, 101, 108, 108, 111 ])
- });
-
- test('Buffer can be assigned to PlatformBuffer', () => {
- const cc = Buffer.alloc(20);
- cc.write("hello", 0, "latin1");
- const bb: PlatformBuffer = cc;
- expect(bb.toString('latin1', 0 , 5)).toBe("hello");
- bb.write("world", 5, "latin1");
- expect(bb.toString('latin1', 0, 10)).toBe("helloworld");
- })
+import {
+ fromUint8Array,
+ alloc,
+ BrowserBuffer,
+ PlatformBuffer,
+} from "../packages/core/lib/platformBuffer";
+import { describe, expect, test } from "@jest/globals";
+
+describe("platformBuffer", () => {
+ test("should fromUint8Array work", () => {
+ const bf = fromUint8Array(new Uint8Array([1, 2, 3]));
+ expect(Buffer.isBuffer(bf)).toBe(true);
+
+ const bf2 = fromUint8Array(Buffer.from([1, 2, 3]));
+ expect(Buffer.isBuffer(bf2)).toBe(true);
+ });
+
+ test("should alloc work", () => {
+ const bf = alloc(10);
+ expect(bf.byteLength).toBe(10);
+
+ const bf2 = BrowserBuffer.alloc(10);
+ expect(bf2.byteLength).toBe(10);
+ });
+
+ test("should latin1Write work", () => {
+ const bb = BrowserBuffer.alloc(100);
+ bb.write("hello, world", 0, "latin1");
+
+ const str = bb.toString("latin1", 0, 12);
+ expect(str).toBe("hello, world");
+ });
+
+ test("should utf8Write work", () => {
+ const rawStr = "我是Fory, 你好!😁א";
+ const bb = BrowserBuffer.alloc(100);
+ bb.write(rawStr, 0);
+
+ const str = bb.toString("utf8", 0, 27);
+ expect(str).toBe(rawStr);
+ });
+
+ test("should utf8 work", () => {
+ const rawStr = "我是Fory, 你好!😁א";
+ const bb = BrowserBuffer.alloc(100);
+ bb.write(rawStr, 0, "utf8");
+
+ const str2 = bb.toString("utf8", 0, 27);
+ expect(str2).toBe(rawStr);
+ });
+
+ test("should byteLength work", () => {
+ expect(BrowserBuffer.byteLength("hello, world")).toBe(12);
+ expect(BrowserBuffer.byteLength("我是Fory, 你好!😁א")).toBe(27);
+ });
+
+ test("should copy work", () => {
+ const bb = BrowserBuffer.alloc(100);
+ bb.write("hello", 0, "latin1");
+ const target = new Uint8Array(5);
+ bb.copy(target, 0, 0, 5);
... 1430 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org