├── .github └── workflows │ ├── js.yml │ └── rust.yml ├── .gitignore ├── .prettierrc.yaml ├── Cargo.lock ├── Cargo.toml ├── README.md ├── js ├── json-canon-fuzz │ ├── README.md │ ├── package.json │ └── src │ │ ├── bin.js │ │ ├── index.js │ │ ├── json.js │ │ └── numbers.js └── json-canon │ ├── LICENSE │ ├── README.md │ ├── bench │ ├── index.js │ └── test.json │ ├── examples │ └── basic.js │ ├── package.json │ ├── src │ └── index.js │ └── test │ ├── fixtures.js │ ├── fuzz.js │ └── units.js ├── package-lock.json ├── package.json ├── rust └── json-canon │ ├── Cargo.toml │ ├── LICENSE │ ├── README.md │ ├── benches │ ├── basic.json │ └── basic.rs │ ├── examples │ └── basic.rs │ ├── src │ ├── lib.rs │ ├── object.rs │ └── ser.rs │ └── tests │ ├── fixtures.rs │ ├── json.rs │ ├── numbers.rs │ └── units.rs └── test-data ├── README.md ├── fuzzies └── 1.json ├── generated └── .gitkeep ├── input ├── arrays.json ├── french.json ├── structures.json ├── unicode.json ├── values.json └── weird.json └── output ├── arrays.json ├── french.json ├── structures.json ├── unicode.json ├── values.json └── weird.json /.github/workflows/js.yml: -------------------------------------------------------------------------------- 1 | name: JavaScript 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | timeout-minutes: 10 13 | 14 | strategy: 15 | matrix: 16 | node-version: [16.x, 18.x] 17 | 18 | steps: 19 | - uses: actions/checkout@v3 20 | - uses: actions/setup-node@v3 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | - run: npm ci 24 | - run: npm test 25 | 26 | lint: 27 | runs-on: ubuntu-latest 28 | 29 | steps: 30 | - uses: actions/checkout@v3 31 | - uses: actions/setup-node@v3 32 | - run: npm ci 33 | - run: npm run lint 34 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | check: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: stable 22 | - uses: actions-rs/cargo@v1 23 | with: 24 | command: check 25 | 26 | test: 27 | runs-on: ubuntu-latest 28 | timeout-minutes: 10 29 | 30 | strategy: 31 | matrix: 32 | toolchain: 33 | - stable 34 | - 1.56.1 35 | 36 | steps: 37 | - uses: actions/checkout@v3 38 | - uses: actions-rs/toolchain@v1 39 | with: 40 | profile: minimal 41 | toolchain: ${{ matrix.toolchain }} 42 | - uses: actions/setup-node@v3 43 | - run: npm ci 44 | - uses: actions-rs/cargo@v1 45 | with: 46 | command: test 47 | 48 | lint: 49 | runs-on: ubuntu-latest 50 | 51 | steps: 52 | - uses: actions/checkout@v3 53 | - uses: actions-rs/toolchain@v1 54 | with: 55 | profile: minimal 56 | toolchain: stable 57 | components: rustfmt 58 | - uses: actions-rs/cargo@v1 59 | with: 60 | command: fmt 61 | args: --all -- --check 62 | 63 | clippy: 64 | runs-on: ubuntu-latest 65 | 66 | steps: 67 | - uses: actions/checkout@v3 68 | - uses: actions-rs/toolchain@v1 69 | with: 70 | profile: minimal 71 | toolchain: stable 72 | components: clippy 73 | - uses: actions-rs/cargo@v1 74 | with: 75 | command: clippy 76 | args: -- -D warnings 77 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log* 3 | /test-data/generated 4 | /target 5 | -------------------------------------------------------------------------------- /.prettierrc.yaml: -------------------------------------------------------------------------------- 1 | semi: false 2 | singleQuote: true 3 | trailingComma: all 4 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "atty" 7 | version = "0.2.14" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 10 | dependencies = [ 11 | "hermit-abi 0.1.19", 12 | "libc", 13 | "winapi", 14 | ] 15 | 16 | [[package]] 17 | name = "autocfg" 18 | version = "1.1.0" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 21 | 22 | [[package]] 23 | name = "bitflags" 24 | version = "1.3.2" 25 | source = "registry+https://github.com/rust-lang/crates.io-index" 26 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 27 | 28 | [[package]] 29 | name = "bumpalo" 30 | version = "3.12.2" 31 | source = "registry+https://github.com/rust-lang/crates.io-index" 32 | checksum = "3c6ed94e98ecff0c12dd1b04c15ec0d7d9458ca8fe806cea6f12954efe74c63b" 33 | 34 | [[package]] 35 | name = "cast" 36 | version = "0.3.0" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" 39 | 40 | [[package]] 41 | name = "cfg-if" 42 | version = "1.0.0" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 45 | 46 | [[package]] 47 | name = "clap" 48 | version = "2.34.0" 49 | source = "registry+https://github.com/rust-lang/crates.io-index" 50 | checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" 51 | dependencies = [ 52 | "bitflags", 53 | "textwrap", 54 | "unicode-width", 55 | ] 56 | 57 | [[package]] 58 | name = "criterion" 59 | version = "0.3.6" 60 | source = "registry+https://github.com/rust-lang/crates.io-index" 61 | checksum = "b01d6de93b2b6c65e17c634a26653a29d107b3c98c607c765bf38d041531cd8f" 62 | dependencies = [ 63 | "atty", 64 | "cast", 65 | "clap", 66 | "criterion-plot", 67 | "csv", 68 | "itertools", 69 | "lazy_static", 70 | "num-traits", 71 | "oorandom", 72 | "plotters", 73 | "rayon", 74 | "regex", 75 | "serde", 76 | "serde_cbor", 77 | "serde_derive", 78 | "serde_json", 79 | "tinytemplate", 80 | "walkdir", 81 | ] 82 | 83 | [[package]] 84 | name = "criterion-plot" 85 | version = "0.4.5" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "2673cc8207403546f45f5fd319a974b1e6983ad1a3ee7e6041650013be041876" 88 | dependencies = [ 89 | "cast", 90 | "itertools", 91 | ] 92 | 93 | [[package]] 94 | name = "crossbeam-channel" 95 | version = "0.5.8" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" 98 | dependencies = [ 99 | "cfg-if", 100 | "crossbeam-utils", 101 | ] 102 | 103 | [[package]] 104 | name = "crossbeam-deque" 105 | version = "0.8.3" 106 | source = "registry+https://github.com/rust-lang/crates.io-index" 107 | checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" 108 | dependencies = [ 109 | "cfg-if", 110 | "crossbeam-epoch", 111 | "crossbeam-utils", 112 | ] 113 | 114 | [[package]] 115 | name = "crossbeam-epoch" 116 | version = "0.9.14" 117 | source = "registry+https://github.com/rust-lang/crates.io-index" 118 | checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695" 119 | dependencies = [ 120 | "autocfg", 121 | "cfg-if", 122 | "crossbeam-utils", 123 | "memoffset", 124 | "scopeguard", 125 | ] 126 | 127 | [[package]] 128 | name = "crossbeam-utils" 129 | version = "0.8.15" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" 132 | dependencies = [ 133 | "cfg-if", 134 | ] 135 | 136 | [[package]] 137 | name = "csv" 138 | version = "1.2.1" 139 | source = "registry+https://github.com/rust-lang/crates.io-index" 140 | checksum = "0b015497079b9a9d69c02ad25de6c0a6edef051ea6360a327d0bd05802ef64ad" 141 | dependencies = [ 142 | "csv-core", 143 | "itoa", 144 | "ryu", 145 | "serde", 146 | ] 147 | 148 | [[package]] 149 | name = "csv-core" 150 | version = "0.1.10" 151 | source = "registry+https://github.com/rust-lang/crates.io-index" 152 | checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" 153 | dependencies = [ 154 | "memchr", 155 | ] 156 | 157 | [[package]] 158 | name = "either" 159 | version = "1.8.1" 160 | source = "registry+https://github.com/rust-lang/crates.io-index" 161 | checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" 162 | 163 | [[package]] 164 | name = "half" 165 | version = "1.8.2" 166 | source = "registry+https://github.com/rust-lang/crates.io-index" 167 | checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" 168 | 169 | [[package]] 170 | name = "hermit-abi" 171 | version = "0.1.19" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 174 | dependencies = [ 175 | "libc", 176 | ] 177 | 178 | [[package]] 179 | name = "hermit-abi" 180 | version = "0.2.6" 181 | source = "registry+https://github.com/rust-lang/crates.io-index" 182 | checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" 183 | dependencies = [ 184 | "libc", 185 | ] 186 | 187 | [[package]] 188 | name = "itertools" 189 | version = "0.10.5" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" 192 | dependencies = [ 193 | "either", 194 | ] 195 | 196 | [[package]] 197 | name = "itoa" 198 | version = "1.0.6" 199 | source = "registry+https://github.com/rust-lang/crates.io-index" 200 | checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" 201 | 202 | [[package]] 203 | name = "js-sys" 204 | version = "0.3.62" 205 | source = "registry+https://github.com/rust-lang/crates.io-index" 206 | checksum = "68c16e1bfd491478ab155fd8b4896b86f9ede344949b641e61501e07c2b8b4d5" 207 | dependencies = [ 208 | "wasm-bindgen", 209 | ] 210 | 211 | [[package]] 212 | name = "json-canon" 213 | version = "0.1.3" 214 | dependencies = [ 215 | "criterion", 216 | "ryu-js", 217 | "serde", 218 | "serde_derive", 219 | "serde_json", 220 | ] 221 | 222 | [[package]] 223 | name = "lazy_static" 224 | version = "1.4.0" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 227 | 228 | [[package]] 229 | name = "libc" 230 | version = "0.2.144" 231 | source = "registry+https://github.com/rust-lang/crates.io-index" 232 | checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1" 233 | 234 | [[package]] 235 | name = "log" 236 | version = "0.4.17" 237 | source = "registry+https://github.com/rust-lang/crates.io-index" 238 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 239 | dependencies = [ 240 | "cfg-if", 241 | ] 242 | 243 | [[package]] 244 | name = "memchr" 245 | version = "2.5.0" 246 | source = "registry+https://github.com/rust-lang/crates.io-index" 247 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 248 | 249 | [[package]] 250 | name = "memoffset" 251 | version = "0.8.0" 252 | source = "registry+https://github.com/rust-lang/crates.io-index" 253 | checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" 254 | dependencies = [ 255 | "autocfg", 256 | ] 257 | 258 | [[package]] 259 | name = "num-traits" 260 | version = "0.2.15" 261 | source = "registry+https://github.com/rust-lang/crates.io-index" 262 | checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" 263 | dependencies = [ 264 | "autocfg", 265 | ] 266 | 267 | [[package]] 268 | name = "num_cpus" 269 | version = "1.15.0" 270 | source = "registry+https://github.com/rust-lang/crates.io-index" 271 | checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" 272 | dependencies = [ 273 | "hermit-abi 0.2.6", 274 | "libc", 275 | ] 276 | 277 | [[package]] 278 | name = "once_cell" 279 | version = "1.17.1" 280 | source = "registry+https://github.com/rust-lang/crates.io-index" 281 | checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" 282 | 283 | [[package]] 284 | name = "oorandom" 285 | version = "11.1.3" 286 | source = "registry+https://github.com/rust-lang/crates.io-index" 287 | checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" 288 | 289 | [[package]] 290 | name = "plotters" 291 | version = "0.3.4" 292 | source = "registry+https://github.com/rust-lang/crates.io-index" 293 | checksum = "2538b639e642295546c50fcd545198c9d64ee2a38620a628724a3b266d5fbf97" 294 | dependencies = [ 295 | "num-traits", 296 | "plotters-backend", 297 | "plotters-svg", 298 | "wasm-bindgen", 299 | "web-sys", 300 | ] 301 | 302 | [[package]] 303 | name = "plotters-backend" 304 | version = "0.3.4" 305 | source = "registry+https://github.com/rust-lang/crates.io-index" 306 | checksum = "193228616381fecdc1224c62e96946dfbc73ff4384fba576e052ff8c1bea8142" 307 | 308 | [[package]] 309 | name = "plotters-svg" 310 | version = "0.3.3" 311 | source = "registry+https://github.com/rust-lang/crates.io-index" 312 | checksum = "f9a81d2759aae1dae668f783c308bc5c8ebd191ff4184aaa1b37f65a6ae5a56f" 313 | dependencies = [ 314 | "plotters-backend", 315 | ] 316 | 317 | [[package]] 318 | name = "proc-macro2" 319 | version = "1.0.56" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" 322 | dependencies = [ 323 | "unicode-ident", 324 | ] 325 | 326 | [[package]] 327 | name = "quote" 328 | version = "1.0.27" 329 | source = "registry+https://github.com/rust-lang/crates.io-index" 330 | checksum = "8f4f29d145265ec1c483c7c654450edde0bfe043d3938d6972630663356d9500" 331 | dependencies = [ 332 | "proc-macro2", 333 | ] 334 | 335 | [[package]] 336 | name = "rayon" 337 | version = "1.7.0" 338 | source = "registry+https://github.com/rust-lang/crates.io-index" 339 | checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" 340 | dependencies = [ 341 | "either", 342 | "rayon-core", 343 | ] 344 | 345 | [[package]] 346 | name = "rayon-core" 347 | version = "1.11.0" 348 | source = "registry+https://github.com/rust-lang/crates.io-index" 349 | checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" 350 | dependencies = [ 351 | "crossbeam-channel", 352 | "crossbeam-deque", 353 | "crossbeam-utils", 354 | "num_cpus", 355 | ] 356 | 357 | [[package]] 358 | name = "regex" 359 | version = "1.8.1" 360 | source = "registry+https://github.com/rust-lang/crates.io-index" 361 | checksum = "af83e617f331cc6ae2da5443c602dfa5af81e517212d9d611a5b3ba1777b5370" 362 | dependencies = [ 363 | "regex-syntax", 364 | ] 365 | 366 | [[package]] 367 | name = "regex-syntax" 368 | version = "0.7.1" 369 | source = "registry+https://github.com/rust-lang/crates.io-index" 370 | checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c" 371 | 372 | [[package]] 373 | name = "ryu" 374 | version = "1.0.13" 375 | source = "registry+https://github.com/rust-lang/crates.io-index" 376 | checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" 377 | 378 | [[package]] 379 | name = "ryu-js" 380 | version = "0.2.2" 381 | source = "registry+https://github.com/rust-lang/crates.io-index" 382 | checksum = "6518fc26bced4d53678a22d6e423e9d8716377def84545fe328236e3af070e7f" 383 | 384 | [[package]] 385 | name = "same-file" 386 | version = "1.0.6" 387 | source = "registry+https://github.com/rust-lang/crates.io-index" 388 | checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 389 | dependencies = [ 390 | "winapi-util", 391 | ] 392 | 393 | [[package]] 394 | name = "scopeguard" 395 | version = "1.1.0" 396 | source = "registry+https://github.com/rust-lang/crates.io-index" 397 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 398 | 399 | [[package]] 400 | name = "serde" 401 | version = "1.0.162" 402 | source = "registry+https://github.com/rust-lang/crates.io-index" 403 | checksum = "71b2f6e1ab5c2b98c05f0f35b236b22e8df7ead6ffbf51d7808da7f8817e7ab6" 404 | 405 | [[package]] 406 | name = "serde_cbor" 407 | version = "0.11.2" 408 | source = "registry+https://github.com/rust-lang/crates.io-index" 409 | checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" 410 | dependencies = [ 411 | "half", 412 | "serde", 413 | ] 414 | 415 | [[package]] 416 | name = "serde_derive" 417 | version = "1.0.163" 418 | source = "registry+https://github.com/rust-lang/crates.io-index" 419 | checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e" 420 | dependencies = [ 421 | "proc-macro2", 422 | "quote", 423 | "syn", 424 | ] 425 | 426 | [[package]] 427 | name = "serde_json" 428 | version = "1.0.96" 429 | source = "registry+https://github.com/rust-lang/crates.io-index" 430 | checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" 431 | dependencies = [ 432 | "itoa", 433 | "ryu", 434 | "serde", 435 | ] 436 | 437 | [[package]] 438 | name = "syn" 439 | version = "2.0.15" 440 | source = "registry+https://github.com/rust-lang/crates.io-index" 441 | checksum = "a34fcf3e8b60f57e6a14301a2e916d323af98b0ea63c599441eec8558660c822" 442 | dependencies = [ 443 | "proc-macro2", 444 | "quote", 445 | "unicode-ident", 446 | ] 447 | 448 | [[package]] 449 | name = "textwrap" 450 | version = "0.11.0" 451 | source = "registry+https://github.com/rust-lang/crates.io-index" 452 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 453 | dependencies = [ 454 | "unicode-width", 455 | ] 456 | 457 | [[package]] 458 | name = "tinytemplate" 459 | version = "1.2.1" 460 | source = "registry+https://github.com/rust-lang/crates.io-index" 461 | checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" 462 | dependencies = [ 463 | "serde", 464 | "serde_json", 465 | ] 466 | 467 | [[package]] 468 | name = "unicode-ident" 469 | version = "1.0.8" 470 | source = "registry+https://github.com/rust-lang/crates.io-index" 471 | checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" 472 | 473 | [[package]] 474 | name = "unicode-width" 475 | version = "0.1.10" 476 | source = "registry+https://github.com/rust-lang/crates.io-index" 477 | checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" 478 | 479 | [[package]] 480 | name = "walkdir" 481 | version = "2.3.3" 482 | source = "registry+https://github.com/rust-lang/crates.io-index" 483 | checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698" 484 | dependencies = [ 485 | "same-file", 486 | "winapi-util", 487 | ] 488 | 489 | [[package]] 490 | name = "wasm-bindgen" 491 | version = "0.2.85" 492 | source = "registry+https://github.com/rust-lang/crates.io-index" 493 | checksum = "5b6cb788c4e39112fbe1822277ef6fb3c55cd86b95cb3d3c4c1c9597e4ac74b4" 494 | dependencies = [ 495 | "cfg-if", 496 | "wasm-bindgen-macro", 497 | ] 498 | 499 | [[package]] 500 | name = "wasm-bindgen-backend" 501 | version = "0.2.85" 502 | source = "registry+https://github.com/rust-lang/crates.io-index" 503 | checksum = "35e522ed4105a9d626d885b35d62501b30d9666283a5c8be12c14a8bdafe7822" 504 | dependencies = [ 505 | "bumpalo", 506 | "log", 507 | "once_cell", 508 | "proc-macro2", 509 | "quote", 510 | "syn", 511 | "wasm-bindgen-shared", 512 | ] 513 | 514 | [[package]] 515 | name = "wasm-bindgen-macro" 516 | version = "0.2.85" 517 | source = "registry+https://github.com/rust-lang/crates.io-index" 518 | checksum = "358a79a0cb89d21db8120cbfb91392335913e4890665b1a7981d9e956903b434" 519 | dependencies = [ 520 | "quote", 521 | "wasm-bindgen-macro-support", 522 | ] 523 | 524 | [[package]] 525 | name = "wasm-bindgen-macro-support" 526 | version = "0.2.85" 527 | source = "registry+https://github.com/rust-lang/crates.io-index" 528 | checksum = "4783ce29f09b9d93134d41297aded3a712b7b979e9c6f28c32cb88c973a94869" 529 | dependencies = [ 530 | "proc-macro2", 531 | "quote", 532 | "syn", 533 | "wasm-bindgen-backend", 534 | "wasm-bindgen-shared", 535 | ] 536 | 537 | [[package]] 538 | name = "wasm-bindgen-shared" 539 | version = "0.2.85" 540 | source = "registry+https://github.com/rust-lang/crates.io-index" 541 | checksum = "a901d592cafaa4d711bc324edfaff879ac700b19c3dfd60058d2b445be2691eb" 542 | 543 | [[package]] 544 | name = "web-sys" 545 | version = "0.3.62" 546 | source = "registry+https://github.com/rust-lang/crates.io-index" 547 | checksum = "16b5f940c7edfdc6d12126d98c9ef4d1b3d470011c47c76a6581df47ad9ba721" 548 | dependencies = [ 549 | "js-sys", 550 | "wasm-bindgen", 551 | ] 552 | 553 | [[package]] 554 | name = "winapi" 555 | version = "0.3.9" 556 | source = "registry+https://github.com/rust-lang/crates.io-index" 557 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 558 | dependencies = [ 559 | "winapi-i686-pc-windows-gnu", 560 | "winapi-x86_64-pc-windows-gnu", 561 | ] 562 | 563 | [[package]] 564 | name = "winapi-i686-pc-windows-gnu" 565 | version = "0.4.0" 566 | source = "registry+https://github.com/rust-lang/crates.io-index" 567 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 568 | 569 | [[package]] 570 | name = "winapi-util" 571 | version = "0.1.5" 572 | source = "registry+https://github.com/rust-lang/crates.io-index" 573 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 574 | dependencies = [ 575 | "winapi", 576 | ] 577 | 578 | [[package]] 579 | name = "winapi-x86_64-pc-windows-gnu" 580 | version = "0.4.0" 581 | source = "registry+https://github.com/rust-lang/crates.io-index" 582 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 583 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "rust/json-canon" 4 | ] 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `json-canon` 2 | 3 | Serialize JSON into a canonical format. 4 | 5 | Safe for generating a consistent cryptographic hash or signature across platforms. 6 | 7 | Follows [RFC8785: JSON Canonicalization Scheme (JCS)](https://tools.ietf.org/html/rfc8785) 8 | 9 | ![JSON cannon](https://i.imgur.com/OdH7hw1.png) 10 | 11 | ## Features 12 | 13 | The JSON Canonicalization Scheme concept in a nutshell: 14 | 15 | - Serialization of primitive JSON data types using methods compatible with ECMAScript's `JSON.stringify()` 16 | - Lexicographic sorting of JSON `Object` properties in a *recursive* process 17 | - JSON `Array` data is also subject to canonicalization, *but element order remains untouched* 18 | 19 | ## Serializers 20 | 21 | ### JavaScript: [`json-canon`](./js/json-canon) 22 | 23 | [![npm version](https://img.shields.io/npm/v/json-canon.svg?style=flat-square)](https://www.npmjs.com/package/json-canon) [![download](https://img.shields.io/npm/dt/json-canon?style=flat-square)](https://www.npmjs.com/package/json-canon) [![ci status](https://img.shields.io/github/actions/workflow/status/ahdinosaur/json-canon/js.yml?branch=main&style=flat-square)](https://github.com/ahdinosaur/json-canon/actions/workflows/js.yml) 24 | 25 | ```js 26 | const serialize = require('json-canon') 27 | 28 | const json = { 29 | from_account: "543 232 625-3", 30 | to_account: "321 567 636-4", 31 | amount: 500, 32 | currency: "USD" 33 | } 34 | 35 | console.log(serialize(json)) 36 | // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 37 | ``` 38 | 39 | ### Rust: [`json-canon`](./rust/json-canon) 40 | 41 | [![crates.io version](https://img.shields.io/crates/v/json-canon.svg?style=flat-square)](https://crates.io/crates/json-canon) [![download](https://img.shields.io/crates/d/json-canon.svg?style=flat-square)](https://crates.io/crates/json-canon) [![docs.rs docs](https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square)](https://docs.rs/json-canon) [![ci status](https://img.shields.io/github/actions/workflow/status/ahdinosaur/json-canon/rust.yml?branch=main&style=flat-square)](https://github.com/ahdinosaur/json-canon/actions/workflows/rust.yml) 42 | 43 | ```rust 44 | use json_canon::to_string; 45 | use serde_json::json; 46 | 47 | let data = json!({ 48 | "from_account": "543 232 625-3", 49 | "to_account": "321 567 636-4", 50 | "amount": 500, 51 | "currency": "USD" 52 | }); 53 | 54 | println!("{}", to_string(&data)?); 55 | // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 56 | ``` 57 | 58 | ## Fuzzers 59 | 60 | - JavaScript: [`json-canon-fuzz`](./js/json-canon-fuzz) 61 | 62 | ## References 63 | 64 | - [`cyberphone/ietf-json-canon`](https://github.com/cyberphone/ietf-json-canon) 65 | - [`cyberphone/json-canonicalization`](https://github.com/cyberphone/json-canonicalization) 66 | -------------------------------------------------------------------------------- /js/json-canon-fuzz/README.md: -------------------------------------------------------------------------------- 1 | # `json-canon-fuzz` 2 | 3 | [Fuzzer](https://en.wikipedia.org/wiki/Fuzzing) to test whether your JSON serialization is [canonical](https://datatracker.ietf.org/doc/rfc8785/). 4 | 5 | ## Install 6 | 7 | ```shell 8 | npm install -g json-canon-fuzz 9 | ``` 10 | 11 | ## Usage 12 | 13 | ```txt 14 | Usage 15 | $ json-canon-fuzz {type} {count} {path} 16 | 17 | Arguments 18 | - type: either `json` or `numbers` 19 | - count: how many lines to generate (default: Infinity) 20 | - path: where to output the generated lines (default: stdout) 21 | 22 | Examples 23 | $ json-canon-fuzz json 100000 24 | ``` 25 | 26 | ### Numbers 27 | 28 | The test output consists of lines 29 | 30 | ```txt 31 | hex-ieee,expected\n 32 | ``` 33 | 34 | where `hex-ieee` holds 1-16 ASCII hexadecimal characters representing an IEEE-754 double precision value while `expected` holds the expected serialized value. 35 | 36 | Each line is terminated by a single new-line character. 37 | 38 | Sample lines: 39 | 40 | ```txt 41 | 4340000000000001,9007199254740994 42 | 4340000000000002,9007199254740996 43 | 444b1ae4d6e2ef50,1e+21 44 | 3eb0c6f7a0b5ed8d,0.000001 45 | 3eb0c6f7a0b5ed8c,9.999999999999997e-7 46 | 8000000000000000,0 47 | 0,0 48 | ``` 49 | 50 | The generation is deterministic. After generating a file, the program will output the hash of the file. 51 | 52 | The following table records the expected hashes: 53 | 54 | | SHA-256 checksum | Number of lines | Size in bytes | 55 | | ---------------------------------------------------------------- | --------------- | ------------- | 56 | | be18b62b6f69cdab33a7e0dae0d9cfa869fda80ddc712221570f9f40a5878687 | 1000 | 37967 | 57 | | b9f7a8e75ef22a835685a52ccba7f7d6bdc99e34b010992cbc5864cd12be6892 | 10000 | 399022 | 58 | | 22776e6d4b49fa294a0d0f349268e5c28808fe7e0cb2bcbe28f63894e494d4c7 | 100000 | 4031728 | 59 | | 49415fee2c56c77864931bd3624faad425c3c577d6d74e89a83bc725506dad16 | 1000000 | 40357417 | 60 | | b9f8a44a91d46813b21b9602e72f112613c91408db0b8341fb94603d9db135e0 | 10000000 | 403630048 | 61 | | 0f7dda6b0837dde083c5d6b896f7d62340c8a2415b0c7121d83145e08a755272 | 100000000 | 4036326174 | 62 | 63 | ### JSON 64 | 65 | The test output consists of lines 66 | 67 | ```txt 68 | json\n 69 | ``` 70 | 71 | where `json` is a valid JSON object serialized according to [RFC8785: JSON Canonicalization Scheme (JCS)](https://tools.ietf.org/html/rfc8785). 72 | 73 | Each line is terminated by a single new-line character. 74 | 75 | Sample lines: 76 | 77 | ```txt 78 | false 79 | {"J���\toR�B\u001d":false,"]E�\u001e\u001d\u0019":4206124647,"�":"�Ĉ/�\u000e\b������5ɵ3\u0014","�\u0001Ƨ�\u0002ŵ":4.633184220509346,"�h\u0002\u000b�u��\\�":"�7� ���xB�K���!\u0019�ujҡ\u0019�Nx�D<��m\u0010*�\u0016p�\u001b�^ aLNt����P�","��X|Av[^E":-1306679260} 80 | 0.7290520820698927 81 | null 82 | "����Z\u0000��/�Bc_+�m�\u0002�\u0006�u�������RṚ�H\u000f�K\u0019��8\"�^ռI�\u0011ו\u001c�:D��n\u0005�s�m\u0013H��\t\b� H̑�\u001a}����\u0005 y&BO" 83 | {} 84 | ``` 85 | 86 | The generation is not deterministic. 87 | 88 | ## References 89 | 90 | - [`json-canonicalization/test-data`](https://github.com/cyberphone/json-canonicalization/tree/master/testdata) 91 | -------------------------------------------------------------------------------- /js/json-canon-fuzz/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json-canon-fuzz", 3 | "version": "0.1.0", 4 | "description": "Fuzzer to test whether your JSON serialization is canonical.", 5 | "main": "src/index.js", 6 | "bin": "src/bin.js", 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/ahdinosaur/json-canon.git" 10 | }, 11 | "keywords": [ 12 | "json", 13 | "jcs", 14 | "rfc8785", 15 | "canon", 16 | "canonical", 17 | "canonicalize", 18 | "crypto", 19 | "fuzz", 20 | "fuzzer", 21 | "fuzzing", 22 | "random", 23 | "generator" 24 | ], 25 | "author": "Michael Williams ", 26 | "contributors": [ 27 | "Anders Rundgren " 28 | ], 29 | "license": "Apache-2.0", 30 | "bugs": { 31 | "url": "https://github.com/ahdinosaur/json-canon/issues" 32 | }, 33 | "homepage": "https://github.com/ahdinosaur/json-canon#readme", 34 | "dependencies": { 35 | "json-canon": "^1.0.0", 36 | "readable-stream": "^4.4.0", 37 | "slump": "^3.0.2" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /js/json-canon-fuzz/src/bin.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { createWriteStream } = require('fs') 4 | const { join } = require('path') 5 | const { pipeline } = require('readable-stream') 6 | 7 | const fuzz = require('./') 8 | 9 | const args = process.argv.slice(2) 10 | 11 | const type = args[0] 12 | const numLines = args[1] ? parseInt(args[1]) : Infinity 13 | const outputFilePath = args[2] 14 | 15 | if (fuzz[type] === undefined || Number.isNaN(numLines)) { 16 | usage() 17 | 18 | process.exit(1) 19 | } 20 | 21 | const getFuzzStream = fuzz[type] 22 | 23 | const fuzzStream = getFuzzStream({ numLines, outputFilePath }) 24 | const outputStream = getOutputStream(outputFilePath) 25 | 26 | pipeline(fuzzStream, outputStream, function onDone(err) { 27 | if (err) throw err 28 | }) 29 | 30 | function usage() { 31 | console.log('Usage') 32 | console.log(' $ json-canon-fuzz {type} {count} {path}') 33 | console.log('') 34 | console.log('Arguments') 35 | console.log(' - type: either `json` or `numbers`') 36 | console.log(' - count: how many lines to generate (default: Infinity)') 37 | console.log(' - path: where to output the generated lines (default: stdout)') 38 | console.log('') 39 | console.log('Examples') 40 | console.log(' $ json-canon-fuzz json 100000') 41 | } 42 | 43 | function getOutputStream(outputFilePath) { 44 | if (outputFilePath) { 45 | const outputFileFullPath = join(process.cwd(), outputFilePath) 46 | return createWriteStream(outputFileFullPath, { encoding: 'utf8' }) 47 | } 48 | return process.stdout 49 | } 50 | -------------------------------------------------------------------------------- /js/json-canon-fuzz/src/index.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | json: require('./json'), 3 | numbers: require('./numbers'), 4 | } 5 | -------------------------------------------------------------------------------- /js/json-canon-fuzz/src/json.js: -------------------------------------------------------------------------------- 1 | const random = require('slump') 2 | const serialize = require('json-canon') 3 | const { Readable } = require('readable-stream') 4 | 5 | module.exports = generateJson 6 | 7 | /** 8 | * @param {object} options 9 | * @param {number} options.numLines 10 | * @param {string | undefined} options.outputFilePath 11 | * @returns {Readable} 12 | */ 13 | function generateJson(options) { 14 | const { numLines } = options 15 | 16 | let i = 0 17 | 18 | return new Readable({ 19 | read() { 20 | if (i >= numLines) { 21 | this.push(null) 22 | return 23 | } 24 | this.push(nextLine(i++)) 25 | }, 26 | }) 27 | 28 | function nextLine() { 29 | const obj = random.json() 30 | 31 | let json 32 | try { 33 | json = serialize(obj) 34 | } catch (err) { 35 | if ( 36 | err.message === 37 | 'Strings must be valid Unicode and not contain any surrogate pairs' 38 | ) { 39 | return nextLine() 40 | } 41 | throw err 42 | } 43 | 44 | return json + '\n' 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /js/json-canon-fuzz/src/numbers.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2006-2021 WebPKI.org (http://webpki.org). 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // https://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | // 17 | // This file originally copied from https://github.com/cyberphone/json-canonicalization/blob/57a0ce2/testdata/numgen.js 18 | 19 | const crypto = require('crypto') 20 | const { Readable } = require('readable-stream') 21 | 22 | module.exports = generateNumbers 23 | 24 | /** 25 | * @param {object} options 26 | * @param {number} options.numLines 27 | * @param {string | undefined} options.outputFilePath 28 | * @returns {Readable} 29 | */ 30 | function generateNumbers(options) { 31 | const { numLines, outputFilePath } = options 32 | 33 | const generateNumber = createNumberGenerator() 34 | 35 | let u64 = new BigUint64Array(1) 36 | let f64 = new Float64Array(u64.buffer) 37 | let hash = crypto.createHash('sha256') 38 | 39 | let i = 0 40 | 41 | return new Readable({ 42 | read() { 43 | if (i >= numLines) { 44 | this.push(null) 45 | if (outputFilePath) { 46 | console.log(hash.digest('hex')) 47 | } 48 | return 49 | } 50 | this.push(nextLine(i++)) 51 | }, 52 | }) 53 | 54 | function nextLine() { 55 | f64[0] = generateNumber() 56 | line = u64[0].toString(16) + ',' + f64[0].toString() + '\n' 57 | hash.update(line) 58 | 59 | return line 60 | } 61 | } 62 | 63 | function createNumberGenerator() { 64 | // prettier-ignore 65 | const staticU64s = new BigUint64Array([ 66 | 0x0000000000000000n, 0x8000000000000000n, 0x0000000000000001n, 0x8000000000000001n, 67 | 0xc46696695dbd1cc3n, 0xc43211ede4974a35n, 0xc3fce97ca0f21056n, 0xc3c7213080c1a6acn, 68 | 0xc39280f39a348556n, 0xc35d9b1f5d20d557n, 0xc327af4c4a80aaacn, 0xc2f2f2a36ecd5556n, 69 | 0xc2be51057e155558n, 0xc28840d131aaaaacn, 0xc253670dc1555557n, 0xc21f0b4935555557n, 70 | 0xc1e8d5d42aaaaaacn, 0xc1b3de4355555556n, 0xc17fca0555555556n, 0xc1496e6aaaaaaaabn, 71 | 0xc114585555555555n, 0xc0e046aaaaaaaaabn, 0xc0aa0aaaaaaaaaaan, 0xc074d55555555555n, 72 | 0xc040aaaaaaaaaaabn, 0xc00aaaaaaaaaaaabn, 0xbfd5555555555555n, 0xbfa1111111111111n, 73 | 0xbf6b4e81b4e81b4fn, 0xbf35d867c3ece2a5n, 0xbf0179ec9cbd821en, 0xbecbf647612f3696n, 74 | 0xbe965e9f80f29212n, 0xbe61e54c672874dbn, 0xbe2ca213d840baf8n, 0xbdf6e80fe033c8c6n, 75 | 0xbdc2533fe68fd3d2n, 0xbd8d51ffd74c861cn, 0xbd5774ccac3d3817n, 0xbd22c3d6f030f9acn, 76 | 0xbcee0624b3818f79n, 0xbcb804ea293472c7n, 0xbc833721ba905bd3n, 0xbc4ebe9c5db3c61en, 77 | 0xbc18987d17c304e5n, 0xbbe3ad30dfcf371dn, 0xbbaf7b816618582fn, 0xbb792f9ab81379bfn, 78 | 0xbb442615600f9499n, 0xbb101e77800c76e1n, 0xbad9ca58cce0be35n, 0xbaa4a1e0a3e6fe90n, 79 | 0xba708180831f320dn, 0xba3a68cd9e985016n, 0x446696695dbd1cc3n, 0x443211ede4974a35n, 80 | 0x43fce97ca0f21056n, 0x43c7213080c1a6acn, 0x439280f39a348556n, 0x435d9b1f5d20d557n, 81 | 0x4327af4c4a80aaacn, 0x42f2f2a36ecd5556n, 0x42be51057e155558n, 0x428840d131aaaaacn, 82 | 0x4253670dc1555557n, 0x421f0b4935555557n, 0x41e8d5d42aaaaaacn, 0x41b3de4355555556n, 83 | 0x417fca0555555556n, 0x41496e6aaaaaaaabn, 0x4114585555555555n, 0x40e046aaaaaaaaabn, 84 | 0x40aa0aaaaaaaaaaan, 0x4074d55555555555n, 0x4040aaaaaaaaaaabn, 0x400aaaaaaaaaaaabn, 85 | 0x3fd5555555555555n, 0x3fa1111111111111n, 0x3f6b4e81b4e81b4fn, 0x3f35d867c3ece2a5n, 86 | 0x3f0179ec9cbd821en, 0x3ecbf647612f3696n, 0x3e965e9f80f29212n, 0x3e61e54c672874dbn, 87 | 0x3e2ca213d840baf8n, 0x3df6e80fe033c8c6n, 0x3dc2533fe68fd3d2n, 0x3d8d51ffd74c861cn, 88 | 0x3d5774ccac3d3817n, 0x3d22c3d6f030f9acn, 0x3cee0624b3818f79n, 0x3cb804ea293472c7n, 89 | 0x3c833721ba905bd3n, 0x3c4ebe9c5db3c61en, 0x3c18987d17c304e5n, 0x3be3ad30dfcf371dn, 90 | 0x3baf7b816618582fn, 0x3b792f9ab81379bfn, 0x3b442615600f9499n, 0x3b101e77800c76e1n, 91 | 0x3ad9ca58cce0be35n, 0x3aa4a1e0a3e6fe90n, 0x3a708180831f320dn, 0x3a3a68cd9e985016n, 92 | 0x4024000000000000n, 0x4014000000000000n, 0x3fe0000000000000n, 0x3fa999999999999an, 93 | 0x3f747ae147ae147bn, 0x3f40624dd2f1a9fcn, 0x3f0a36e2eb1c432dn, 0x3ed4f8b588e368f1n, 94 | 0x3ea0c6f7a0b5ed8dn, 0x3e6ad7f29abcaf48n, 0x3e35798ee2308c3an, 0x3ed539223589fa95n, 95 | 0x3ed4ff26cd5a7781n, 0x3ed4f95a762283ffn, 0x3ed4f8c60703520cn, 0x3ed4f8b72f19cd0dn, 96 | 0x3ed4f8b5b31c0c8dn, 0x3ed4f8b58d1c461an, 0x3ed4f8b5894f7f0en, 0x3ed4f8b588ee37f3n, 97 | 0x3ed4f8b588e47da4n, 0x3ed4f8b588e3849cn, 0x3ed4f8b588e36bb5n, 0x3ed4f8b588e36937n, 98 | 0x3ed4f8b588e368f8n, 0x3ed4f8b588e368f1n, 0x3ff0000000000000n, 0xbff0000000000000n, 99 | 0xbfeffffffffffffan, 0xbfeffffffffffffbn, 0x3feffffffffffffan, 0x3feffffffffffffbn, 100 | 0x3feffffffffffffcn, 0x3feffffffffffffen, 0xbfefffffffffffffn, 0xbfefffffffffffffn, 101 | 0x3fefffffffffffffn, 0x3fefffffffffffffn, 0x3fd3333333333332n, 0x3fd3333333333333n, 102 | 0x3fd3333333333334n, 0x0010000000000000n, 0x000ffffffffffffdn, 0x000fffffffffffffn, 103 | 0x7fefffffffffffffn, 0xffefffffffffffffn, 0x4340000000000000n, 0xc340000000000000n, 104 | 0x4430000000000000n, 0x44b52d02c7e14af5n, 0x44b52d02c7e14af6n, 0x44b52d02c7e14af7n, 105 | 0x444b1ae4d6e2ef4en, 0x444b1ae4d6e2ef4fn, 0x444b1ae4d6e2ef50n, 0x3eb0c6f7a0b5ed8cn, 106 | 0x3eb0c6f7a0b5ed8dn, 0x41b3de4355555553n, 0x41b3de4355555554n, 0x41b3de4355555555n, 107 | 0x41b3de4355555556n, 0x41b3de4355555557n, 0xbecbf647612f3696n, 0x43143ff3c1cb0959n, 108 | ]) 109 | const staticF64s = new Float64Array(staticU64s.buffer) 110 | const serialU64s = new BigUint64Array(2000) 111 | for (i = 0; i < 2000; i++) { 112 | serialU64s[i] = 0x0010000000000000n + BigInt(i) 113 | } 114 | const serialF64s = new Float64Array(serialU64s.buffer) 115 | 116 | let state = { 117 | idx: 0, 118 | data: new Float64Array(), 119 | block: new ArrayBuffer(32), 120 | } 121 | 122 | return function nextNumber() { 123 | let f = 0.0 124 | if (state.idx < staticF64s.length) { 125 | f = staticF64s[state.idx] 126 | } else if (state.idx < staticF64s.length + serialF64s.length) { 127 | f = serialF64s[state.idx - staticF64s.length] 128 | } else { 129 | while (f == 0.0 || !isFinite(f)) { 130 | if (state.data.length == 0) { 131 | state.block = crypto 132 | .createHash('sha256') 133 | .update(new Buffer.from(state.block)) 134 | .digest().buffer 135 | state.data = new Float64Array(state.block) 136 | } 137 | f = state.data[0] 138 | state.data = state.data.slice(1) 139 | } 140 | } 141 | state.idx++ 142 | return f 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /js/json-canon/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /js/json-canon/README.md: -------------------------------------------------------------------------------- 1 | # `json-canon` 2 | 3 | ## Install 4 | 5 | ```shell 6 | npm install json-canon 7 | ``` 8 | 9 | ## Example 10 | 11 | ```js 12 | const serialize = require('json-canon') 13 | 14 | const json = { 15 | from_account: "543 232 625-3", 16 | to_account: "321 567 636-4", 17 | amount: 500, 18 | currency: "USD" 19 | } 20 | 21 | console.log(serialize(json)) 22 | // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 23 | ``` 24 | 25 | See [`./examples/basic.js`](./examples/basic.js) 26 | 27 | ## Usage 28 | 29 | ### `serialize = require('json-canon')` 30 | 31 | ```ts 32 | function serialize(input: unknown): string; 33 | ``` 34 | 35 | ## Bench 36 | 37 | ```txt 38 | json-canon x 44,441 ops/sec ±0.42% (91 runs sampled) 39 | JSON.stringify x 101,970 ops/sec ±0.37% (90 runs sampled) 40 | fast-json-stable-stringify x 30,066 ops/sec ±0.35% (95 runs sampled) 41 | json-stable-stringify x 23,099 ops/sec ±0.50% (93 runs sampled) 42 | fast-stable-stringify x 35,560 ops/sec ±0.23% (91 runs sampled) 43 | json-stringify-deterministic x 18,521 ops/sec ±0.37% (95 runs sampled) 44 | faster-stable-stringify x 28,588 ops/sec ±0.20% (96 runs sampled) 45 | fast-safe-stringify x 83,523 ops/sec ±0.23% (98 runs sampled) 46 | safe-stable-stringify x 50,807 ops/sec ±0.26% (94 runs sampled) 47 | canonicalize x 28,365 ops/sec ±0.79% (93 runs sampled) 48 | json-canonicalize x 30,372 ops/sec ±0.56% (89 runs sampled) 49 | The fastest is JSON.stringify 50 | ``` 51 | 52 | ## License 53 | 54 | ```txt 55 | Copyright 2023 Michael Williams 56 | 57 | Licensed under the Apache License, Version 2.0 (the "License"); 58 | you may not use this file except in compliance with the License. 59 | You may obtain a copy of the License at 60 | 61 | http://www.apache.org/licenses/LICENSE-2.0 62 | 63 | Unless required by applicable law or agreed to in writing, software 64 | distributed under the License is distributed on an "AS IS" BASIS, 65 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 66 | See the License for the specific language governing permissions and 67 | limitations under the License. 68 | ``` 69 | 70 | ## Related 71 | 72 | - [`canonicalize`](https://github.com/erdtman/canonicalize) 73 | - [`json-canonicalize`](https://github.com/snowyu/json-canonicalize.ts) 74 | -------------------------------------------------------------------------------- /js/json-canon/bench/index.js: -------------------------------------------------------------------------------- 1 | 'use strict' 2 | 3 | const Benchmark = require('benchmark') 4 | const suite = new Benchmark.Suite() 5 | 6 | const testData = require('./test.json') 7 | 8 | const stringifyPackages = { 9 | 'json-canon': require('../src/index'), 10 | 'JSON.stringify': JSON.stringify, 11 | 'fast-json-stable-stringify': true, 12 | 'json-stable-stringify': true, 13 | 'fast-stable-stringify': true, 14 | 'json-stringify-deterministic': true, 15 | 'faster-stable-stringify': true, 16 | 'fast-safe-stringify': true, 17 | 'safe-stable-stringify': true, 18 | canonicalize: true, 19 | 'json-canonicalize': require('json-canonicalize').canonicalize, 20 | } 21 | 22 | for (const name in stringifyPackages) { 23 | let func = stringifyPackages[name] 24 | if (func === true) func = require(name) 25 | 26 | suite.add(name, function () { 27 | func(testData) 28 | }) 29 | } 30 | 31 | suite 32 | .on('cycle', (event) => console.log(String(event.target))) 33 | .on('complete', function () { 34 | console.log('The fastest is ' + this.filter('fastest').map('name')) 35 | }) 36 | .run({ async: true }) 37 | -------------------------------------------------------------------------------- /js/json-canon/bench/test.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "_id": "59ef4a83ee8364808d761beb", 4 | "index": 0, 5 | "guid": "e50ffae9-7128-4148-9ee5-40c3fc523c5d", 6 | "isActive": false, 7 | "balance": "$2,341.81", 8 | "picture": "http://placehold.it/32x32", 9 | "age": 28, 10 | "eyeColor": "brown", 11 | "name": "Carey Savage", 12 | "gender": "female", 13 | "company": "VERAQ", 14 | "email": "careysavage@veraq.com", 15 | "phone": "+1 (897) 574-3014", 16 | "address": "458 Willow Street, Henrietta, California, 7234", 17 | "about": "Nisi reprehenderit nulla ad officia pariatur non dolore laboris irure cupidatat laborum. Minim eu ex Lorem adipisicing exercitation irure minim sunt est enim mollit incididunt voluptate nulla. Ut mollit anim reprehenderit et aliqua ex esse aliquip. Aute sit duis deserunt do incididunt consequat minim qui dolor commodo deserunt et voluptate.\r\n", 18 | "registered": "2014-05-21T01:56:51 -01:00", 19 | "latitude": 63.89502, 20 | "longitude": 62.369807, 21 | "tags": [ 22 | "nostrud", 23 | "nisi", 24 | "consectetur", 25 | "ullamco", 26 | "cupidatat", 27 | "culpa", 28 | "commodo" 29 | ], 30 | "friends": [ 31 | { 32 | "id": 0, 33 | "name": "Henry Walls" 34 | }, 35 | { 36 | "id": 1, 37 | "name": "Janice Baker" 38 | }, 39 | { 40 | "id": 2, 41 | "name": "Russell Bush" 42 | } 43 | ], 44 | "greeting": "Hello, Carey Savage! You have 4 unread messages.", 45 | "favoriteFruit": "banana" 46 | }, 47 | { 48 | "_id": "59ef4a83ff5774a691454e89", 49 | "index": 1, 50 | "guid": "2bee9efc-4095-4c2e-87ef-d08c8054c89d", 51 | "isActive": true, 52 | "balance": "$1,618.15", 53 | "picture": "http://placehold.it/32x32", 54 | "age": 35, 55 | "eyeColor": "blue", 56 | "name": "Elinor Pearson", 57 | "gender": "female", 58 | "company": "FLEXIGEN", 59 | "email": "elinorpearson@flexigen.com", 60 | "phone": "+1 (923) 548-3751", 61 | "address": "600 Bayview Avenue, Draper, Montana, 3088", 62 | "about": "Mollit commodo ea sit Lorem velit. Irure anim esse Lorem sint quis officia ut. Aliqua nisi dolore in aute deserunt mollit ex ea in mollit.\r\n", 63 | "registered": "2017-04-22T07:58:41 -01:00", 64 | "latitude": -87.824919, 65 | "longitude": 69.538927, 66 | "tags": [ 67 | "fugiat", 68 | "labore", 69 | "proident", 70 | "quis", 71 | "eiusmod", 72 | "qui", 73 | "est" 74 | ], 75 | "friends": [ 76 | { 77 | "id": 0, 78 | "name": "Massey Wagner" 79 | }, 80 | { 81 | "id": 1, 82 | "name": "Marcella Ferrell" 83 | }, 84 | { 85 | "id": 2, 86 | "name": "Evans Mckee" 87 | } 88 | ], 89 | "greeting": "Hello, Elinor Pearson! You have 3 unread messages.", 90 | "favoriteFruit": "strawberry" 91 | }, 92 | { 93 | "_id": "59ef4a839ec8a4be4430b36b", 94 | "index": 2, 95 | "guid": "ddd6e8c0-95bd-416d-8b46-a768d6363809", 96 | "isActive": false, 97 | "balance": "$2,046.95", 98 | "picture": "http://placehold.it/32x32", 99 | "age": 40, 100 | "eyeColor": "green", 101 | "name": "Irwin Davidson", 102 | "gender": "male", 103 | "company": "DANJA", 104 | "email": "irwindavidson@danja.com", 105 | "phone": "+1 (883) 537-2041", 106 | "address": "439 Cook Street, Chapin, Kentucky, 7398", 107 | "about": "Irure velit non commodo aliqua exercitation ut nostrud minim magna. Dolor ad ad ut irure eu. Non pariatur dolor eiusmod ipsum do et exercitation cillum. Et amet laboris minim eiusmod ullamco magna ea reprehenderit proident sunt.\r\n", 108 | "registered": "2016-09-01T07:49:08 -01:00", 109 | "latitude": -49.803812, 110 | "longitude": 104.93279, 111 | "tags": [ 112 | "consequat", 113 | "enim", 114 | "quis", 115 | "magna", 116 | "est", 117 | "culpa", 118 | "tempor" 119 | ], 120 | "friends": [ 121 | { 122 | "id": 0, 123 | "name": "Ruth Hansen" 124 | }, 125 | { 126 | "id": 1, 127 | "name": "Kathrine Austin" 128 | }, 129 | { 130 | "id": 2, 131 | "name": "Rivera Munoz" 132 | } 133 | ], 134 | "greeting": "Hello, Irwin Davidson! You have 2 unread messages.", 135 | "favoriteFruit": "banana" 136 | } 137 | ] 138 | -------------------------------------------------------------------------------- /js/json-canon/examples/basic.js: -------------------------------------------------------------------------------- 1 | const serialize = require('../src/index') 2 | 3 | const json = { 4 | from_account: "543 232 625-3", 5 | to_account: "321 567 636-4", 6 | amount: 500, 7 | currency: "USD" 8 | } 9 | 10 | console.log(serialize(json)) 11 | // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 12 | -------------------------------------------------------------------------------- /js/json-canon/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json-canon", 3 | "version": "1.0.1", 4 | "description": "Serialize JSON into a canonical format.", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "ava", 8 | "bench": "node bench" 9 | }, 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/ahdinosaur/json-canon.git" 13 | }, 14 | "keywords": [ 15 | "json", 16 | "jcs", 17 | "rfc8785", 18 | "canon", 19 | "canonical", 20 | "canonicalize", 21 | "crypto", 22 | "hashable", 23 | "hashing", 24 | "signable", 25 | "signing" 26 | ], 27 | "author": "Michael Williams ", 28 | "contributors": [ 29 | "Samuel Erdtman ", 30 | "Anders Rundgren " 31 | ], 32 | "license": "Apache-2.0", 33 | "bugs": { 34 | "url": "https://github.com/ahdinosaur/json-canon/issues" 35 | }, 36 | "homepage": "https://github.com/ahdinosaur/json-canon#readme", 37 | "devDependencies": { 38 | "benchmark": "^2.1.4", 39 | "canonicalize": "^2.0.0", 40 | "fast-json-stable-stringify": "latest", 41 | "fast-safe-stringify": "latest", 42 | "fast-stable-stringify": "latest", 43 | "faster-stable-stringify": "latest", 44 | "fastest-stable-stringify": "latest", 45 | "json-canonicalize": "^1.0.5", 46 | "json-stable-stringify": "latest", 47 | "json-stringify-deterministic": "latest", 48 | "json-stringify-safe": "latest", 49 | "safe-stable-stringify": "latest", 50 | "slump": "^3.0.2" 51 | }, 52 | "directories": { 53 | "example": "examples", 54 | "test": "test" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /js/json-canon/src/index.js: -------------------------------------------------------------------------------- 1 | module.exports = serialize 2 | 3 | /** 4 | * @param {unknown} value 5 | * @returns {string} 6 | */ 7 | function serialize(value) { 8 | const type = typeof value 9 | 10 | switch (type) { 11 | case 'undefined': 12 | case 'symbol': 13 | return serializeUndefined() 14 | case 'boolean': 15 | return serializeBoolean(value) 16 | case 'number': 17 | return serializeNumber(value) 18 | case 'string': 19 | return serializeString(value) 20 | case 'function': 21 | return serializeFunction(value) 22 | case 'object': 23 | break 24 | default: 25 | return JSON.stringify(value) 26 | } 27 | 28 | if (value === null) { 29 | return JSON.stringify(value) 30 | } 31 | 32 | if (value.toJSON instanceof Function) { 33 | return serialize(value.toJSON()) 34 | } 35 | 36 | if (Array.isArray(value)) { 37 | return serializeArray(value) 38 | } 39 | 40 | return serializeObject(value) 41 | } 42 | 43 | function serializeUndefined() { 44 | return 'null' 45 | } 46 | 47 | function serializeBoolean(bool) { 48 | if (bool) return 'true' 49 | else return 'false' 50 | } 51 | 52 | function serializeNumber(num) { 53 | if (isNaN(num)) { 54 | throw new Error('NaN is not allowed') 55 | } 56 | if (!isFinite(num)) { 57 | throw new Error('Infinity is not allowed') 58 | } 59 | return JSON.stringify(num) 60 | } 61 | 62 | // https://github.com/BridgeAR/safe-stable-stringify/blob/26dc000/index.js#L22-L33 63 | 64 | // eslint-disable-next-line no-control-regex 65 | const stringEscapeSequencesRegExp = 66 | /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/ 67 | 68 | function serializeString(str) { 69 | if (!isWellFormed(str)) { 70 | throw new Error( 71 | 'Strings must be valid Unicode and not contain any surrogate pairs', 72 | ) 73 | } 74 | if (str.length < 5000 && !stringEscapeSequencesRegExp.test(str)) { 75 | return '"' + str + '"' 76 | } 77 | return JSON.stringify(str) 78 | } 79 | 80 | function serializeFunction(fn) { 81 | return JSON.stringify(fn) 82 | } 83 | 84 | function serializeArray(arr) { 85 | let str = '[' 86 | const length = arr.length 87 | for (let i = 0; i < length; i++) { 88 | const val = arr[i] 89 | if (i !== 0) str += ',' 90 | str += serialize(val) 91 | } 92 | return str + ']' 93 | } 94 | 95 | function serializeObject(obj) { 96 | const sortedKeys = sort(Object.keys(obj)) 97 | let str = '{' 98 | const length = sortedKeys.length 99 | for (let i = 0; i < length; i++) { 100 | const key = sortedKeys[i] 101 | const val = obj[key] 102 | if (val === undefined || typeof val === 'symbol') { 103 | continue 104 | } 105 | if (i !== 0 && str.length !== 0) { 106 | str += ',' 107 | } 108 | str += serialize(key) + ':' + serialize(val) 109 | } 110 | return str + '}' 111 | } 112 | 113 | // https://github.com/BridgeAR/safe-stable-stringify/blob/26dc000/index.js#L35-L51 114 | function sort(array) { 115 | // Insertion sort is very efficient for small input sizes but it has a bad 116 | // worst case complexity. Thus, use native array sort for bigger values. 117 | if (array.length > 2e2) { 118 | return array.sort() 119 | } 120 | for (let i = 1; i < array.length; i++) { 121 | const currentValue = array[i] 122 | let position = i 123 | while (position !== 0 && array[position - 1] > currentValue) { 124 | array[position] = array[position - 1] 125 | position-- 126 | } 127 | array[position] = currentValue 128 | } 129 | return array 130 | } 131 | 132 | const stringSurrogateRegex = /\p{Surrogate}/u 133 | 134 | function isWellFormed(str) { 135 | if (typeof String.prototype.isWellFormed === 'function') { 136 | return str.isWellFormed() 137 | } 138 | 139 | return !stringSurrogateRegex.test(str) 140 | } 141 | -------------------------------------------------------------------------------- /js/json-canon/test/fixtures.js: -------------------------------------------------------------------------------- 1 | const test = require('ava') 2 | const { join } = require('path') 3 | const { readFileSync, readdirSync } = require('fs') 4 | 5 | const jsonCanon = require('../') 6 | 7 | const testDataBaseDir = join(__dirname, '../../../test-data') 8 | const testDataInputDir = join(testDataBaseDir, 'input') 9 | const testDataOutputDir = join(testDataBaseDir, 'output') 10 | 11 | readdirSync(testDataInputDir).forEach((name) => { 12 | test(name, (t) => { 13 | const input = readJsonSync(join(testDataInputDir, name)) 14 | const expected = readFileSync(join(testDataOutputDir, name), 'utf8').trim() 15 | const actual = jsonCanon(input) 16 | t.is(actual, expected) 17 | }) 18 | }) 19 | 20 | function readJsonSync(path) { 21 | return JSON.parse(readFileSync(path, 'utf8')) 22 | } 23 | -------------------------------------------------------------------------------- /js/json-canon/test/fuzz.js: -------------------------------------------------------------------------------- 1 | const test = require('ava') 2 | const random = require('slump') 3 | 4 | const canonicalize = require('canonicalize') 5 | const jsonCanon = require('../') 6 | 7 | test('random json', async (t) => { 8 | t.timeout(Infinity) 9 | 10 | const total = 1e4 11 | for (let i = 0; i < total; i++) { 12 | // if (i % 1e3 === 0) console.log(i) 13 | 14 | const json = random.json() 15 | 16 | const expected = canonicalize(json) 17 | 18 | let actual 19 | try { 20 | actual = jsonCanon(json) 21 | } catch (err) { 22 | if ( 23 | err.message === 24 | 'Strings must be valid Unicode and not contain any surrogate pairs' 25 | ) { 26 | continue 27 | } 28 | throw err 29 | } 30 | 31 | t.is(actual, expected) 32 | 33 | await nextTick() 34 | } 35 | }) 36 | 37 | function nextTick() { 38 | return new Promise((resolve) => { 39 | setTimeout(resolve) 40 | }) 41 | } 42 | -------------------------------------------------------------------------------- /js/json-canon/test/units.js: -------------------------------------------------------------------------------- 1 | const test = require('ava') 2 | 3 | const jsonCanon = require('../') 4 | 5 | test('empty array', (t) => { 6 | const input = [] 7 | const expected = '[]' 8 | const actual = jsonCanon(input) 9 | t.is(actual, expected) 10 | }) 11 | 12 | test('one element array', (t) => { 13 | const input = [123] 14 | const expected = '[123]' 15 | const actual = jsonCanon(input) 16 | t.is(actual, expected) 17 | }) 18 | 19 | test('multi element array', (t) => { 20 | const input = [123, 456, 'hello'] 21 | const expected = '[123,456,"hello"]' 22 | const actual = jsonCanon(input) 23 | t.is(actual, expected) 24 | }) 25 | 26 | test('null and undefined values in array', (t) => { 27 | const input = [null, undefined, 'hello'] 28 | const expected = '[null,null,"hello"]' 29 | const actual = jsonCanon(input) 30 | t.is(actual, expected) 31 | }) 32 | 33 | test('NaN in array', (t) => { 34 | try { 35 | const input = [NaN] 36 | jsonCanon(input) 37 | t.fail() 38 | } catch (error) { 39 | t.is(error.message, 'NaN is not allowed') 40 | t.pass() 41 | } 42 | }) 43 | 44 | test('NaN in object', (t) => { 45 | try { 46 | const input = { key: NaN } 47 | jsonCanon(input) 48 | t.fail() 49 | } catch (error) { 50 | t.is(error.message, 'NaN is not allowed') 51 | t.pass() 52 | } 53 | }) 54 | 55 | test('NaN single value', (t) => { 56 | try { 57 | const input = NaN 58 | jsonCanon(input) 59 | t.fail() 60 | } catch (error) { 61 | t.is(error.message, 'NaN is not allowed') 62 | t.pass() 63 | } 64 | }) 65 | 66 | test('Infinity in array', (t) => { 67 | try { 68 | const input = [Infinity] 69 | jsonCanon(input) 70 | t.fail() 71 | } catch (error) { 72 | t.is(error.message, 'Infinity is not allowed') 73 | t.pass() 74 | } 75 | }) 76 | 77 | test('Infinity in object', (t) => { 78 | try { 79 | const input = { key: Infinity } 80 | jsonCanon(input) 81 | t.fail() 82 | } catch (error) { 83 | t.is(error.message, 'Infinity is not allowed') 84 | t.pass() 85 | } 86 | }) 87 | 88 | test('Infinity single value', (t) => { 89 | try { 90 | const input = -Infinity 91 | jsonCanon(input) 92 | t.fail() 93 | } catch (error) { 94 | t.is(error.message, 'Infinity is not allowed') 95 | t.pass() 96 | } 97 | }) 98 | 99 | test('object in array', (t) => { 100 | const input = [{ b: 123, a: 'string' }] 101 | const expected = '[{"a":"string","b":123}]' 102 | const actual = jsonCanon(input) 103 | t.is(actual, expected) 104 | }) 105 | 106 | test('empty object', (t) => { 107 | const input = {} 108 | const expected = '{}' 109 | const actual = jsonCanon(input) 110 | t.is(actual, expected) 111 | }) 112 | 113 | test('object with undefined value', (t) => { 114 | const input = { test: undefined } 115 | const expected = '{}' 116 | const actual = jsonCanon(input) 117 | t.is(actual, expected) 118 | }) 119 | 120 | test('object with null value', (t) => { 121 | const input = { test: null } 122 | const expected = '{"test":null}' 123 | const actual = jsonCanon(input) 124 | t.is(actual, expected) 125 | }) 126 | 127 | test('object with one property', (t) => { 128 | const input = { hello: 'world' } 129 | const expected = '{"hello":"world"}' 130 | const actual = jsonCanon(input) 131 | t.is(actual, expected) 132 | }) 133 | 134 | test('object with more than one property', (t) => { 135 | const input = { hello: 'world', number: 123 } 136 | const expected = '{"hello":"world","number":123}' 137 | const actual = jsonCanon(input) 138 | t.is(actual, expected) 139 | }) 140 | 141 | test('undefined', (t) => { 142 | const input = undefined 143 | const expected = 'null' 144 | const actual = jsonCanon(input) 145 | t.is(actual, expected) 146 | }) 147 | 148 | test('null', (t) => { 149 | const input = null 150 | const expected = 'null' 151 | const actual = jsonCanon(input) 152 | t.is(actual, expected) 153 | }) 154 | 155 | test('symbol', (t) => { 156 | const input = Symbol('hello world') 157 | const expected = 'null' 158 | const actual = jsonCanon(input) 159 | t.is(actual, expected) 160 | }) 161 | 162 | test('object with symbol value', (t) => { 163 | const input = { test: Symbol('hello world') } 164 | const expected = '{}' 165 | const actual = jsonCanon(input) 166 | t.is(actual, expected) 167 | }) 168 | 169 | test('object with number key', (t) => { 170 | const input = { 42: 'foo' } 171 | const expected = '{"42":"foo"}' 172 | const actual = jsonCanon(input) 173 | t.is(actual, expected) 174 | }) 175 | 176 | test('object with symbol key', (t) => { 177 | const input = { [Symbol('hello world')]: 'foo' } 178 | const expected = '{}' 179 | const actual = jsonCanon(input) 180 | t.is(actual, expected) 181 | }) 182 | 183 | test('object with toJSON', (t) => { 184 | const input = { 185 | a: 123, 186 | b: 456, 187 | toJSON: function () { 188 | return { 189 | b: this.b, 190 | a: this.a, 191 | } 192 | }, 193 | } 194 | const expected = '{"a":123,"b":456}' 195 | const actual = jsonCanon(input) 196 | t.is(actual, expected) 197 | }) 198 | 199 | test('"lone surrogate" invalid Unicode data', (t) => { 200 | const input = { test: '\u{DEAD}' } 201 | try { 202 | console.log(jsonCanon(input)) 203 | t.fail() 204 | } catch (error) { 205 | t.is( 206 | error.message, 207 | 'Strings must be valid Unicode and not contain any surrogate pairs', 208 | ) 209 | t.pass() 210 | } 211 | }) 212 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json-canon-project", 3 | "scripts": { 4 | "test": "npm run test --workspaces --if-present", 5 | "bench": "npm run bench --workspaces --if-present", 6 | "lint": "prettier --check \"./js/*/(src|test|bench)/**/*.js\"", 7 | "format": "prettier --write \"./js/*/(src|test|bench)/**/*.js\"", 8 | "format-staged": "pretty-quick --staged -pattern \"./js/*/(src|test|bench)/**/*.js\"", 9 | "clean:generate": "rm test-data/generated/*", 10 | "generate": "npm run generate:numbers && npm run generate:json", 11 | "generate:numbers": "json-canon-fuzz numbers 1000000 test-data/generated/numbers.txt", 12 | "generate:json": "json-canon-fuzz json 100000 test-data/generated/json.txt" 13 | }, 14 | "workspaces": [ 15 | "./js/*" 16 | ], 17 | "devDependencies": { 18 | "ava": "^5.2.0", 19 | "husky": "^8.0.3", 20 | "pretty": "^2.0.0", 21 | "pretty-quick": "^3.1.3" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /rust/json-canon/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "json-canon" 3 | version = "0.1.3" 4 | authors = ["Michael Williams "] 5 | edition = "2021" 6 | rust-version = "1.56.1" 7 | license = "Apache-2.0" 8 | description = "Serialize JSON into a canonical format." 9 | repository = "https://github.com/ahdinosaur/json-canon" 10 | keywords = ["json", "serde", "serialization", "canonical"] 11 | categories = ["encoding"] 12 | readme = "README.md" 13 | 14 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 15 | 16 | [dependencies] 17 | ryu-js = { version = "0.2.2", default-features = false } 18 | serde = { version = "1.0.162", default-features = false } 19 | serde_json = { version = "1.0.96", default-features = false, features = ["std", "float_roundtrip"] } 20 | 21 | [dev-dependencies] 22 | criterion = "0.3" 23 | serde_derive = "1.0.163" 24 | 25 | [[bench]] 26 | name = "basic" 27 | harness = false 28 | -------------------------------------------------------------------------------- /rust/json-canon/LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /rust/json-canon/README.md: -------------------------------------------------------------------------------- 1 | # `json-canon` 2 | 3 | [![Crates.io version](https://img.shields.io/crates/v/json-canon.svg?style=flat-square)](https://crates.io/crates/json-canon) [![Download](https://img.shields.io/crates/d/json-canon.svg?style=flat-square)](https://crates.io/crates/json-canon) [![docs.rs docs](https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square)](https://docs.rs/json-canon) 4 | 5 | Serialize JSON into a canonical format. 6 | 7 | ## Install 8 | 9 | ```shell 10 | cargo add json-canon 11 | ``` 12 | 13 | ## Example 14 | 15 | ```rust 16 | use json_canon::to_string; 17 | use serde_json::json; 18 | 19 | let data = json!({ 20 | "from_account": "543 232 625-3", 21 | "to_account": "321 567 636-4", 22 | "amount": 500, 23 | "currency": "USD" 24 | }); 25 | 26 | println!("{}", to_string(&data)?); 27 | // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 28 | ``` 29 | 30 | See [`./examples/basic.rs`](./examples/basic.rs) 31 | 32 | ## Usage 33 | 34 | See [docs](https://docs.rs/json-canon/) 35 | 36 | ## Caveats 37 | 38 | Different from [the JavaScript implementation](../../js/json-canon), `serde_json` deserializes `f64::NAN` and `f64::Infinite` as `None`, so if given a Rust struct with these values, the `json-canon` serializer will currently output `"null"`. 39 | 40 | ## Bench 41 | 42 | ``` 43 | from_elem/basic/[{"_id":"59ef4a83ee8364808d761beb","about":"Nisi reprehenderit nulla ad officia pari... 44 | time: [28.019 µs 28.032 µs 28.047 µs] 45 | thrpt: [35.654 Kelem/s 35.673 Kelem/s 35.690 Kelem/s] 46 | ``` 47 | 48 | ## License 49 | 50 | ```txt 51 | Copyright 2023 Michael Williams 52 | 53 | Licensed under the Apache License, Version 2.0 (the "License"); 54 | you may not use this file except in compliance with the License. 55 | You may obtain a copy of the License at 56 | 57 | http://www.apache.org/licenses/LICENSE-2.0 58 | 59 | Unless required by applicable law or agreed to in writing, software 60 | distributed under the License is distributed on an "AS IS" BASIS, 61 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 62 | See the License for the specific language governing permissions and 63 | limitations under the License. 64 | ``` 65 | 66 | ## Related 67 | 68 | - [`l1h3r/serde_jcs`](https://github.com/l1h3r/serde_jcs) 69 | -------------------------------------------------------------------------------- /rust/json-canon/benches/basic.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "_id": "59ef4a83ee8364808d761beb", 4 | "index": 0, 5 | "guid": "e50ffae9-7128-4148-9ee5-40c3fc523c5d", 6 | "isActive": false, 7 | "balance": "$2,341.81", 8 | "picture": "http://placehold.it/32x32", 9 | "age": 28, 10 | "eyeColor": "brown", 11 | "name": "Carey Savage", 12 | "gender": "female", 13 | "company": "VERAQ", 14 | "email": "careysavage@veraq.com", 15 | "phone": "+1 (897) 574-3014", 16 | "address": "458 Willow Street, Henrietta, California, 7234", 17 | "about": "Nisi reprehenderit nulla ad officia pariatur non dolore laboris irure cupidatat laborum. Minim eu ex Lorem adipisicing exercitation irure minim sunt est enim mollit incididunt voluptate nulla. Ut mollit anim reprehenderit et aliqua ex esse aliquip. Aute sit duis deserunt do incididunt consequat minim qui dolor commodo deserunt et voluptate.\r\n", 18 | "registered": "2014-05-21T01:56:51 -01:00", 19 | "latitude": 63.89502, 20 | "longitude": 62.369807, 21 | "tags": [ 22 | "nostrud", 23 | "nisi", 24 | "consectetur", 25 | "ullamco", 26 | "cupidatat", 27 | "culpa", 28 | "commodo" 29 | ], 30 | "friends": [ 31 | { 32 | "id": 0, 33 | "name": "Henry Walls" 34 | }, 35 | { 36 | "id": 1, 37 | "name": "Janice Baker" 38 | }, 39 | { 40 | "id": 2, 41 | "name": "Russell Bush" 42 | } 43 | ], 44 | "greeting": "Hello, Carey Savage! You have 4 unread messages.", 45 | "favoriteFruit": "banana" 46 | }, 47 | { 48 | "_id": "59ef4a83ff5774a691454e89", 49 | "index": 1, 50 | "guid": "2bee9efc-4095-4c2e-87ef-d08c8054c89d", 51 | "isActive": true, 52 | "balance": "$1,618.15", 53 | "picture": "http://placehold.it/32x32", 54 | "age": 35, 55 | "eyeColor": "blue", 56 | "name": "Elinor Pearson", 57 | "gender": "female", 58 | "company": "FLEXIGEN", 59 | "email": "elinorpearson@flexigen.com", 60 | "phone": "+1 (923) 548-3751", 61 | "address": "600 Bayview Avenue, Draper, Montana, 3088", 62 | "about": "Mollit commodo ea sit Lorem velit. Irure anim esse Lorem sint quis officia ut. Aliqua nisi dolore in aute deserunt mollit ex ea in mollit.\r\n", 63 | "registered": "2017-04-22T07:58:41 -01:00", 64 | "latitude": -87.824919, 65 | "longitude": 69.538927, 66 | "tags": [ 67 | "fugiat", 68 | "labore", 69 | "proident", 70 | "quis", 71 | "eiusmod", 72 | "qui", 73 | "est" 74 | ], 75 | "friends": [ 76 | { 77 | "id": 0, 78 | "name": "Massey Wagner" 79 | }, 80 | { 81 | "id": 1, 82 | "name": "Marcella Ferrell" 83 | }, 84 | { 85 | "id": 2, 86 | "name": "Evans Mckee" 87 | } 88 | ], 89 | "greeting": "Hello, Elinor Pearson! You have 3 unread messages.", 90 | "favoriteFruit": "strawberry" 91 | }, 92 | { 93 | "_id": "59ef4a839ec8a4be4430b36b", 94 | "index": 2, 95 | "guid": "ddd6e8c0-95bd-416d-8b46-a768d6363809", 96 | "isActive": false, 97 | "balance": "$2,046.95", 98 | "picture": "http://placehold.it/32x32", 99 | "age": 40, 100 | "eyeColor": "green", 101 | "name": "Irwin Davidson", 102 | "gender": "male", 103 | "company": "DANJA", 104 | "email": "irwindavidson@danja.com", 105 | "phone": "+1 (883) 537-2041", 106 | "address": "439 Cook Street, Chapin, Kentucky, 7398", 107 | "about": "Irure velit non commodo aliqua exercitation ut nostrud minim magna. Dolor ad ad ut irure eu. Non pariatur dolor eiusmod ipsum do et exercitation cillum. Et amet laboris minim eiusmod ullamco magna ea reprehenderit proident sunt.\r\n", 108 | "registered": "2016-09-01T07:49:08 -01:00", 109 | "latitude": -49.803812, 110 | "longitude": 104.93279, 111 | "tags": [ 112 | "consequat", 113 | "enim", 114 | "quis", 115 | "magna", 116 | "est", 117 | "culpa", 118 | "tempor" 119 | ], 120 | "friends": [ 121 | { 122 | "id": 0, 123 | "name": "Ruth Hansen" 124 | }, 125 | { 126 | "id": 1, 127 | "name": "Kathrine Austin" 128 | }, 129 | { 130 | "id": 2, 131 | "name": "Rivera Munoz" 132 | } 133 | ], 134 | "greeting": "Hello, Irwin Davidson! You have 2 unread messages.", 135 | "favoriteFruit": "banana" 136 | } 137 | ] 138 | -------------------------------------------------------------------------------- /rust/json-canon/benches/basic.rs: -------------------------------------------------------------------------------- 1 | use std::{env::current_dir, fs::read_to_string, path::Path}; 2 | 3 | use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; 4 | 5 | use json_canon::to_string; 6 | use serde_json::{from_str, Value}; 7 | 8 | fn bench_input(value: &Value) { 9 | to_string(value).unwrap(); 10 | } 11 | 12 | fn from_elem(c: &mut Criterion) { 13 | let test_data_path = current_dir() 14 | .unwrap() 15 | .join(Path::new("./benches/basic.json")); 16 | let test_data_str = read_to_string(test_data_path).unwrap(); 17 | let test_data: Value = from_str(&test_data_str).unwrap(); 18 | let mut group = c.benchmark_group("from_elem"); 19 | group.throughput(Throughput::Elements(1)); 20 | group.bench_with_input(BenchmarkId::new("basic", &test_data), &test_data, |b, v| { 21 | b.iter(|| bench_input(&v)); 22 | }); 23 | group.finish(); 24 | } 25 | 26 | criterion_group!(benches, from_elem); 27 | criterion_main!(benches); 28 | -------------------------------------------------------------------------------- /rust/json-canon/examples/basic.rs: -------------------------------------------------------------------------------- 1 | use json_canon::to_string; 2 | use serde_json::{json, Error}; 3 | 4 | fn main() -> Result<(), Error> { 5 | let data = json!({ 6 | "from_account": "543 232 625-3", 7 | "to_account": "321 567 636-4", 8 | "amount": 500, 9 | "currency": "USD" 10 | }); 11 | 12 | println!("{}", to_string(&data)?); 13 | // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 14 | 15 | Ok(()) 16 | } 17 | -------------------------------------------------------------------------------- /rust/json-canon/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # `json-canon` 2 | //! 3 | //! Serialize JSON into a canonical format. 4 | //! 5 | //! Safe for generating a consistent cryptographic hash or signature across platforms. 6 | //! 7 | //! Follows [RFC8785: JSON Canonicalization Scheme (JCS)] 8 | //! 9 | //! [RFC8785: JSON Canonicalization Scheme (JCS)]: https://tools.ietf.org/html/rfc8785 10 | //! 11 | //! ## Example 12 | //! 13 | //! ```rust 14 | //! use json_canon::to_string; 15 | //! use serde_json::json; 16 | //! # use serde_json::Error; 17 | //! # fn main() -> Result<(), Error> { 18 | //! 19 | //! let data = json!({ 20 | //! "from_account": "543 232 625-3", 21 | //! "to_account": "321 567 636-4", 22 | //! "amount": 500, 23 | //! "currency": "USD" 24 | //! }); 25 | //! 26 | //! println!("{}", to_string(&data)?); 27 | //! // {"amount":500,"currency":"USD","from_account":"543 232 625-3","to_account":"321 567 636-4"} 28 | //! # Ok(()) 29 | //! # } 30 | //! ``` 31 | //! 32 | //! ## Caveats 33 | //! 34 | //! `serde_json` deserializes `f64::NAN` and `f64::Infinite` as `None`, so if given a Rust struct with these values, the `json-canon` will currently output `"null"`. 35 | //! 36 | 37 | mod object; 38 | mod ser; 39 | 40 | pub use self::ser::{to_string, to_vec, to_writer}; 41 | -------------------------------------------------------------------------------- /rust/json-canon/src/object.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | io::{self, sink, Error, ErrorKind, Write}, 3 | str::from_utf8_unchecked, 4 | }; 5 | 6 | use serde_json::ser::{CompactFormatter, Formatter}; 7 | 8 | #[derive(Clone, Debug)] 9 | pub(crate) struct ObjectEntry { 10 | key: Vec, 11 | key_bytes: Vec, 12 | value: Vec, 13 | is_key_done: bool, 14 | } 15 | 16 | impl ObjectEntry { 17 | pub(crate) fn new() -> Self { 18 | Self { 19 | key: Vec::new(), 20 | key_bytes: Vec::new(), 21 | value: Vec::new(), 22 | is_key_done: false, 23 | } 24 | } 25 | 26 | #[inline] 27 | pub(crate) fn end_key(&mut self) { 28 | self.is_key_done = true; 29 | } 30 | 31 | pub(crate) fn is_in_key(&mut self) -> bool { 32 | !self.is_key_done 33 | } 34 | 35 | #[inline] 36 | pub(crate) fn cmpable(&self) -> impl Iterator { 37 | let key_orig = unsafe { from_utf8_unchecked(self.key_bytes.as_slice()) }; 38 | key_orig.encode_utf16() 39 | } 40 | 41 | #[inline] 42 | pub(crate) fn scope(&mut self) -> io::Result { 43 | if self.is_in_key() { 44 | Ok(&mut self.key) 45 | } else { 46 | Ok(&mut self.value) 47 | } 48 | } 49 | 50 | #[inline] 51 | pub(crate) fn scope_with_key(&mut self) -> io::Result { 52 | let writer = if self.is_in_key() { 53 | EitherWriter::Left(BothWriter::new(&mut self.key, &mut self.key_bytes)) 54 | } else { 55 | EitherWriter::Right(&mut self.value) 56 | }; 57 | Ok(writer) 58 | } 59 | 60 | #[inline] 61 | pub(crate) fn key_bytes(&mut self) -> io::Result { 62 | let writer = if self.is_in_key() { 63 | EitherWriter::Left(&mut self.key_bytes) 64 | } else { 65 | EitherWriter::Right(sink()) 66 | }; 67 | Ok(writer) 68 | } 69 | 70 | #[inline] 71 | pub(crate) fn write_to(&self, first: bool, writer: &mut W) -> io::Result<()> 72 | where 73 | W: Write + ?Sized, 74 | { 75 | CompactFormatter.begin_object_key(writer, first)?; 76 | writer.write_all(self.key.as_slice())?; 77 | CompactFormatter.end_object_key(writer)?; 78 | 79 | CompactFormatter.begin_object_value(writer)?; 80 | writer.write_all(self.value.as_slice())?; 81 | CompactFormatter.end_object_value(writer)?; 82 | 83 | Ok(()) 84 | } 85 | } 86 | 87 | #[derive(Clone, Debug)] 88 | pub(crate) struct Object { 89 | entries: Vec, 90 | } 91 | 92 | impl Object { 93 | pub(crate) fn new() -> Self { 94 | Self { 95 | entries: Vec::new(), 96 | } 97 | } 98 | 99 | pub(crate) fn current_entry(&mut self) -> io::Result<&mut ObjectEntry> { 100 | self.entries.last_mut().ok_or_else(|| { 101 | Error::new( 102 | ErrorKind::InvalidData, 103 | "Object entry requested when entry is not active.", 104 | ) 105 | }) 106 | } 107 | 108 | #[inline] 109 | pub(crate) fn start_key(&mut self) { 110 | self.entries.push(ObjectEntry::new()) 111 | } 112 | 113 | #[inline] 114 | pub(crate) fn end_key(&mut self) -> io::Result<()> { 115 | self.current_entry()?.end_key(); 116 | Ok(()) 117 | } 118 | 119 | #[inline] 120 | pub(crate) fn is_in_key(&mut self) -> io::Result { 121 | let is_in_key = self.current_entry()?.is_in_key(); 122 | Ok(is_in_key) 123 | } 124 | 125 | #[inline] 126 | pub(crate) fn scope(&mut self) -> io::Result { 127 | let writer = self.current_entry()?.scope()?; 128 | Ok(writer) 129 | } 130 | 131 | #[inline] 132 | pub(crate) fn scope_with_key(&mut self) -> io::Result { 133 | let writer = self.current_entry()?.scope_with_key()?; 134 | Ok(writer) 135 | } 136 | 137 | #[inline] 138 | pub(crate) fn key_bytes(&mut self) -> io::Result { 139 | let writer = self.current_entry()?.key_bytes()?; 140 | Ok(writer) 141 | } 142 | 143 | #[inline] 144 | pub(crate) fn write_to(&mut self, writer: &mut W) -> io::Result<()> 145 | where 146 | W: Write + ?Sized, 147 | { 148 | CompactFormatter.begin_object(writer)?; 149 | 150 | let entries = &mut self.entries; 151 | 152 | entries.sort_by(|a, b| a.cmpable().cmp(b.cmpable())); 153 | 154 | let mut first = true; 155 | for entry in entries { 156 | entry.write_to(first, writer)?; 157 | 158 | first = false; 159 | } 160 | 161 | CompactFormatter.end_object(writer)?; 162 | 163 | Ok(()) 164 | } 165 | } 166 | 167 | #[derive(Clone, Debug)] 168 | pub(crate) struct ObjectStack { 169 | objects: Vec, 170 | } 171 | 172 | impl ObjectStack { 173 | pub(crate) fn new() -> Self { 174 | Self { 175 | objects: Vec::new(), 176 | } 177 | } 178 | 179 | pub(crate) fn current_object(&mut self) -> io::Result<&mut Object> { 180 | self.objects.last_mut().ok_or_else(|| { 181 | Error::new( 182 | ErrorKind::InvalidData, 183 | "Object requested when object is not active.", 184 | ) 185 | }) 186 | } 187 | 188 | pub(crate) fn has_current_object(&mut self) -> bool { 189 | !self.objects.is_empty() 190 | } 191 | 192 | #[inline] 193 | pub(crate) fn start_object(&mut self) { 194 | self.objects.push(Object::new()) 195 | } 196 | 197 | #[inline] 198 | pub(crate) fn end_object(&mut self, writer: &mut W) -> io::Result<()> 199 | where 200 | W: Write + ?Sized, 201 | { 202 | let mut object = self.objects.pop().ok_or_else(|| { 203 | Error::new( 204 | ErrorKind::InvalidData, 205 | "Object requested when object is not active.", 206 | ) 207 | })?; 208 | 209 | if self.has_current_object() { 210 | let mut writer = self.current_object()?.scope()?; 211 | object.write_to(&mut writer)?; 212 | } else { 213 | object.write_to(writer)?; 214 | } 215 | Ok(()) 216 | } 217 | 218 | #[inline] 219 | pub(crate) fn start_key(&mut self) -> io::Result<()> { 220 | self.current_object()?.start_key(); 221 | Ok(()) 222 | } 223 | 224 | #[inline] 225 | pub(crate) fn end_key(&mut self) -> io::Result<()> { 226 | self.current_object()?.end_key()?; 227 | Ok(()) 228 | } 229 | 230 | #[inline] 231 | pub(crate) fn is_in_key(&mut self) -> io::Result { 232 | let is_in_key = if self.has_current_object() { 233 | self.current_object()?.is_in_key()? 234 | } else { 235 | false 236 | }; 237 | Ok(is_in_key) 238 | } 239 | 240 | pub(crate) fn scope<'a, W>(&'a mut self, writer: &'a mut W) -> io::Result 241 | where 242 | W: Write + ?Sized, 243 | { 244 | let writer: EitherWriter<_, _> = if self.has_current_object() { 245 | let object_writer = self.current_object()?.scope()?; 246 | EitherWriter::Left(object_writer) 247 | } else { 248 | EitherWriter::Right(writer) 249 | }; 250 | Ok(writer) 251 | } 252 | 253 | pub(crate) fn scope_with_key<'a, W>( 254 | &'a mut self, 255 | writer: &'a mut W, 256 | ) -> io::Result 257 | where 258 | W: Write + ?Sized, 259 | { 260 | let writer: EitherWriter<_, _> = if self.has_current_object() { 261 | let object_writer = self.current_object()?.scope_with_key()?; 262 | EitherWriter::Left(object_writer) 263 | } else { 264 | EitherWriter::Right(writer) 265 | }; 266 | Ok(writer) 267 | } 268 | 269 | pub(crate) fn key_bytes(&mut self) -> io::Result { 270 | let writer: EitherWriter<_, _> = if self.has_current_object() { 271 | let key_bytes_writer = self.current_object()?.key_bytes()?; 272 | EitherWriter::Left(key_bytes_writer) 273 | } else { 274 | EitherWriter::Right(sink()) 275 | }; 276 | Ok(writer) 277 | } 278 | } 279 | 280 | enum EitherWriter { 281 | Left(LeftWriter), 282 | Right(RightWriter), 283 | } 284 | 285 | impl Write for EitherWriter 286 | where 287 | LeftWriter: Write, 288 | RightWriter: Write, 289 | { 290 | fn write(&mut self, buf: &[u8]) -> io::Result { 291 | match self { 292 | EitherWriter::Left(writer) => writer.write(buf), 293 | EitherWriter::Right(writer) => writer.write(buf), 294 | } 295 | } 296 | 297 | fn flush(&mut self) -> io::Result<()> { 298 | match self { 299 | EitherWriter::Left(writer) => writer.flush(), 300 | EitherWriter::Right(writer) => writer.flush(), 301 | } 302 | } 303 | } 304 | 305 | struct BothWriter { 306 | left: LeftWriter, 307 | right: RightWriter, 308 | } 309 | 310 | impl BothWriter { 311 | fn new(left: LeftWriter, right: RightWriter) -> Self { 312 | Self { left, right } 313 | } 314 | } 315 | 316 | impl Write for BothWriter 317 | where 318 | LeftWriter: Write, 319 | RightWriter: Write, 320 | { 321 | fn write(&mut self, buf: &[u8]) -> io::Result { 322 | self.left.write_all(buf)?; 323 | self.right.write_all(buf)?; 324 | self.flush()?; 325 | Ok(buf.len()) 326 | } 327 | 328 | fn flush(&mut self) -> io::Result<()> { 329 | self.left.flush()?; 330 | self.right.flush()?; 331 | Ok(()) 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /rust/json-canon/src/ser.rs: -------------------------------------------------------------------------------- 1 | use core::num::FpCategory; 2 | use serde::Serialize; 3 | use serde_json::{ 4 | ser::{CharEscape, CompactFormatter, Formatter}, 5 | Result, Serializer, 6 | }; 7 | 8 | use std::io::{self, Error, ErrorKind, Write}; 9 | 10 | use crate::object::ObjectStack; 11 | 12 | /// Serialize the given value as a String of JSON. 13 | /// 14 | /// Serialization is performed as specified in [RFC 8785](https://tools.ietf.org/html/rfc8785). 15 | /// 16 | /// # Errors 17 | /// 18 | /// Serialization can fail if `T`'s implementation of `Serialize` fails. 19 | #[inline] 20 | pub fn to_string(value: &T) -> Result 21 | where 22 | T: Serialize + ?Sized, 23 | { 24 | let data: Vec = to_vec(value)?; 25 | 26 | let data: String = unsafe { String::from_utf8_unchecked(data) }; 27 | 28 | Ok(data) 29 | } 30 | 31 | /// Serialize the given value as a JSON byte vector. 32 | /// 33 | /// Serialization is performed as specified in [RFC 8785](https://tools.ietf.org/html/rfc8785). 34 | /// 35 | /// # Errors 36 | /// 37 | /// Serialization can fail if `T`'s implementation of `Serialize` fails. 38 | #[inline] 39 | pub fn to_vec(value: &T) -> Result> 40 | where 41 | T: Serialize + ?Sized, 42 | { 43 | let mut data: Vec = Vec::with_capacity(128); 44 | 45 | to_writer(&mut data, value)?; 46 | 47 | Ok(data) 48 | } 49 | 50 | /// Serialize the given value as JSON into the IO stream. 51 | /// 52 | /// Serialization is performed as specified in [RFC 8785](https://tools.ietf.org/html/rfc8785). 53 | /// 54 | /// # Errors 55 | /// 56 | /// Serialization can fail if `T`'s implementation of `Serialize` fails. 57 | #[inline] 58 | pub fn to_writer(writer: W, value: &T) -> Result<()> 59 | where 60 | W: Write, 61 | T: Serialize + ?Sized, 62 | { 63 | value.serialize(&mut Serializer::with_formatter( 64 | writer, 65 | CanonicalFormatter::new(), 66 | )) 67 | } 68 | 69 | static MAX_SAFE_INTEGER_U64: u64 = 9_007_199_254_740_991; 70 | static MAX_SAFE_INTEGER_I64: i64 = 9_007_199_254_740_991; 71 | static MAX_SAFE_INTEGER_U128: u128 = 9_007_199_254_740_991; 72 | static MAX_SAFE_INTEGER_I128: i128 = 9_007_199_254_740_991; 73 | 74 | #[derive(Clone, Debug)] 75 | #[repr(transparent)] 76 | pub struct CanonicalFormatter { 77 | stack: ObjectStack, 78 | } 79 | 80 | impl CanonicalFormatter { 81 | pub fn new() -> Self { 82 | Self { 83 | stack: ObjectStack::new(), 84 | } 85 | } 86 | } 87 | 88 | impl Formatter for CanonicalFormatter { 89 | /// Writes a `null` value to the specified writer. 90 | #[inline] 91 | fn write_null(&mut self, writer: &mut W) -> io::Result<()> 92 | where 93 | W: Write + ?Sized, 94 | { 95 | let mut writer = self.stack.scope(writer)?; 96 | writer.write_all(b"null")?; 97 | Ok(()) 98 | } 99 | 100 | /// Writes a `true` or `false` value to the specified writer. 101 | #[inline] 102 | fn write_bool(&mut self, writer: &mut W, value: bool) -> io::Result<()> 103 | where 104 | W: Write + ?Sized, 105 | { 106 | let mut writer = self.stack.scope(writer)?; 107 | if value { 108 | writer.write_all(b"true")?; 109 | } else { 110 | writer.write_all(b"false")?; 111 | } 112 | Ok(()) 113 | } 114 | 115 | /// Writes an integer value like `-123` to the specified writer. 116 | #[inline] 117 | fn write_i8(&mut self, writer: &mut W, value: i8) -> io::Result<()> 118 | where 119 | W: Write + ?Sized, 120 | { 121 | CompactFormatter.write_i8(&mut self.stack.scope_with_key(writer)?, value) 122 | } 123 | 124 | /// Writes an integer value like `-123` to the specified writer. 125 | #[inline] 126 | fn write_i16(&mut self, writer: &mut W, value: i16) -> io::Result<()> 127 | where 128 | W: Write + ?Sized, 129 | { 130 | CompactFormatter.write_i16(&mut self.stack.scope_with_key(writer)?, value) 131 | } 132 | 133 | /// Writes an integer value like `-123` to the specified writer. 134 | #[inline] 135 | fn write_i32(&mut self, writer: &mut W, value: i32) -> io::Result<()> 136 | where 137 | W: Write + ?Sized, 138 | { 139 | CompactFormatter.write_i32(&mut self.stack.scope_with_key(writer)?, value) 140 | } 141 | 142 | /// Writes an integer value like `-123` to the specified writer. 143 | /// 144 | /// Integer `value.abs()` must be safe for JSON: less than `2.pow(53) - 1` 145 | #[inline] 146 | fn write_i64(&mut self, writer: &mut W, value: i64) -> io::Result<()> 147 | where 148 | W: Write + ?Sized, 149 | { 150 | if !self.stack.is_in_key()? && value.abs() > MAX_SAFE_INTEGER_I64 { 151 | Err(Error::new( 152 | ErrorKind::InvalidData, 153 | "i64.abs() must be less than JSON max safe integer", 154 | )) 155 | } else { 156 | CompactFormatter.write_i64(&mut self.stack.scope(writer)?, value) 157 | } 158 | } 159 | 160 | /// Writes an integer value like `-123` to the specified writer. 161 | /// 162 | /// Integer `value.abs()` must be safe for JSON: less than `2.pow(53) - 1` 163 | #[inline] 164 | fn write_i128(&mut self, writer: &mut W, value: i128) -> io::Result<()> 165 | where 166 | W: Write + ?Sized, 167 | { 168 | if !self.stack.is_in_key()? && value.abs() > MAX_SAFE_INTEGER_I128 { 169 | Err(Error::new( 170 | ErrorKind::InvalidData, 171 | "i128.abs() must be less than JSON max safe integer", 172 | )) 173 | } else { 174 | CompactFormatter.write_i128(&mut self.stack.scope(writer)?, value) 175 | } 176 | } 177 | 178 | /// Writes an integer value like `123` to the specified writer. 179 | #[inline] 180 | fn write_u8(&mut self, writer: &mut W, value: u8) -> io::Result<()> 181 | where 182 | W: Write + ?Sized, 183 | { 184 | CompactFormatter.write_u8(&mut self.stack.scope_with_key(writer)?, value) 185 | } 186 | 187 | /// Writes an integer value like `123` to the specified writer. 188 | #[inline] 189 | fn write_u16(&mut self, writer: &mut W, value: u16) -> io::Result<()> 190 | where 191 | W: Write + ?Sized, 192 | { 193 | CompactFormatter.write_u16(&mut self.stack.scope_with_key(writer)?, value) 194 | } 195 | 196 | /// Writes an integer value like `123` to the specified writer. 197 | #[inline] 198 | fn write_u32(&mut self, writer: &mut W, value: u32) -> io::Result<()> 199 | where 200 | W: Write + ?Sized, 201 | { 202 | CompactFormatter.write_u32(&mut self.stack.scope_with_key(writer)?, value) 203 | } 204 | 205 | /// Writes an integer value like `123` to the specified writer. 206 | /// 207 | /// Integer `value` must be safe for JSON: less than `2.pow(53) - 1` 208 | #[inline] 209 | fn write_u64(&mut self, writer: &mut W, value: u64) -> io::Result<()> 210 | where 211 | W: Write + ?Sized, 212 | { 213 | if !self.stack.is_in_key()? && value > MAX_SAFE_INTEGER_U64 { 214 | Err(Error::new( 215 | ErrorKind::InvalidData, 216 | "u64 must be less than JSON max safe integer", 217 | )) 218 | } else { 219 | CompactFormatter.write_u64(&mut self.stack.scope(writer)?, value) 220 | } 221 | } 222 | 223 | /// Writes an integer value like `123` to the specified writer. 224 | /// 225 | /// Integer `value` must be safe for JSON: less than `2.pow(53) - 1` 226 | #[inline] 227 | fn write_u128(&mut self, writer: &mut W, value: u128) -> io::Result<()> 228 | where 229 | W: Write + ?Sized, 230 | { 231 | if !self.stack.is_in_key()? && value > MAX_SAFE_INTEGER_U128 { 232 | Err(Error::new( 233 | ErrorKind::InvalidData, 234 | "u128 must be less than JSON max safe integer", 235 | )) 236 | } else { 237 | CompactFormatter.write_u128(&mut self.stack.scope(writer)?, value) 238 | } 239 | } 240 | 241 | /// Writes a floating point value like `-31.26e+12` to the specified writer. 242 | /// 243 | /// Follows the [ECMAScript number-to-string] algorithm 244 | /// 245 | /// [ECMAScript number-to-string]: https://tc39.es/ecma262/#sec-numeric-types-number-tostring 246 | #[inline] 247 | fn write_f32(&mut self, writer: &mut W, value: f32) -> io::Result<()> 248 | where 249 | W: Write + ?Sized, 250 | { 251 | write_float( 252 | &mut self.stack.scope_with_key(writer)?, 253 | value.classify(), 254 | value, 255 | ) 256 | } 257 | 258 | /// Writes a floating point value like `-31.26e+12` to the specified writer. 259 | /// 260 | /// Follows the [ECMAScript number-to-string] algorithm 261 | /// 262 | /// [ECMAScript number-to-string]: https://tc39.es/ecma262/#sec-numeric-types-number-tostring 263 | #[inline] 264 | fn write_f64(&mut self, writer: &mut W, value: f64) -> io::Result<()> 265 | where 266 | W: Write + ?Sized, 267 | { 268 | write_float( 269 | &mut self.stack.scope_with_key(writer)?, 270 | value.classify(), 271 | value, 272 | ) 273 | } 274 | 275 | /// Writes a number that has already been rendered to a string. 276 | #[inline] 277 | fn write_number_str(&mut self, writer: &mut W, value: &str) -> io::Result<()> 278 | where 279 | W: Write + ?Sized, 280 | { 281 | let bytes = value.as_bytes(); 282 | let mut writer = self.stack.scope_with_key(writer)?; 283 | writer.write_all(bytes)?; 284 | Ok(()) 285 | } 286 | 287 | /// Called before each series of `write_string_fragment` and `write_char_escape`. 288 | /// 289 | /// Writes a `"` to the specified writer. 290 | #[inline] 291 | fn begin_string(&mut self, writer: &mut W) -> io::Result<()> 292 | where 293 | W: Write + ?Sized, 294 | { 295 | CompactFormatter.begin_string(&mut self.stack.scope(writer)?) 296 | } 297 | 298 | /// Called after each series of `write_string_fragment` and `write_char_escape`. 299 | /// 300 | /// Writes a `"` to the specified writer. 301 | #[inline] 302 | fn end_string(&mut self, writer: &mut W) -> io::Result<()> 303 | where 304 | W: Write + ?Sized, 305 | { 306 | CompactFormatter.end_string(&mut self.stack.scope(writer)?) 307 | } 308 | 309 | /// Writes a string fragment that doesn't need any escaping to the specified writer. 310 | #[inline] 311 | fn write_string_fragment(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> 312 | where 313 | W: Write + ?Sized, 314 | { 315 | let bytes = fragment.as_bytes(); 316 | let mut writer = self.stack.scope_with_key(writer)?; 317 | writer.write_all(bytes)?; 318 | Ok(()) 319 | } 320 | 321 | /// Writes a character escape code to the specified writer. 322 | #[inline] 323 | fn write_char_escape(&mut self, writer: &mut W, escape: CharEscape) -> io::Result<()> 324 | where 325 | W: Write + ?Sized, 326 | { 327 | static HEX_CHARS: [u8; 16] = *b"0123456789abcdef"; 328 | 329 | match escape { 330 | CharEscape::Backspace => { 331 | self.stack.key_bytes()?.write_all(&[0x08])?; 332 | self.stack.scope(writer)?.write_all(b"\\b")?; 333 | } 334 | CharEscape::Tab => { 335 | self.stack.key_bytes()?.write_all(&[0x09])?; 336 | self.stack.scope(writer)?.write_all(b"\\t")?; 337 | } 338 | CharEscape::LineFeed => { 339 | self.stack.key_bytes()?.write_all(&[0x0A])?; 340 | self.stack.scope(writer)?.write_all(b"\\n")?; 341 | } 342 | CharEscape::FormFeed => { 343 | self.stack.key_bytes()?.write_all(&[0x0C])?; 344 | self.stack.scope(writer)?.write_all(b"\\f")?; 345 | } 346 | CharEscape::CarriageReturn => { 347 | self.stack.key_bytes()?.write_all(&[0x0D])?; 348 | self.stack.scope(writer)?.write_all(b"\\r")?; 349 | } 350 | CharEscape::Quote => { 351 | self.stack.key_bytes()?.write_all(&[0x22])?; 352 | self.stack.scope(writer)?.write_all(b"\\\"")?; 353 | } 354 | CharEscape::Solidus => { 355 | self.stack.key_bytes()?.write_all(&[0x2F])?; 356 | self.stack.scope(writer)?.write_all(b"\\/")?; 357 | } 358 | CharEscape::ReverseSolidus => { 359 | self.stack.key_bytes()?.write_all(&[0x5C])?; 360 | self.stack.scope(writer)?.write_all(b"\\\\")?; 361 | } 362 | CharEscape::AsciiControl(control) => { 363 | self.stack.key_bytes()?.write_all(&[control])?; 364 | self.stack.scope(writer)?.write_all(&[ 365 | b'\\', 366 | b'u', 367 | b'0', 368 | b'0', 369 | HEX_CHARS[(control >> 4) as usize], 370 | HEX_CHARS[(control & 0xF) as usize], 371 | ])?; 372 | } 373 | } 374 | Ok(()) 375 | } 376 | 377 | /// Called before every array. Writes a `[` to the specified writer. 378 | #[inline] 379 | fn begin_array(&mut self, writer: &mut W) -> io::Result<()> 380 | where 381 | W: Write + ?Sized, 382 | { 383 | CompactFormatter.begin_array(&mut self.stack.scope(writer)?) 384 | } 385 | 386 | /// Called after every array. Writes a `]` to the specified writer. 387 | #[inline] 388 | fn end_array(&mut self, writer: &mut W) -> io::Result<()> 389 | where 390 | W: Write + ?Sized, 391 | { 392 | CompactFormatter.end_array(&mut self.stack.scope(writer)?) 393 | } 394 | 395 | /// Called before every array value. Writes a `,` if needed to the specified writer. 396 | #[inline] 397 | fn begin_array_value(&mut self, writer: &mut W, first: bool) -> io::Result<()> 398 | where 399 | W: Write + ?Sized, 400 | { 401 | CompactFormatter.begin_array_value(&mut self.stack.scope(writer)?, first) 402 | } 403 | 404 | /// Called after every array value. 405 | #[inline] 406 | fn end_array_value(&mut self, writer: &mut W) -> io::Result<()> 407 | where 408 | W: Write + ?Sized, 409 | { 410 | CompactFormatter.end_array_value(&mut self.stack.scope(writer)?) 411 | } 412 | 413 | /// Called before every object. 414 | #[inline] 415 | fn begin_object(&mut self, _writer: &mut W) -> io::Result<()> 416 | where 417 | W: Write + ?Sized, 418 | { 419 | self.stack.start_object(); 420 | Ok(()) 421 | } 422 | 423 | /// Called after every object. 424 | #[inline] 425 | fn end_object(&mut self, writer: &mut W) -> io::Result<()> 426 | where 427 | W: Write + ?Sized, 428 | { 429 | self.stack.end_object(writer) 430 | } 431 | 432 | /// Called before every object key. 433 | #[inline] 434 | fn begin_object_key(&mut self, _writer: &mut W, _first: bool) -> io::Result<()> 435 | where 436 | W: Write + ?Sized, 437 | { 438 | self.stack.start_key() 439 | } 440 | 441 | /// Called after every object key. 442 | #[inline] 443 | fn end_object_key(&mut self, _writer: &mut W) -> io::Result<()> 444 | where 445 | W: Write + ?Sized, 446 | { 447 | self.stack.end_key() 448 | } 449 | 450 | /// Called before every object value. 451 | #[inline] 452 | fn begin_object_value(&mut self, _writer: &mut W) -> io::Result<()> 453 | where 454 | W: Write + ?Sized, 455 | { 456 | Ok(()) 457 | } 458 | 459 | /// Called after every object value. 460 | #[inline] 461 | fn end_object_value(&mut self, _writer: &mut W) -> io::Result<()> 462 | where 463 | W: Write + ?Sized, 464 | { 465 | Ok(()) 466 | } 467 | 468 | /// Writes a raw JSON fragment that doesn't need any escaping to the specified writer. 469 | #[inline] 470 | fn write_raw_fragment(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> 471 | where 472 | W: Write + ?Sized, 473 | { 474 | let bytes = fragment.as_bytes(); 475 | let mut writer = self.stack.scope_with_key(writer)?; 476 | writer.write_all(bytes)?; 477 | Ok(()) 478 | } 479 | } 480 | 481 | fn write_float(writer: &mut W, category: FpCategory, value: F) -> io::Result<()> 482 | where 483 | W: Write + ?Sized, 484 | F: ryu_js::Float, 485 | { 486 | match category { 487 | FpCategory::Nan => Err(Error::new(ErrorKind::InvalidData, "NaN is not allowed.")), 488 | FpCategory::Infinite => Err(Error::new( 489 | ErrorKind::InvalidData, 490 | "Infinity is not allowed.", 491 | )), 492 | FpCategory::Zero => writer.write_all(b"0"), 493 | FpCategory::Normal | FpCategory::Subnormal => { 494 | writer.write_all(ryu_js::Buffer::new().format_finite(value).as_bytes()) 495 | } 496 | } 497 | } 498 | -------------------------------------------------------------------------------- /rust/json-canon/tests/fixtures.rs: -------------------------------------------------------------------------------- 1 | use std::io::Error; 2 | 3 | use json_canon::to_string; 4 | use serde_json::{from_str, Value}; 5 | 6 | #[track_caller] 7 | fn test_data_import(input: &str, expected: &str) -> Result<(), Error> { 8 | let actual = to_string(&from_str::(input.trim())?)?; 9 | assert_eq!(actual, expected.trim()); 10 | Ok(()) 11 | } 12 | 13 | #[test] 14 | fn arrays() -> Result<(), Error> { 15 | test_data_import( 16 | include_str!("../../../test-data/input/arrays.json"), 17 | include_str!("../../../test-data/output/arrays.json"), 18 | )?; 19 | Ok(()) 20 | } 21 | 22 | #[test] 23 | fn french() -> Result<(), Error> { 24 | test_data_import( 25 | include_str!("../../../test-data/input/french.json"), 26 | include_str!("../../../test-data/output/french.json"), 27 | )?; 28 | Ok(()) 29 | } 30 | 31 | #[test] 32 | fn structures() -> Result<(), Error> { 33 | test_data_import( 34 | include_str!("../../../test-data/input/structures.json"), 35 | include_str!("../../../test-data/output/structures.json"), 36 | )?; 37 | Ok(()) 38 | } 39 | 40 | #[test] 41 | fn unicode() -> Result<(), Error> { 42 | test_data_import( 43 | include_str!("../../../test-data/input/unicode.json"), 44 | include_str!("../../../test-data/output/unicode.json"), 45 | )?; 46 | Ok(()) 47 | } 48 | 49 | #[test] 50 | fn values() -> Result<(), Error> { 51 | test_data_import( 52 | include_str!("../../../test-data/input/values.json"), 53 | include_str!("../../../test-data/output/values.json"), 54 | )?; 55 | Ok(()) 56 | } 57 | 58 | #[test] 59 | fn weird() -> Result<(), Error> { 60 | test_data_import( 61 | include_str!("../../../test-data/input/weird.json"), 62 | include_str!("../../../test-data/output/weird.json"), 63 | )?; 64 | Ok(()) 65 | } 66 | 67 | #[test] 68 | fn fuzzy_1() -> Result<(), Error> { 69 | test_data_import( 70 | include_str!("../../../test-data/fuzzies/1.json"), 71 | include_str!("../../../test-data/fuzzies/1.json"), 72 | )?; 73 | Ok(()) 74 | } 75 | -------------------------------------------------------------------------------- /rust/json-canon/tests/json.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | env::current_dir, 3 | fs::File, 4 | io::{self, BufRead, BufReader}, 5 | path::Path, 6 | process::{Command, Stdio}, 7 | }; 8 | 9 | use json_canon::to_string; 10 | use serde_json::{from_str, Value}; 11 | 12 | #[test] 13 | fn test_json_data_from_file() -> Result<(), io::Error> { 14 | let test_data_path = current_dir()?.join(Path::new("../../test-data/generated/json.txt")); 15 | 16 | // only run test if generated file exists 17 | if !test_data_path.exists() { 18 | return Ok(()); 19 | } 20 | 21 | let file = File::open(test_data_path)?; 22 | let reader = BufReader::new(file); 23 | for line_result in reader.lines() { 24 | let line = line_result?; 25 | let expected = line.trim(); 26 | let value = from_str(&line)?; 27 | test_json(&value, expected); 28 | } 29 | 30 | Ok(()) 31 | } 32 | 33 | #[test] 34 | fn test_json_data_from_command() -> Result<(), io::Error> { 35 | let test_command_path = current_dir()?.join(Path::new("../../js/json-canon-fuzz/src/bin")); 36 | 37 | let mut child = Command::new("node") 38 | .arg(test_command_path) 39 | .arg("json") 40 | .arg("100000") 41 | .stdout(Stdio::piped()) 42 | .spawn() 43 | .expect("Failed to execute command"); 44 | 45 | let stdout = child.stdout.as_mut().expect("Failed to open stdout"); 46 | let reader = io::BufReader::new(stdout); 47 | 48 | for line_result in reader.lines() { 49 | let line = line_result?; 50 | let expected = line.trim(); 51 | let value = from_str(&line)?; 52 | test_json(&value, expected); 53 | } 54 | 55 | let ecode = child.wait()?; 56 | assert!(ecode.success()); 57 | 58 | Ok(()) 59 | } 60 | 61 | #[track_caller] 62 | fn test_json(value: &Value, expected: &str) { 63 | let actual = to_string(value).unwrap(); 64 | assert_eq!(actual, expected); 65 | } 66 | -------------------------------------------------------------------------------- /rust/json-canon/tests/numbers.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | env::current_dir, 3 | fs::File, 4 | io::{self, BufRead, BufReader}, 5 | path::Path, 6 | process::{Command, Stdio}, 7 | str, 8 | }; 9 | 10 | use json_canon::to_string; 11 | 12 | #[test] 13 | fn test_numbers() { 14 | // fn test_json_number_err(bits: u64) { 15 | // assert!(to_string(&f64::from_bits(bits)).is_err()); 16 | // } 17 | 18 | test_json_number(0x0000000000000000, "0"); // Zero 19 | test_json_number(0x8000000000000000, "0"); // Minus zero 20 | test_json_number(0x0000000000000001, "5e-324"); // Min pos number 21 | test_json_number(0x8000000000000001, "-5e-324"); // Min neg number 22 | test_json_number(0x7fefffffffffffff, "1.7976931348623157e+308"); // Max pos number 23 | test_json_number(0xffefffffffffffff, "-1.7976931348623157e+308"); // Max neg number 24 | test_json_number(0x4340000000000000, "9007199254740992"); // Max pos int 25 | test_json_number(0xc340000000000000, "-9007199254740992"); // Max neg int 26 | test_json_number(0x4430000000000000, "295147905179352830000"); // ~2**68 27 | 28 | // TODO: Custom Serializer... 29 | // test_json_number_err(0x7fffffffffffffff); // NaN 30 | // test_json_number_err(0x7ff0000000000000); // Infinity 31 | 32 | test_json_number(0x44b52d02c7e14af5, "9.999999999999997e+22"); 33 | test_json_number(0x44b52d02c7e14af6, "1e+23"); 34 | test_json_number(0x44b52d02c7e14af7, "1.0000000000000001e+23"); 35 | test_json_number(0x444b1ae4d6e2ef4e, "999999999999999700000"); 36 | test_json_number(0x444b1ae4d6e2ef4f, "999999999999999900000"); 37 | test_json_number(0x444b1ae4d6e2ef50, "1e+21"); 38 | test_json_number(0x3eb0c6f7a0b5ed8c, "9.999999999999997e-7"); 39 | test_json_number(0x3eb0c6f7a0b5ed8d, "0.000001"); 40 | test_json_number(0x41b3de4355555553, "333333333.3333332"); 41 | test_json_number(0x41b3de4355555554, "333333333.33333325"); 42 | test_json_number(0x41b3de4355555555, "333333333.3333333"); 43 | test_json_number(0x41b3de4355555556, "333333333.3333334"); 44 | test_json_number(0x41b3de4355555557, "333333333.33333343"); 45 | test_json_number(0xbecbf647612f3696, "-0.0000033333333333333333"); 46 | test_json_number(0x43143ff3c1cb0959, "1424953923781206.2"); // Round to even 47 | } 48 | 49 | #[test] 50 | fn test_valid_integers() -> io::Result<()> { 51 | macro_rules! test_valid_integers { 52 | ($($i:expr => $o:expr),+) => { 53 | { 54 | $( 55 | let actual = to_string(&$i)?; 56 | assert_eq!(actual, $o); 57 | )+ 58 | } 59 | }; 60 | } 61 | 62 | test_valid_integers![ 63 | 0_u8 => "0", 64 | 0_i8 => "0", 65 | -0_i8 => "0", 66 | 0_i128 => "0", 67 | -0_i128 => "0", 68 | 1_u8 => "1", 69 | 2_u16 => "2", 70 | 4_u32 => "4", 71 | 8_u64 => "8", 72 | 16_u128 => "16", 73 | 32_i8 => "32", 74 | 64_i16 => "64", 75 | 128_i32 => "128", 76 | 256_i64 => "256", 77 | 512_i128 => "512", 78 | -1024_i64 => "-1024", 79 | -2048_i32 => "-2048", 80 | -4096_i16 => "-4096", 81 | -2_i8 => "-2" 82 | ]; 83 | 84 | Ok(()) 85 | } 86 | 87 | #[test] 88 | fn test_invalid_integers() -> io::Result<()> { 89 | macro_rules! test_invalid_integers { 90 | ($($i:expr => $o:expr),+) => { 91 | { 92 | $( 93 | let result = to_string(&$i); 94 | assert!(result.is_err()); 95 | let err = result.unwrap_err(); 96 | assert_eq!(err.to_string(), $o); 97 | )+ 98 | } 99 | }; 100 | } 101 | 102 | test_invalid_integers![ 103 | // 2.pow(60) 104 | 1152921504606846976_u64 => "u64 must be less than JSON max safe integer", 105 | 1152921504606846976_u128 => "u128 must be less than JSON max safe integer", 106 | 1152921504606846976_i64 => "i64.abs() must be less than JSON max safe integer", 107 | 1152921504606846976_i128 => "i128.abs() must be less than JSON max safe integer", 108 | -1152921504606846976_i64 => "i64.abs() must be less than JSON max safe integer", 109 | -1152921504606846976_i128 => "i128.abs() must be less than JSON max safe integer" 110 | ]; 111 | 112 | Ok(()) 113 | } 114 | 115 | #[test] 116 | fn test_number_data_from_file() -> Result<(), io::Error> { 117 | let test_data_path = current_dir()?.join(Path::new("../../test-data/generated/numbers.txt")); 118 | 119 | // only run test if generated file exists 120 | if !test_data_path.exists() { 121 | return Ok(()); 122 | } 123 | 124 | let file = File::open(test_data_path)?; 125 | let reader = BufReader::new(file); 126 | for line_result in reader.lines() { 127 | let line = line_result?; 128 | let mut split = line.split(','); 129 | let bits_str = split.next().ok_or(io::Error::new( 130 | io::ErrorKind::InvalidData, 131 | "Test data: `bits` not found", 132 | ))?; 133 | let bits = u64::from_str_radix(bits_str, 16).map_err(|_| { 134 | io::Error::new( 135 | io::ErrorKind::InvalidData, 136 | "Test data: `bits` not parseable to u64", 137 | ) 138 | })?; 139 | let expected = split.next().ok_or(io::Error::new( 140 | io::ErrorKind::InvalidData, 141 | "Test data: `expected` not found", 142 | ))?; 143 | assert_eq!(split.next(), None); 144 | test_json_number(bits, expected); 145 | } 146 | 147 | Ok(()) 148 | } 149 | 150 | #[test] 151 | fn test_data_from_command() -> Result<(), io::Error> { 152 | let test_command_path = current_dir()?.join(Path::new("../../js/json-canon-fuzz/src/bin")); 153 | 154 | let mut child = Command::new("node") 155 | .arg(test_command_path) 156 | .arg("numbers") 157 | .arg("100000") 158 | .stdout(Stdio::piped()) 159 | .spawn() 160 | .expect("Failed to execute command"); 161 | 162 | let stdout = child.stdout.as_mut().expect("Failed to open stdout"); 163 | let reader = io::BufReader::new(stdout); 164 | 165 | for line_result in reader.lines() { 166 | let line = line_result?; 167 | 168 | let mut split = line.split(','); 169 | let bits_str = split.next().ok_or(io::Error::new( 170 | io::ErrorKind::InvalidData, 171 | "Test data: `bits` not found", 172 | ))?; 173 | let bits = u64::from_str_radix(bits_str, 16).map_err(|_| { 174 | io::Error::new( 175 | io::ErrorKind::InvalidData, 176 | "Test data: `bits` not parseable to u64", 177 | ) 178 | })?; 179 | let expected = split.next().ok_or(io::Error::new( 180 | io::ErrorKind::InvalidData, 181 | "Test data: `expected` not found", 182 | ))?; 183 | assert_eq!(split.next(), None); 184 | 185 | test_json_number(bits, expected); 186 | } 187 | 188 | let ecode = child.wait()?; 189 | assert!(ecode.success()); 190 | 191 | Ok(()) 192 | } 193 | 194 | #[track_caller] 195 | fn test_json_number(bits: u64, expected: &str) { 196 | assert_eq!(to_string(&f64::from_bits(bits)).unwrap(), expected); 197 | } 198 | -------------------------------------------------------------------------------- /rust/json-canon/tests/units.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::BTreeMap, fmt::Debug, io}; 2 | 3 | use json_canon::to_string; 4 | use serde::Serialize; 5 | use serde_json::{from_str, json, Value}; 6 | 7 | macro_rules! treemap { 8 | () => { 9 | BTreeMap::new() 10 | }; 11 | ($($k:expr => $v:expr),+) => { 12 | { 13 | let mut m = BTreeMap::new(); 14 | $( 15 | m.insert($k, $v); 16 | )+ 17 | m 18 | } 19 | }; 20 | } 21 | 22 | fn test_ok(expected: Expected, input: Input) -> io::Result<()> 23 | where 24 | Expected: AsRef + Debug, 25 | Input: Serialize, 26 | String: PartialEq, 27 | { 28 | let actual = to_string(&input)?; 29 | assert_eq!(actual, expected); 30 | Ok(()) 31 | } 32 | 33 | fn test_err(expected: ExpectedErr, input: Input) -> io::Result<()> 34 | where 35 | ExpectedErr: AsRef + Debug, 36 | Input: Serialize, 37 | String: PartialEq, 38 | { 39 | let result = to_string(&input); 40 | assert!(result.is_err()); 41 | let err = result.unwrap_err(); 42 | assert_eq!(err.to_string(), expected); 43 | Ok(()) 44 | } 45 | 46 | #[test] 47 | fn test_works() -> io::Result<()> { 48 | let expected = r#"{"a":1,"b":[],"c":2}"#; 49 | let input = &from_str::(r#"{"c": 2, "a": 1, "b": []}"#)?; 50 | test_ok(expected, input) 51 | } 52 | 53 | #[test] 54 | fn test_null() -> io::Result<()> { 55 | let expected = "null"; 56 | let input_json = json!(None::<()>); 57 | let input_rs = None::<()>; 58 | test_ok(expected, input_json)?; 59 | test_ok(expected, input_rs)?; 60 | Ok(()) 61 | } 62 | 63 | #[test] 64 | fn test_encode_special_utf_ascii() -> io::Result<()> { 65 | let expected = r#""\n""#; 66 | let input_json = json!("\u{000a}"); 67 | let input_rs = "\u{000a}"; 68 | test_ok(expected, input_json)?; 69 | test_ok(expected, input_rs)?; 70 | Ok(()) 71 | } 72 | 73 | #[test] 74 | fn test_empty_array() -> io::Result<()> { 75 | let expected = "[]"; 76 | let input_json = json!([]); 77 | let input_rs: Vec<()> = vec![]; 78 | test_ok(expected, input_json)?; 79 | test_ok(expected, input_rs)?; 80 | Ok(()) 81 | } 82 | 83 | #[test] 84 | fn test_one_element_array() -> io::Result<()> { 85 | let expected = "[123]"; 86 | let input_json = json!([123]); 87 | let input_rs = vec![123]; 88 | test_ok(expected, input_json)?; 89 | test_ok(expected, input_rs)?; 90 | Ok(()) 91 | } 92 | 93 | #[test] 94 | fn test_multi_element_array() -> io::Result<()> { 95 | let expected = "[123,456]"; 96 | let input_json = json!([123, 456]); 97 | let input_rs = vec![123, 456]; 98 | test_ok(expected, input_json)?; 99 | test_ok(expected, input_rs)?; 100 | Ok(()) 101 | } 102 | 103 | #[test] 104 | fn test_multi_element_mixed_array() -> io::Result<()> { 105 | #[derive(serde_derive::Serialize)] 106 | #[serde(untagged)] 107 | enum Val<'a> { 108 | Str(&'a str), 109 | Num(u32), 110 | } 111 | let expected = r#"[123,456,"hello"]"#; 112 | let input_json = json!([123, 456, "hello"]); 113 | let input_rs = vec![Val::Num(123), Val::Num(456), Val::Str("hello")]; 114 | test_ok(expected, input_json)?; 115 | test_ok(expected, input_rs)?; 116 | Ok(()) 117 | } 118 | 119 | #[test] 120 | fn test_none_values_in_array() -> io::Result<()> { 121 | let expected = r#"[null,"hello"]"#; 122 | let input_json = json!([None::<()>, "hello"]); 123 | let input_rs: Vec> = vec![None, Some("hello")]; 124 | test_ok(expected, input_json)?; 125 | test_ok(expected, input_rs)?; 126 | Ok(()) 127 | } 128 | 129 | #[test] 130 | fn test_array_with_large_integer_values() -> io::Result<()> { 131 | // test numbers are 132 | // larger than JavaScript's Number.MAX_SAFE_INTEGER 133 | // and less than i64::MAX 134 | macro_rules! create_input_rs { 135 | () => { 136 | vec![ 137 | // 2.pow(60) 138 | 1152921504606846976, 139 | // 2.pow(61) 140 | 2305843009213693952, 141 | // 2.pow(62) 142 | 4611686018427387904, 143 | ] 144 | }; 145 | } 146 | let input_rs_u64: Vec = create_input_rs!(); 147 | let input_rs_u128: Vec = create_input_rs!(); 148 | let input_rs_i64: Vec = create_input_rs!(); 149 | let input_rs_i128: Vec = create_input_rs!(); 150 | test_err("u64 must be less than JSON max safe integer", input_rs_u64)?; 151 | test_err( 152 | "u128 must be less than JSON max safe integer", 153 | input_rs_u128, 154 | )?; 155 | test_err( 156 | "i64.abs() must be less than JSON max safe integer", 157 | input_rs_i64, 158 | )?; 159 | test_err( 160 | "i128.abs() must be less than JSON max safe integer", 161 | input_rs_i128, 162 | )?; 163 | Ok(()) 164 | } 165 | 166 | /* 167 | 168 | NaN and Infinity are not possible because 169 | 170 | ``` 171 | let input = Value::Number(Number::from_f64(f64::NAN)); 172 | ``` 173 | 174 | is not possible. 175 | 176 | `serde_json::Number::from_f64` returns None on NaN or Infinity. 177 | 178 | */ 179 | 180 | #[test] 181 | fn test_object_in_array() -> io::Result<()> { 182 | #[derive(serde_derive::Serialize)] 183 | #[serde(untagged)] 184 | enum Val<'a> { 185 | Str(&'a str), 186 | Num(u32), 187 | } 188 | let expected = r#"[{"a":"string","b":123}]"#; 189 | let input_json = json!([{ "b": 123, "a": "string" }]); 190 | let input_rs = vec![treemap![ 191 | "b".to_string() => Val::Num(123), 192 | "a".to_string() => Val::Str("string") 193 | ]]; 194 | test_ok(expected, input_json)?; 195 | test_ok(expected, input_rs)?; 196 | Ok(()) 197 | } 198 | 199 | #[test] 200 | fn test_empty_object() -> io::Result<()> { 201 | let expected = r#"{}"#; 202 | let input_json = json!({}); 203 | let input_rs: BTreeMap<(), ()> = treemap![]; 204 | test_ok(expected, input_json)?; 205 | test_ok(expected, input_rs)?; 206 | Ok(()) 207 | } 208 | 209 | // Undefined is also not possible because `serde_json` has no such thing. 210 | 211 | #[test] 212 | fn test_object_with_null_value() -> io::Result<()> { 213 | let expected = r#"{"test":null}"#; 214 | let input_json = json!({ "test": None::<()> }); 215 | let input_rs: BTreeMap<&str, Option<&str>> = treemap![ 216 | "test" => None 217 | ]; 218 | test_ok(expected, input_json)?; 219 | test_ok(expected, input_rs)?; 220 | Ok(()) 221 | } 222 | 223 | #[test] 224 | fn test_object_with_one_property() -> io::Result<()> { 225 | let expected = r#"{"hello":"world"}"#; 226 | let input_json = json!({ "hello": "world" }); 227 | let input_rs = treemap![ 228 | "hello" => "world" 229 | ]; 230 | test_ok(expected, input_json)?; 231 | test_ok(expected, input_rs)?; 232 | Ok(()) 233 | } 234 | 235 | #[test] 236 | fn test_object_with_more_than_one_property() -> io::Result<()> { 237 | let expected = r#"{"goodbye":"test","hello":"world"}"#; 238 | let input_json = json!({ "hello": "world", "goodbye": "test" }); 239 | let input_rs = treemap![ 240 | "hello" => "world", 241 | "goodbye" => "test" 242 | ]; 243 | test_ok(expected, input_json)?; 244 | test_ok(expected, input_rs)?; 245 | Ok(()) 246 | } 247 | 248 | #[test] 249 | fn test_mixed_object_with_more_than_one_property() -> io::Result<()> { 250 | #[derive(serde_derive::Serialize)] 251 | #[serde(untagged)] 252 | enum Val<'a> { 253 | Str(&'a str), 254 | Num(u32), 255 | } 256 | let expected = r#"{"hello":"world","number":123}"#; 257 | let input_json = json!({ "hello": "world", "number": 123 }); 258 | let input_rs = treemap![ 259 | "hello" => Val::Str("world"), 260 | "number" => Val::Num(123) 261 | ]; 262 | test_ok(expected, input_json)?; 263 | test_ok(expected, input_rs)?; 264 | Ok(()) 265 | } 266 | 267 | #[test] 268 | fn test_object_with_bool_keys() -> io::Result<()> { 269 | let expected_err = "key must be a string"; 270 | let input_rs = treemap![ 271 | true => "True", 272 | false => "False" 273 | ]; 274 | test_err(expected_err, input_rs)?; 275 | Ok(()) 276 | } 277 | 278 | #[test] 279 | fn test_object_with_valid_integer_keys() -> io::Result<()> { 280 | macro_rules! create_input_rs { 281 | () => { 282 | treemap![ 283 | 2 => "Two", 284 | 4 => "Four", 285 | 1 => "One", 286 | 3 => "Three" 287 | ] 288 | }; 289 | } 290 | let expected = r#"{"1":"One","2":"Two","3":"Three","4":"Four"}"#; 291 | let input_json = json!({ 292 | "2": "Two", 293 | "4": "Four", 294 | "1": "One", 295 | "3": "Three" 296 | }); 297 | let input_rs_u8: BTreeMap = create_input_rs!(); 298 | let input_rs_u16: BTreeMap = create_input_rs!(); 299 | let input_rs_u32: BTreeMap = create_input_rs!(); 300 | let input_rs_u64: BTreeMap = create_input_rs!(); 301 | let input_rs_u128: BTreeMap = create_input_rs!(); 302 | let input_rs_i8: BTreeMap = create_input_rs!(); 303 | let input_rs_i16: BTreeMap = create_input_rs!(); 304 | let input_rs_i32: BTreeMap = create_input_rs!(); 305 | let input_rs_i64: BTreeMap = create_input_rs!(); 306 | let input_rs_i128: BTreeMap = create_input_rs!(); 307 | test_ok(expected, input_json)?; 308 | test_ok(expected, input_rs_u8)?; 309 | test_ok(expected, input_rs_u16)?; 310 | test_ok(expected, input_rs_u32)?; 311 | test_ok(expected, input_rs_u64)?; 312 | test_ok(expected, input_rs_u128)?; 313 | test_ok(expected, input_rs_i8)?; 314 | test_ok(expected, input_rs_i16)?; 315 | test_ok(expected, input_rs_i32)?; 316 | test_ok(expected, input_rs_i64)?; 317 | test_ok(expected, input_rs_i128)?; 318 | Ok(()) 319 | } 320 | 321 | #[test] 322 | fn test_object_with_large_integer_keys() -> io::Result<()> { 323 | // test numbers are 324 | // larger than JavaScript's Number.MAX_SAFE_INTEGER 325 | // and less than i64::MAX 326 | macro_rules! create_input_rs { 327 | () => { 328 | treemap![ 329 | 9_100_000_000_000_000 => "OKAYY", 330 | 9_000_000_000_000_000 => "WOWZA", 331 | 9_200_000_000_000_000 => "YIPES" 332 | ] 333 | }; 334 | } 335 | let expected = 336 | r#"{"9000000000000000":"WOWZA","9100000000000000":"OKAYY","9200000000000000":"YIPES"}"#; 337 | let input_json = json!({ 338 | "9100000000000000": "OKAYY", 339 | "9000000000000000": "WOWZA", 340 | "9200000000000000": "YIPES" 341 | }); 342 | let input_rs_u64: BTreeMap = create_input_rs!(); 343 | let input_rs_u128: BTreeMap = create_input_rs!(); 344 | let input_rs_i64: BTreeMap = create_input_rs!(); 345 | let input_rs_i128: BTreeMap = create_input_rs!(); 346 | test_ok(expected, input_json)?; 347 | test_ok(expected, input_rs_u64)?; 348 | test_ok(expected, input_rs_u128)?; 349 | test_ok(expected, input_rs_i64)?; 350 | test_ok(expected, input_rs_i128)?; 351 | Ok(()) 352 | } 353 | 354 | #[test] 355 | fn test_object_with_unit_variant_keys() -> io::Result<()> { 356 | let expected = r#"{"One":"One","Three":"Three","Two":"Two"}"#; 357 | #[derive(PartialEq, Eq, PartialOrd, Ord, serde_derive::Serialize)] 358 | enum Key { 359 | One, 360 | Two, 361 | Three, 362 | } 363 | let input_rs = treemap![ 364 | Key::One => "One", 365 | Key::Two => "Two", 366 | Key::Three => "Three" 367 | ]; 368 | test_ok(expected, input_rs)?; 369 | Ok(()) 370 | } 371 | 372 | #[test] 373 | fn test_object_with_newtype_keys() -> io::Result<()> { 374 | let expected = r#"{"One":"One","Three":"Three","Two":"Two"}"#; 375 | #[derive(PartialEq, Eq, PartialOrd, Ord, serde_derive::Serialize)] 376 | struct Key<'a>(&'a str); 377 | let input_rs = treemap![ 378 | Key("One") => "One", 379 | Key("Two") => "Two", 380 | Key("Three") => "Three" 381 | ]; 382 | test_ok(expected, input_rs)?; 383 | Ok(()) 384 | } 385 | 386 | #[test] 387 | fn test_object_with_char_keys() -> io::Result<()> { 388 | let expected = r#"{"1":"One","2":"Two","3":"Three"}"#; 389 | let input_rs = treemap![ 390 | '1' => "One", 391 | '3' => "Three", 392 | '2' => "Two" 393 | ]; 394 | test_ok(expected, input_rs)?; 395 | Ok(()) 396 | } 397 | 398 | #[test] 399 | fn test_object_with_unit_keys() -> io::Result<()> { 400 | let expected_err = "key must be a string"; 401 | let input_rs = treemap![ 402 | () => "One", 403 | () => "Two", 404 | () => "Three" 405 | ]; 406 | test_err(expected_err, input_rs)?; 407 | Ok(()) 408 | } 409 | 410 | #[test] 411 | fn test_object_with_some_keys() -> io::Result<()> { 412 | let expected_err = "key must be a string"; 413 | let input_rs = treemap![ 414 | Some("One") => "One", 415 | Some("Two") => "Two", 416 | Some("Three") => "Three" 417 | ]; 418 | test_err(expected_err, input_rs)?; 419 | Ok(()) 420 | } 421 | 422 | #[test] 423 | fn test_object_with_none_keys() -> io::Result<()> { 424 | let expected_err = "key must be a string"; 425 | let input_rs = treemap![ 426 | None::<&str> => "One", 427 | None::<&str> => "Two", 428 | None::<&str> => "Three" 429 | ]; 430 | test_err(expected_err, input_rs)?; 431 | Ok(()) 432 | } 433 | 434 | #[test] 435 | fn test_object_with_struct_keys() -> io::Result<()> { 436 | let expected_err = "key must be a string"; 437 | #[derive(PartialEq, Eq, PartialOrd, Ord, serde_derive::Serialize)] 438 | struct Key<'a> { 439 | name: &'a str, 440 | } 441 | let input_rs = treemap![ 442 | Key { name: "One" } => "One", 443 | Key { name: "Two" } => "Two", 444 | Key { name: "Three" } => "Three" 445 | ]; 446 | test_err(expected_err, input_rs)?; 447 | Ok(()) 448 | } 449 | 450 | #[test] 451 | fn test_object_with_utf_keys() -> io::Result<()> { 452 | let expected = r#"{"\n":"Newline","1":"One"}"#; 453 | let input_json = json!({ 454 | "1": "One", 455 | "\u{000a}": "Newline", 456 | }); 457 | let input_rs = treemap![ 458 | "1" => "One", 459 | "\u{000a}" => "Newline" 460 | ]; 461 | test_ok(expected, input_json)?; 462 | test_ok(expected, input_rs)?; 463 | Ok(()) 464 | } 465 | 466 | #[test] 467 | fn test_object_with_wacky_keys() -> io::Result<()> { 468 | #[derive(PartialEq, Eq, PartialOrd, Ord, serde_derive::Serialize)] 469 | #[serde(untagged)] 470 | enum Key<'a> { 471 | Str(&'a str), 472 | Num(u32), 473 | } 474 | let expected = r#"{"\n":"Newline","1":"One","2":"Two","3":"Three","4":"Four"}"#; 475 | let input_json = json!({ 476 | "2": "Two", 477 | "4": "Four", 478 | "1": "One", 479 | "3": "Three", 480 | "\u{000a}": "Newline", 481 | }); 482 | let input_rs = treemap![ 483 | Key::Num(2) => "Two", 484 | Key::Str("4") => "Four", 485 | Key::Str("1") => "One", 486 | Key::Num(3) => "Three", 487 | Key::Str("\u{000a}") => "Newline" 488 | ]; 489 | test_ok(expected, input_json)?; 490 | test_ok(expected, input_rs)?; 491 | Ok(()) 492 | } 493 | 494 | #[test] 495 | fn test_bug_utf8_sort() -> io::Result<()> { 496 | let input = r###"{"�\u0017B��":null,"�\u0017\\�4�":null}"###; 497 | let input_val: Value = from_str(input)?; 498 | let expected = input.to_string(); 499 | let actual = to_string(&input_val)?; 500 | assert_eq!(actual, expected); 501 | Ok(()) 502 | } 503 | -------------------------------------------------------------------------------- /test-data/README.md: -------------------------------------------------------------------------------- 1 | ## Test Data 2 | 3 | The [input](input) directory contains files with non-canonicalized data which is 4 | supposed be transformed as specified by the corresponding file in the 5 | [output](output) directory. 6 | 7 | ## ES6 Numbers 8 | 9 | For testing ES6 number serialization there is a GZIP file hosted at 10 | https://github.com/cyberphone/json-canonicalization/releases/download/es6testfile/es6testfile100m.txt.gz 11 | containing a test vector of 100 million of random and edge-case values. 12 | The test file consists of lines 13 | ```code 14 | hex-ieee,expected\n 15 | ``` 16 | where `hex-ieee` holds 1-16 ASCII hexadecimal characters 17 | representing an IEEE-754 double precision value 18 | while `expected` holds the expected serialized value. 19 | Each line is terminated by a single new-line character. 20 | 21 | Sample lines: 22 | ```code 23 | 4340000000000001,9007199254740994 24 | 4340000000000002,9007199254740996 25 | 444b1ae4d6e2ef50,1e+21 26 | 3eb0c6f7a0b5ed8d,0.000001 27 | 3eb0c6f7a0b5ed8c,9.999999999999997e-7 28 | 8000000000000000,0 29 | 0,0 30 | ``` 31 | 32 | The sequence of IEEE-754 double precision values is deterministically generated 33 | according to the following algorithm: 34 | ```js 35 | const crypto = require("crypto") 36 | 37 | staticU64s = new BigUint64Array([ 38 | 0x0000000000000000n, 0x8000000000000000n, 0x0000000000000001n, 0x8000000000000001n, 39 | 0xc46696695dbd1cc3n, 0xc43211ede4974a35n, 0xc3fce97ca0f21056n, 0xc3c7213080c1a6acn, 40 | 0xc39280f39a348556n, 0xc35d9b1f5d20d557n, 0xc327af4c4a80aaacn, 0xc2f2f2a36ecd5556n, 41 | 0xc2be51057e155558n, 0xc28840d131aaaaacn, 0xc253670dc1555557n, 0xc21f0b4935555557n, 42 | 0xc1e8d5d42aaaaaacn, 0xc1b3de4355555556n, 0xc17fca0555555556n, 0xc1496e6aaaaaaaabn, 43 | 0xc114585555555555n, 0xc0e046aaaaaaaaabn, 0xc0aa0aaaaaaaaaaan, 0xc074d55555555555n, 44 | 0xc040aaaaaaaaaaabn, 0xc00aaaaaaaaaaaabn, 0xbfd5555555555555n, 0xbfa1111111111111n, 45 | 0xbf6b4e81b4e81b4fn, 0xbf35d867c3ece2a5n, 0xbf0179ec9cbd821en, 0xbecbf647612f3696n, 46 | 0xbe965e9f80f29212n, 0xbe61e54c672874dbn, 0xbe2ca213d840baf8n, 0xbdf6e80fe033c8c6n, 47 | 0xbdc2533fe68fd3d2n, 0xbd8d51ffd74c861cn, 0xbd5774ccac3d3817n, 0xbd22c3d6f030f9acn, 48 | 0xbcee0624b3818f79n, 0xbcb804ea293472c7n, 0xbc833721ba905bd3n, 0xbc4ebe9c5db3c61en, 49 | 0xbc18987d17c304e5n, 0xbbe3ad30dfcf371dn, 0xbbaf7b816618582fn, 0xbb792f9ab81379bfn, 50 | 0xbb442615600f9499n, 0xbb101e77800c76e1n, 0xbad9ca58cce0be35n, 0xbaa4a1e0a3e6fe90n, 51 | 0xba708180831f320dn, 0xba3a68cd9e985016n, 0x446696695dbd1cc3n, 0x443211ede4974a35n, 52 | 0x43fce97ca0f21056n, 0x43c7213080c1a6acn, 0x439280f39a348556n, 0x435d9b1f5d20d557n, 53 | 0x4327af4c4a80aaacn, 0x42f2f2a36ecd5556n, 0x42be51057e155558n, 0x428840d131aaaaacn, 54 | 0x4253670dc1555557n, 0x421f0b4935555557n, 0x41e8d5d42aaaaaacn, 0x41b3de4355555556n, 55 | 0x417fca0555555556n, 0x41496e6aaaaaaaabn, 0x4114585555555555n, 0x40e046aaaaaaaaabn, 56 | 0x40aa0aaaaaaaaaaan, 0x4074d55555555555n, 0x4040aaaaaaaaaaabn, 0x400aaaaaaaaaaaabn, 57 | 0x3fd5555555555555n, 0x3fa1111111111111n, 0x3f6b4e81b4e81b4fn, 0x3f35d867c3ece2a5n, 58 | 0x3f0179ec9cbd821en, 0x3ecbf647612f3696n, 0x3e965e9f80f29212n, 0x3e61e54c672874dbn, 59 | 0x3e2ca213d840baf8n, 0x3df6e80fe033c8c6n, 0x3dc2533fe68fd3d2n, 0x3d8d51ffd74c861cn, 60 | 0x3d5774ccac3d3817n, 0x3d22c3d6f030f9acn, 0x3cee0624b3818f79n, 0x3cb804ea293472c7n, 61 | 0x3c833721ba905bd3n, 0x3c4ebe9c5db3c61en, 0x3c18987d17c304e5n, 0x3be3ad30dfcf371dn, 62 | 0x3baf7b816618582fn, 0x3b792f9ab81379bfn, 0x3b442615600f9499n, 0x3b101e77800c76e1n, 63 | 0x3ad9ca58cce0be35n, 0x3aa4a1e0a3e6fe90n, 0x3a708180831f320dn, 0x3a3a68cd9e985016n, 64 | 0x4024000000000000n, 0x4014000000000000n, 0x3fe0000000000000n, 0x3fa999999999999an, 65 | 0x3f747ae147ae147bn, 0x3f40624dd2f1a9fcn, 0x3f0a36e2eb1c432dn, 0x3ed4f8b588e368f1n, 66 | 0x3ea0c6f7a0b5ed8dn, 0x3e6ad7f29abcaf48n, 0x3e35798ee2308c3an, 0x3ed539223589fa95n, 67 | 0x3ed4ff26cd5a7781n, 0x3ed4f95a762283ffn, 0x3ed4f8c60703520cn, 0x3ed4f8b72f19cd0dn, 68 | 0x3ed4f8b5b31c0c8dn, 0x3ed4f8b58d1c461an, 0x3ed4f8b5894f7f0en, 0x3ed4f8b588ee37f3n, 69 | 0x3ed4f8b588e47da4n, 0x3ed4f8b588e3849cn, 0x3ed4f8b588e36bb5n, 0x3ed4f8b588e36937n, 70 | 0x3ed4f8b588e368f8n, 0x3ed4f8b588e368f1n, 0x3ff0000000000000n, 0xbff0000000000000n, 71 | 0xbfeffffffffffffan, 0xbfeffffffffffffbn, 0x3feffffffffffffan, 0x3feffffffffffffbn, 72 | 0x3feffffffffffffcn, 0x3feffffffffffffen, 0xbfefffffffffffffn, 0xbfefffffffffffffn, 73 | 0x3fefffffffffffffn, 0x3fefffffffffffffn, 0x3fd3333333333332n, 0x3fd3333333333333n, 74 | 0x3fd3333333333334n, 0x0010000000000000n, 0x000ffffffffffffdn, 0x000fffffffffffffn, 75 | 0x7fefffffffffffffn, 0xffefffffffffffffn, 0x4340000000000000n, 0xc340000000000000n, 76 | 0x4430000000000000n, 0x44b52d02c7e14af5n, 0x44b52d02c7e14af6n, 0x44b52d02c7e14af7n, 77 | 0x444b1ae4d6e2ef4en, 0x444b1ae4d6e2ef4fn, 0x444b1ae4d6e2ef50n, 0x3eb0c6f7a0b5ed8cn, 78 | 0x3eb0c6f7a0b5ed8dn, 0x41b3de4355555553n, 0x41b3de4355555554n, 0x41b3de4355555555n, 79 | 0x41b3de4355555556n, 0x41b3de4355555557n, 0xbecbf647612f3696n, 0x43143ff3c1cb0959n, 80 | ]) 81 | staticF64s = new Float64Array(staticU64s.buffer) 82 | serialU64s = new BigUint64Array(2000) 83 | for (i = 0; i < 2000; i++) { 84 | serialU64s[i] = 0x0010000000000000n + BigInt(i) 85 | } 86 | serialF64s = new Float64Array(serialU64s.buffer) 87 | 88 | var state = { 89 | idx: 0, 90 | data: new Float64Array(), 91 | block: new ArrayBuffer(32), 92 | } 93 | while (true) { 94 | // Generate the next IEEE-754 value in the sequence. 95 | var f = 0.0; 96 | if (state.idx < staticF64s.length) { 97 | f = staticF64s[state.idx] 98 | } else if (state.idx < staticF64s.length + serialF64s.length) { 99 | f = serialF64s[state.idx - staticF64s.length] 100 | } else { 101 | while (f == 0.0 || !isFinite(f)) { 102 | if (state.data.length == 0) { 103 | state.block = crypto.createHash("sha256").update(new Buffer(state.block)).digest().buffer 104 | state.data = new Float64Array(state.block) 105 | } 106 | f = state.data[0] 107 | state.data = state.data.slice(1) 108 | } 109 | } 110 | state.idx++ 111 | 112 | // Print the raw IEEE-754 value as hexadecimal. 113 | var u64 = new BigUint64Array(1) 114 | var f64 = new Float64Array(u64.buffer) 115 | f64[0] = f 116 | console.log(u64[0].toString(16)) 117 | } 118 | ``` 119 | Deterministic generation of the test inputs allows an implementation to verify 120 | correctness of ES6 number formatting without requiring any network bandwidth by 121 | generating the test file locally and computing its hash. 122 | 123 | The following table records the expected hashes: 124 | | SHA-256 checksum | Number of lines | Size in bytes | 125 | | ---------------------------------------------------------------- | --------------- | ------------- | 126 | | be18b62b6f69cdab33a7e0dae0d9cfa869fda80ddc712221570f9f40a5878687 | 1000 | 37967 | 127 | | b9f7a8e75ef22a835685a52ccba7f7d6bdc99e34b010992cbc5864cd12be6892 | 10000 | 399022 | 128 | | 22776e6d4b49fa294a0d0f349268e5c28808fe7e0cb2bcbe28f63894e494d4c7 | 100000 | 4031728 | 129 | | 49415fee2c56c77864931bd3624faad425c3c577d6d74e89a83bc725506dad16 | 1000000 | 40357417 | 130 | | b9f8a44a91d46813b21b9602e72f112613c91408db0b8341fb94603d9db135e0 | 10000000 | 403630048 | 131 | | 0f7dda6b0837dde083c5d6b896f7d62340c8a2415b0c7121d83145e08a755272 | 100000000 | 4036326174 | 132 | 133 | The entries in the table are determined apart from GZIP compression. 134 | The `SHA-256 checksum` is a hash of the generated output file for the 135 | first `Number of lines` in the sequence. 136 | 137 | `numgen.js` can generate `es6testfile100m.txt`. 138 | -------------------------------------------------------------------------------- /test-data/fuzzies/1.json: -------------------------------------------------------------------------------- 1 | [{"�\u0017B��":null,"�\u0017\\�4�":null,"�&BI":true,"��\n�V":true,"���j���Bȵ�":true},-3833854707,true,-1405764607] 2 | -------------------------------------------------------------------------------- /test-data/generated/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahdinosaur/json-canon/05458a56871a15fb38837956d8b60b2622bb976c/test-data/generated/.gitkeep -------------------------------------------------------------------------------- /test-data/input/arrays.json: -------------------------------------------------------------------------------- 1 | [ 2 | 56, 3 | { 4 | "d": true, 5 | "10": null, 6 | "1": [ ] 7 | } 8 | ] 9 | -------------------------------------------------------------------------------- /test-data/input/french.json: -------------------------------------------------------------------------------- 1 | { 2 | "peach": "This sorting order", 3 | "péché": "is wrong according to French", 4 | "pêche": "but canonicalization MUST", 5 | "sin": "ignore locale" 6 | } 7 | -------------------------------------------------------------------------------- /test-data/input/structures.json: -------------------------------------------------------------------------------- 1 | { 2 | "1": {"f": {"f": "hi","F": 5} ,"\n": 56.0}, 3 | "10": { }, 4 | "": "empty", 5 | "a": { }, 6 | "111": [ {"e": "yes","E": "no" } ], 7 | "A": { } 8 | } -------------------------------------------------------------------------------- /test-data/input/unicode.json: -------------------------------------------------------------------------------- 1 | { 2 | "Unnormalized Unicode":"A\u030a" 3 | } 4 | -------------------------------------------------------------------------------- /test-data/input/values.json: -------------------------------------------------------------------------------- 1 | { 2 | "numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001], 3 | "string": "\u20ac$\u000F\u000aA'\u0042\u0022\u005c\\\"\/", 4 | "literals": [null, true, false] 5 | } -------------------------------------------------------------------------------- /test-data/input/weird.json: -------------------------------------------------------------------------------- 1 | { 2 | "\u20ac": "Euro Sign", 3 | "\r": "Carriage Return", 4 | "\u000a": "Newline", 5 | "1": "One", 6 | "\u0080": "Control\u007f", 7 | "\ud83d\ude02": "Smiley", 8 | "\u00f6": "Latin Small Letter O With Diaeresis", 9 | "\ufb33": "Hebrew Letter Dalet With Dagesh", 10 | "": "Browser Challenge" 11 | } 12 | -------------------------------------------------------------------------------- /test-data/output/arrays.json: -------------------------------------------------------------------------------- 1 | [56,{"1":[],"10":null,"d":true}] -------------------------------------------------------------------------------- /test-data/output/french.json: -------------------------------------------------------------------------------- 1 | {"peach":"This sorting order","péché":"is wrong according to French","pêche":"but canonicalization MUST","sin":"ignore locale"} -------------------------------------------------------------------------------- /test-data/output/structures.json: -------------------------------------------------------------------------------- 1 | {"":"empty","1":{"\n":56,"f":{"F":5,"f":"hi"}},"10":{},"111":[{"E":"no","e":"yes"}],"A":{},"a":{}} -------------------------------------------------------------------------------- /test-data/output/unicode.json: -------------------------------------------------------------------------------- 1 | {"Unnormalized Unicode":"Å"} -------------------------------------------------------------------------------- /test-data/output/values.json: -------------------------------------------------------------------------------- 1 | {"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\u000f\nA'B\"\\\\\"/"} -------------------------------------------------------------------------------- /test-data/output/weird.json: -------------------------------------------------------------------------------- 1 | {"\n":"Newline","\r":"Carriage Return","1":"One","":"Browser Challenge","€":"Control","ö":"Latin Small Letter O With Diaeresis","€":"Euro Sign","😂":"Smiley","דּ":"Hebrew Letter Dalet With Dagesh"} --------------------------------------------------------------------------------