├── .clang-format ├── .editorconfig ├── .envrc ├── .eslintignore ├── .eslintrc.json ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .gitmodules ├── .husky ├── .gitignore ├── pre-commit └── pre-push ├── .prettierignore ├── .prettierrc ├── .vscode ├── c_cpp_properties.json ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── lint-staged.config.js ├── package-lock.json ├── package.json ├── packages ├── roaring-wasm-src │ ├── IDisposable.ts │ ├── ReadonlyRoaringBitmap32.ts │ ├── RoaringArenaAllocator.ts │ ├── RoaringBitmap32.ts │ ├── RoaringBitmap32Iterator.ts │ ├── RoaringUint8Array.ts │ ├── cpp │ │ ├── global.h │ │ ├── roaring-js.c │ │ └── roaring.c │ ├── enums.ts │ ├── index.ts │ ├── lib │ │ ├── free-finalization-registry.ts │ │ ├── roaring-arena-allocator-stack.ts │ │ ├── roaring-wasm-module.d.ts │ │ └── roaring-wasm.ts │ ├── package.json │ ├── tsconfig.json │ └── utils.ts └── roaring-wasm │ ├── .npmignore │ ├── LICENSE │ ├── README.md │ ├── package.json │ └── tsconfig.json ├── playwright.config.ts ├── pnpm-workspace.yaml ├── scripts ├── build.js ├── clean.js ├── compile-ts.js ├── compile-wasm.js ├── config │ ├── exportedFunctions.js │ ├── paths.d.ts │ ├── paths.js │ └── terser-config.js ├── lib │ ├── logging.js │ └── utils.js ├── lint.js ├── precommit.js ├── prepush.js ├── test.js ├── typecheck.js └── update-roaring.sh ├── submodules └── .vscode │ └── settings.json ├── test ├── benchmark.js ├── package-test │ └── package.test.ts ├── playwright │ └── browser-mocha.spec.ts ├── stress │ ├── data.txt │ └── index.js ├── tslint.json ├── unit │ ├── IDisposable.test.ts │ ├── RoaringArenaAllocator.test.ts │ ├── RoaringBitmap32 │ │ ├── RoaringBitmap32-empty.test.ts │ │ ├── RoaringBitmap32-many.test.ts │ │ ├── RoaringBitmap32-one-element.test.ts │ │ ├── RoaringBitmap32.ranges.test.ts │ │ ├── RoaringBitmap32.serialization.test.ts │ │ ├── RoaringBitmap32.static.test.ts │ │ ├── RoaringBitmap32.test.ts │ │ ├── RoaringBitmap32.to.test.ts │ │ └── data │ │ │ └── serialized.json │ ├── RoaringBitmap32Iterator.test.ts │ └── RoaringUint8Array.test.ts └── web │ ├── index.html │ ├── main.ts │ ├── roaring.jpg │ ├── styles.css │ ├── tsconfig.json │ └── vite.config.ts ├── tsconfig-build.json └── tsconfig.json /.clang-format: -------------------------------------------------------------------------------- 1 | DisableFormat: false 2 | BasedOnStyle: Chromium 3 | IndentWidth: 2 4 | UseTab: Never 5 | ColumnLimit: 125 6 | NamespaceIndentation: All 7 | AlignAfterOpenBracket: AlwaysBreak 8 | AlignConsecutiveAssignments: false 9 | AlignConsecutiveBitFields: false 10 | AlignConsecutiveDeclarations: false 11 | AlignConsecutiveMacros: false 12 | AlignTrailingComments: false 13 | AlignEscapedNewlines: Left 14 | AlignOperands: false 15 | BitFieldColonSpacing: After 16 | AllowShortEnumsOnASingleLine: true 17 | AllowShortBlocksOnASingleLine: false 18 | AllowShortCaseLabelsOnASingleLine: true 19 | AlwaysBreakBeforeMultilineStrings: true 20 | AllowShortFunctionsOnASingleLine: true 21 | AllowShortIfStatementsOnASingleLine: true 22 | AllowShortLambdasOnASingleLine: false 23 | AllowShortLoopsOnASingleLine: false 24 | AlwaysBreakAfterDefinitionReturnType: false 25 | AllowAllArgumentsOnNextLine: true 26 | AllowAllConstructorInitializersOnNextLine: true 27 | AllowAllParametersOfDeclarationOnNextLine: true 28 | AlwaysBreakTemplateDeclarations: true 29 | BreakBeforeTernaryOperators: true 30 | ConstructorInitializerAllOnOneLineOrOnePerLine: true 31 | ConstructorInitializerIndentWidth: 2 32 | ContinuationIndentWidth: 2 33 | LambdaBodyIndentation: Signature 34 | PointerAlignment: Middle 35 | BinPackParameters: false 36 | BinPackArguments: false 37 | MaxEmptyLinesToKeep: 1 38 | BreakBeforeBraces: Attach 39 | BreakBeforeConceptDeclarations: true 40 | BreakConstructorInitializers: AfterColon 41 | BreakInheritanceList: AfterColon 42 | IndentPPDirectives: AfterHash 43 | SortIncludes: false 44 | SortUsingDeclarations: true 45 | 46 | --- 47 | Language: JavaScript 48 | DisableFormat: true 49 | ColumnLimit: 120 50 | JavaScriptQuotes: Single 51 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | 7 | [*.{js,ts}] 8 | charset = utf-8 9 | indent_style = space 10 | indent_size = 2 -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | source ~/emsdk/emsdk_env.sh 2 | PATH=$BINARYEN_ROOT/bin:$PATH -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | temp 2 | packages/roaring-wasm/**/*.*ts 3 | packages/roaring-wasm/**/*.*js 4 | src/cpp/**/* 5 | docs/**/* 6 | build/ 7 | 8 | roaring-wasm-module 9 | 10 | # dotfiles 11 | 12 | !.*.js 13 | !.*._js 14 | !.*.jsx 15 | !.*.mjs 16 | !.*.cjs 17 | !.*.es 18 | !.*.es6 19 | !.*.assetgen 20 | !.*.ts 21 | !.*.tsx 22 | !.*.json 23 | !.eslintrc.js 24 | 25 | # Dependencies and vendor 26 | vendor 27 | typings 28 | node_modules 29 | bower_components 30 | jspm_packages 31 | package-lock.json 32 | /.pnp 33 | .pnp.js 34 | .serverless 35 | .webpack 36 | .next/ 37 | 38 | # Build outputs 39 | bundle.js 40 | *.bundle.js 41 | .serverless 42 | build/Release 43 | *.min.* 44 | *-min.* 45 | 46 | # Cache 47 | .git 48 | .eslintcache 49 | .tmp 50 | .temp 51 | .cache 52 | .fuse_hidden* 53 | .fusebox 54 | .dynamodb 55 | 56 | # Test coverage and snapshots 57 | lib-cov 58 | coverage 59 | .nyc_output 60 | __snapshots__ 61 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["@balsamic"], 3 | "plugins": ["node", "import"], 4 | "rules": { 5 | "global-require": 0, 6 | "@typescript-eslint/no-unsafe-declaration-merging": 0 7 | }, 8 | "overrides": [ 9 | { 10 | "files": ["index.js"], 11 | "rules": { 12 | "node/no-unpublished-require": 0, 13 | "import/no-unresolved": 0 14 | } 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | with: 11 | submodules: true 12 | - name: Use Node.js 18.x 13 | uses: actions/setup-node@v3 14 | with: 15 | node-version: 18.x 16 | cache: "npm" 17 | - name: Install emcc 18 | uses: mymindstorm/setup-emsdk@v12 19 | with: 20 | version: 3.1.41 21 | - run: npm ci 22 | - run: npm run lint:ci # run linting 23 | - run: npm run build # build the library and run tests 24 | - run: npm run lint:ci # re-run linting after build 25 | 26 | - name: Install Playwright Browsers 27 | run: npx playwright install --with-deps 28 | - name: Run Playwright tests 29 | run: npx playwright test 30 | - uses: actions/upload-artifact@v3 31 | if: always() 32 | with: 33 | name: playwright-report 34 | path: playwright-report/ 35 | retention-days: 10 36 | 37 | - run: npm run doc # build the documentation 38 | 39 | - name: Deploy documentation 🚀 40 | if: github.ref == 'refs/heads/master' 41 | uses: JamesIves/github-pages-deploy-action@4.1.4 42 | with: 43 | branch: gh-pages 44 | folder: docs 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compilation output 2 | 3 | packages/roaring-wasm/**/*.*ts 4 | packages/roaring-wasm/**/*.*js 5 | packages/roaring-wasm/**/*.wasm 6 | **/*.o 7 | docs/ 8 | build/ 9 | 10 | roaring-wasm-module 11 | 12 | temp 13 | 14 | # Logs 15 | logs 16 | *.log 17 | npm-debug.log* 18 | yarn-debug.log* 19 | yarn-error.log* 20 | 21 | # Runtime data 22 | pids 23 | *.pid 24 | *.seed 25 | *.pid.lock 26 | 27 | # Directory for instrumented libs generated by jscoverage/JSCover 28 | lib-cov 29 | 30 | # Coverage directory used by tools like istanbul 31 | coverage 32 | 33 | # nyc test coverage 34 | .nyc_output 35 | 36 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 37 | .grunt 38 | 39 | # Bower dependency directory (https://bower.io/) 40 | bower_components 41 | 42 | # node-waf configuration 43 | .lock-wscript 44 | 45 | # Compiled binary addons (http://nodejs.org/api/addons.html) 46 | build/Release 47 | 48 | # Dependency directories 49 | node_modules/ 50 | jspm_packages/ 51 | 52 | # Typescript v1 declaration files 53 | typings/ 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Optional REPL history 62 | .node_repl_history 63 | 64 | # Output of 'npm pack' 65 | *.tgz 66 | 67 | # Yarn Integrity file 68 | .yarn-integrity 69 | 70 | # dotenv environment variables file 71 | .env 72 | 73 | 74 | 75 | # General 76 | .DS_Store 77 | .AppleDouble 78 | .LSOverride 79 | 80 | # Icon must end with two \r 81 | Icon 82 | 83 | 84 | # Thumbnails 85 | ._* 86 | 87 | # Files that might appear in the root of a volume 88 | .DocumentRevisions-V100 89 | .fseventsd 90 | .Spotlight-V100 91 | .TemporaryItems 92 | .Trashes 93 | .VolumeIcon.icns 94 | .com.apple.timemachine.donotpresent 95 | 96 | # Directories potentially created on remote AFP share 97 | .AppleDB 98 | .AppleDesktop 99 | Network Trash Folder 100 | Temporary Items 101 | .apdisk 102 | 103 | # Windows thumbnail cache files 104 | Thumbs.db 105 | ehthumbs.db 106 | ehthumbs_vista.db 107 | 108 | # Dump file 109 | *.stackdump 110 | 111 | # Folder config file 112 | [Dd]esktop.ini 113 | 114 | # Recycle Bin used on file shares 115 | $RECYCLE.BIN/ 116 | 117 | # Windows Installer files 118 | *.cab 119 | *.msi 120 | *.msix 121 | *.msm 122 | *.msp 123 | 124 | # Windows shortcuts 125 | *.lnk 126 | /test-results/ 127 | /playwright-report/ 128 | /playwright/.cache/ 129 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "submodules/CRoaring"] 2 | path = submodules/CRoaring 3 | url = https://github.com/RoaringBitmap/CRoaring.git 4 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | node scripts/precommit.js 2 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | node scripts/prepush.js 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | src/cpp/**/* 2 | docs/**/* 3 | submodules/**/* 4 | .clang-tidy 5 | build/ 6 | packages/roaring-wasm/**/*.*ts 7 | packages/roaring-wasm/**/*.*js 8 | 9 | roaring-wasm-module 10 | 11 | # Dependencies and vendor 12 | vendor 13 | typings 14 | node_modules 15 | bower_components 16 | jspm_packages 17 | package-lock.json 18 | /.pnp 19 | .pnp.js 20 | .serverless 21 | .webpack 22 | .next/ 23 | 24 | # Build outputs 25 | bundle.js 26 | *.bundle.js 27 | .serverless 28 | build/Debug 29 | build/Release 30 | *.min.* 31 | *-min.* 32 | 33 | # Cache 34 | .tmp 35 | .temp 36 | .cache 37 | .fuse_hidden* 38 | .fusebox 39 | .dynamodb 40 | 41 | # Test coverage and snapshots 42 | lib-cov 43 | coverage 44 | .nyc_output 45 | __snapshots__ 46 | 47 | .vercel 48 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSpacing": true, 4 | "endOfLine": "lf", 5 | "htmlWhitespaceSensitivity": "css", 6 | "jsxSingleQuote": false, 7 | "printWidth": 120, 8 | "semi": true, 9 | "singleQuote": false, 10 | "tabWidth": 2, 11 | "trailingComma": "all", 12 | "useTabs": false 13 | } 14 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Mac", 5 | "includePath": [ 6 | "${workspaceFolder}", 7 | "${workspaceFolder}/submodules/CRoaring/include", 8 | "${env:EMSDK}/upstream/emscripten/system/include" 9 | ], 10 | "defines": [], 11 | "intelliSenseMode": "clang-x64", 12 | "browse": { 13 | "path": [ 14 | "${workspaceFolder}", 15 | "${workspaceFolder}/submodules/CRoaring/include", 16 | "${env:EMSDK}/upstream/emscripten/system/include" 17 | ], 18 | "limitSymbolsToIncludedHeaders": true, 19 | "databaseFilename": "" 20 | }, 21 | "macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"], 22 | "compilerPath": "/usr/bin/clang", 23 | "cStandard": "c11", 24 | "cppStandard": "c++17" 25 | }, 26 | { 27 | "name": "Linux", 28 | "includePath": [ 29 | "${workspaceFolder}", 30 | "${workspaceFolder}/submodules/CRoaring/include", 31 | "${env:EMSDK}/upstream/emscripten/system/include", 32 | "/usr/include", 33 | "/usr/local/include" 34 | ], 35 | "defines": [], 36 | "intelliSenseMode": "clang-x64", 37 | "browse": { 38 | "path": [ 39 | "${workspaceFolder}", 40 | "${workspaceFolder}/submodules/CRoaring/include", 41 | "${env:EMSDK}/upstream/emscripten/system/include", 42 | "/usr/include", 43 | "/usr/local/include" 44 | ], 45 | "limitSymbolsToIncludedHeaders": true, 46 | "databaseFilename": "" 47 | } 48 | }, 49 | { 50 | "name": "Win32", 51 | "includePath": [ 52 | "${workspaceFolder}", 53 | "${workspaceFolder}/submodules/CRoaring/include", 54 | "${env:EMSDK}/upstream/emscripten/system/include", 55 | "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include" 56 | ], 57 | "defines": ["_DEBUG", "UNICODE", "_UNICODE"], 58 | "intelliSenseMode": "msvc-x64", 59 | "browse": { 60 | "path": ["C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/include/*", "${workspaceFolder}"], 61 | "limitSymbolsToIncludedHeaders": true, 62 | "databaseFilename": "" 63 | } 64 | } 65 | ], 66 | "version": 4 67 | } 68 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode", 5 | "pflannery.vscode-versionlens", 6 | "visualstudioexptteam.vscodeintellicode", 7 | "donjayamanne.githistory", 8 | "eamodio.gitlens", 9 | "ms-vscode.cpptools", 10 | "xaver.clang-format" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[json]": { 3 | "editor.defaultFormatter": "esbenp.prettier-vscode", 4 | "editor.formatOnSave": true, 5 | "editor.quickSuggestions": { 6 | "comments": true, 7 | "other": true, 8 | "strings": true 9 | } 10 | }, 11 | "[jsonc]": { 12 | "editor.defaultFormatter": "esbenp.prettier-vscode", 13 | "editor.formatOnSave": true, 14 | "editor.quickSuggestions": { 15 | "comments": true, 16 | "other": true, 17 | "strings": true 18 | } 19 | }, 20 | "[css]": { 21 | "editor.defaultFormatter": "esbenp.prettier-vscode", 22 | "editor.formatOnSave": true 23 | }, 24 | "[html]": { 25 | "editor.defaultFormatter": "esbenp.prettier-vscode", 26 | "editor.formatOnSave": true 27 | }, 28 | "[javascript]": { 29 | "editor.defaultFormatter": "esbenp.prettier-vscode", 30 | "editor.formatOnSave": true 31 | }, 32 | "[javascriptreact]": { 33 | "editor.defaultFormatter": "esbenp.prettier-vscode", 34 | "editor.formatOnSave": true 35 | }, 36 | "[typescript]": { 37 | "editor.defaultFormatter": "esbenp.prettier-vscode", 38 | "editor.formatOnSave": true 39 | }, 40 | "[typescriptreact]": { 41 | "editor.defaultFormatter": "esbenp.prettier-vscode", 42 | "editor.formatOnSave": true 43 | }, 44 | "editor.codeActionsOnSave": { 45 | "source.fixAll": "explicit", 46 | "source.fixAll.eslint": "explicit" 47 | }, 48 | "[c]": { 49 | "editor.defaultFormatter": "xaver.clang-format" 50 | }, 51 | "[cpp]": { 52 | "editor.defaultFormatter": "xaver.clang-format" 53 | }, 54 | "editor.detectIndentation": false, 55 | "editor.formatOnSave": true, 56 | "editor.lineNumbers": "on", 57 | "editor.tabSize": 2, 58 | "eslint.codeActionsOnSave.mode": "all", 59 | "eslint.format.enable": true, 60 | "eslint.lintTask.enable": true, 61 | "eslint.validate": [], 62 | "javascript.format.semicolons": "insert", 63 | "typescript.format.semicolons": "insert", 64 | "files.eol": "\n", 65 | "git.detectSubmodules": true, 66 | "cmake.configureOnOpen": false, 67 | "files.associations": { 68 | "filesystem": "c", 69 | "__locale": "c", 70 | "roaring_array.h": "c" 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # roaring-wasm 2 | 3 | WebAssembly port of [Roaring Bitmaps](http://roaringbitmap.org) for Node, Browser and Deno. 4 | It is interoperable with other implementations via the [Roaring format](https://github.com/RoaringBitmap/RoaringFormatSpec/). 5 | 6 | Roaring bitmaps are compressed bitmaps. They can be hundreds of times faster. 7 | 8 | ## NOTE 9 | 10 | This package is intended as a stripped down cross platform and browser compatible alternative to [roaring-node](https://www.npmjs.com/package/roaring), [repository](https://github.com/SalvatorePreviti/roaring-node). 11 | If you are using just NodeJS, [roaring-node](https://github.com/SalvatorePreviti/roaring-node) is faster, has a better API that fully leverages the v8 garbage collector and the native CPU SIMD instructions, and has also asynchronous operations. 12 | 13 | # WARNING ⚠️ - breaking API changes introduced in version 1.0.0 14 | 15 | Please update your codebase accordingly. 16 | 17 | - remove cardinality() method, replaced with "size" property 18 | - convert method isEmpty() to a property isEmpty: boolean 19 | - serialize and deserialize now require a format argument 20 | - removed RoaringUint32Array - since we have "streaming" functions now that copy chunks data in chunks between JS 21 | - removed some utility methods 22 | - removed usage of Node buffer 23 | 24 | ## installation 25 | 26 | ```sh 27 | npm install --save roaring-wasm 28 | ``` 29 | 30 | Try it live - 31 | 32 | Code sample: 33 | 34 | ```javascript 35 | // npm install --save roaring-wasm 36 | // create this file as demo.js 37 | // type node demo.js or nodejs demo.js depending on your system 38 | 39 | import { RoaringBitmap32, roaringLibraryInitialize } from "roaring-wasm"; 40 | 41 | // This is needed in browser (and in this case we are using top level await), in nodejs this is not required. 42 | await roaringLibraryInitialize(); 43 | 44 | var bitmap1 = new RoaringBitmap32(); 45 | bitmap1.addMany([1, 2, 3, 4, 5, 100, 1000]); 46 | console.log("bitmap1.toSet():", bitmap1.toSet()); 47 | 48 | var bitmap2 = new RoaringBitmap32(); 49 | bitmap2.addMany([3, 4, 1000]); 50 | console.log("bitmap2.toSet():", bitmap1.toSet()); 51 | 52 | var bitmap3 = new RoaringBitmap32(); 53 | console.log("bitmap1.size:", bitmap1.size); 54 | console.log("bitmap2.has(3):", bitmap2.has(3)); 55 | 56 | bitmap3.add(111); 57 | bitmap3.add(544); 58 | bitmap3.orInPlace(bitmap1); 59 | bitmap1.optimize(); 60 | console.log(bitmap3.toString()); 61 | 62 | console.log("bitmap3.toArray():", bitmap3.toArray()); 63 | console.log("bitmap3.maximum():", bitmap3.maximum()); 64 | console.log("bitmap3.rank(100):", bitmap3.rank(100)); 65 | 66 | bitmap1.dispose(); 67 | bitmap2.dispose(); 68 | bitmap3.dispose(); 69 | ``` 70 | 71 | ## Documentation 72 | 73 | [https://salvatorepreviti.github.io/roaring-wasm](https://salvatorepreviti.github.io/roaring-wasm/modules.html) 74 | 75 | ## References 76 | 77 | - [roaring for NodeJS](https://www.npmjs.com/package/roaring), [repository](https://github.com/SalvatorePreviti/roaring-node) 78 | 79 | - This package - 80 | 81 | - Source code and build tools for this package - 82 | 83 | - Roaring Bitmaps - 84 | 85 | - Portable Roaring bitmaps in C - 86 | 87 | - emscripten - 88 | 89 | # Licenses 90 | 91 | - This package is provided as open source software using Apache License. 92 | 93 | - CRoaring is provided as open source software using Apache License. 94 | 95 | # API 96 | 97 | See the [roaring module documentation](https://salvatorepreviti.github.io/roaring-wasm/modules.html) 98 | 99 | # Other 100 | 101 | Wanna play an open source game made by the author of this library? Try [Dante](https://github.com/SalvatorePreviti/js13k-2022) 102 | 103 | # Development, local building 104 | 105 | This project requires emsdk installed and activated. See . 106 | 107 | On mac you can install emscripten with homebrew: 108 | 109 | ``` 110 | brew install emscripten 111 | ``` 112 | 113 | To download the repository: 114 | 115 | ``` 116 | git clone https://github.com/SalvatorePreviti/roaring-wasm.git 117 | 118 | cd roaring-wasm 119 | 120 | git submodule update --init --recursive 121 | 122 | npm install 123 | ``` 124 | 125 | To compile and run test 126 | 127 | ``` 128 | npm run build 129 | ``` 130 | 131 | Output will be generated in the `packages/roaring-wasm` folder 132 | 133 | The build system was tried on Linux and MacOSX, is not tested/maintained for other system or Windows. 134 | -------------------------------------------------------------------------------- /lint-staged.config.js: -------------------------------------------------------------------------------- 1 | /* eslint node/no-unpublished-require:0 */ 2 | 3 | const { ESLint } = require("eslint"); 4 | 5 | const removeIgnoredFiles = async (files) => { 6 | const eslint = new ESLint(); 7 | const ignoredFiles = await Promise.all(files.map((file) => eslint.isPathIgnored(file))); 8 | const filteredFiles = files.filter((_, i) => !ignoredFiles[i]); 9 | return filteredFiles.join(" "); 10 | }; 11 | 12 | module.exports = { 13 | "*.{js,jsx,ts,tsx}": async (files) => { 14 | const filesToLint = await removeIgnoredFiles(files); 15 | return [`eslint --max-warnings=0 ${filesToLint}`]; 16 | }, 17 | }; 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@roaring-wasm/workspace", 3 | "private": true, 4 | "version": "1.0.0", 5 | "description": "Node JS porting of Roaring using WebAssembly", 6 | "main": "index.js", 7 | "scripts": { 8 | "prepare": "husky install", 9 | "lint": "node scripts/lint.js", 10 | "lint:ci": "node scripts/lint.js --ci", 11 | "clean": "node scripts/clean.js", 12 | "build": "node scripts/build.js", 13 | "test": "node scripts/test.js", 14 | "doc": "typedoc ./packages/roaring-wasm/index.d.ts --tsconfig ./packages/roaring-wasm/tsconfig.json", 15 | "web-app": "vite --config ./test/web/vite.config.ts", 16 | "web-test": "playwright test", 17 | "precommit": "lint-staged && pretty-quick --staged" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/SalvatorePreviti/roaring-wasm.git" 22 | }, 23 | "keywords": [ 24 | "roaring" 25 | ], 26 | "engines": { 27 | "node": ">=14" 28 | }, 29 | "author": "Salvatore Previti", 30 | "license": "Apache-2.0", 31 | "bugs": { 32 | "url": "https://github.com/SalvatorePreviti/roaring-wasm/issues" 33 | }, 34 | "homepage": "https://github.com/SalvatorePreviti/roaring-wasm#readme", 35 | "husky": { 36 | "hooks": { 37 | "pre-commit": "lint-staged" 38 | } 39 | }, 40 | "workspaces": [ 41 | "packages/*" 42 | ], 43 | "dependencies": { 44 | "roaring-wasm": "*", 45 | "roaring-wasm-src": "*" 46 | }, 47 | "devDependencies": { 48 | "@balsamic/eslint-config": "^0.7.0", 49 | "@playwright/test": "^1.48.0", 50 | "@types/chai": "^4.3.20", 51 | "@types/chai-as-promised": "^8.0.1", 52 | "@types/mocha": "^10.0.9", 53 | "@types/node": "^22.7.5", 54 | "@typescript-eslint/eslint-plugin": "^7.18.0", 55 | "@typescript-eslint/parser": "^7.18.0", 56 | "benchmark": "^2.1.4", 57 | "chai": "^4.5.0", 58 | "chai-as-promised": "^7.1.2", 59 | "delete-empty": "^3.0.0", 60 | "esbuild": "^0.24.0", 61 | "eslint": "^8.57.1", 62 | "eslint-plugin-chai-expect": "^3.1.0", 63 | "eslint-plugin-import": "^2.31.0", 64 | "eslint-plugin-json": "^4.0.1", 65 | "eslint-plugin-node": "^11.1.0", 66 | "fast-glob": "^3.3.2", 67 | "fastbitset": "^0.4.1", 68 | "husky": "^9.1.6", 69 | "lint-staged": "^15.2.10", 70 | "mocha": "^10.3.0", 71 | "prettier": "^3.2.5", 72 | "pretty-quick": "^4.0.0", 73 | "terser": "^5.34.1", 74 | "ts-node": "^10.9.2", 75 | "tslib": "^2.7.0", 76 | "tsup": "^8.3.0", 77 | "typedoc": "^0.26.8", 78 | "typescript": "^5.6.2", 79 | "vite": "^5.4.8", 80 | "vite-plugin-node-polyfills": "^0.22.0", 81 | "eslint-plugin-mocha": "^10.5.0" 82 | }, 83 | "lint-staged": { 84 | "*.{js,jsx,ts,tsx,mts,cts,cjs,mjs,json}": [ 85 | "eslint --no-error-on-unmatched-pattern --fix", 86 | "prettier --write --loglevel=warn" 87 | ], 88 | "*.{yml,yaml,md,htm,html,css,scss,less}": [ 89 | "prettier --write --loglevel=warn" 90 | ] 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/IDisposable.ts: -------------------------------------------------------------------------------- 1 | export interface IDisposable { 2 | dispose(): boolean | void; 3 | } 4 | 5 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 6 | type UnsafeAny = any; 7 | 8 | const _thenableToPromise = async (thenable: PromiseLike): Promise => thenable; 9 | 10 | /** 11 | * Checks if the given value is an instance of `IDisposable`. 12 | * Returns true only if value is a non null object and has a method "dispose" 13 | * @param value The value to check. 14 | * @returns true if the value is an instance of `IDisposable`, false otherwise. 15 | */ 16 | export const isDisposable = (value: unknown): value is IDisposable => 17 | typeof value === "object" && value !== null && typeof (value as unknown as IDisposable).dispose === "function"; 18 | 19 | /** 20 | * Disposes the given IDisposable instance. 21 | * @param disposable The object to dispose. 22 | * @returns true if the object was disposed, false otherwise. 23 | */ 24 | export const dispose = (disposable: IDisposable | null | undefined): boolean => { 25 | const ret = !!disposable && typeof disposable.dispose === "function" && disposable.dispose(); 26 | return ret === undefined || ret === true; 27 | }; 28 | 29 | /** 30 | * Disposes the IDisposable passed as "this". 31 | * @example 32 | * ```ts 33 | * const disposable: IDisposable = ...; 34 | * const disposeFn = disposeThis.bind(disposable); 35 | * disposeFn(); 36 | * ``` 37 | * @returns true if the object was disposed, false otherwise. 38 | */ 39 | export function disposeThis(this: IDisposable | null | undefined): boolean { 40 | const ret = !!this && typeof this.dispose === "function" && this.dispose(); 41 | return ret === undefined || ret === true; 42 | } 43 | 44 | /** 45 | * Tries to dispose the given object. 46 | * Does not throw and eats the exception if any. 47 | * @param disposable The object to dispose or a promise of the object to dispose. 48 | * @returns true if the object was disposed, false otherwise. 49 | */ 50 | export const tryDispose = (disposable: IDisposable | null | undefined): boolean => { 51 | if (disposable) { 52 | try { 53 | const ret = typeof disposable.dispose === "function" && disposable.dispose(); 54 | return ret === undefined || ret; 55 | } catch { 56 | // Ignore exception 57 | } 58 | } 59 | return false; 60 | }; 61 | 62 | export const using: { 63 | < 64 | TFn extends (disposable: TDisposable) => UnsafeAny, 65 | TDisposable extends Readonly | null | undefined = IDisposable, 66 | >( 67 | disposable: TDisposable, 68 | what: TFn, 69 | ): ReturnType extends never 70 | ? never 71 | : ReturnType extends PromiseLike> 72 | ? Promise 73 | : ReturnType; 74 | 75 | | null | undefined = IDisposable>( 76 | disposable: TDisposable, 77 | what: TValue, 78 | ): TValue extends never ? never : TValue extends PromiseLike> ? Promise : TValue; 79 | } = (disposable: UnsafeAny, what: UnsafeAny) => { 80 | let result: UnsafeAny; 81 | try { 82 | result = typeof what === "function" ? what(disposable) : what; 83 | if (typeof result === "object" && result !== null && typeof result.then === "function") { 84 | return (typeof result.finally === "function" ? result : _thenableToPromise(result)).finally( 85 | disposeThis.bind(disposable), 86 | ); 87 | } 88 | } catch (e) { 89 | tryDispose(disposable); 90 | throw e; 91 | } 92 | dispose(disposable); 93 | return result; 94 | }; 95 | 96 | export const disposeAll = ( 97 | ...disposables: readonly ( 98 | | readonly (IDisposable | null | undefined | false | readonly (IDisposable | null | undefined | false)[])[] 99 | | IDisposable 100 | | null 101 | | undefined 102 | | false 103 | )[] 104 | ): number => { 105 | let result = 0; 106 | let errorToThrow: Error | undefined; 107 | for (const disposable of disposables) { 108 | try { 109 | if (isDisposable(disposable)) { 110 | if (dispose(disposable)) { 111 | ++result; 112 | } 113 | } 114 | } catch (e) { 115 | errorToThrow = e as Error; 116 | } 117 | if (Array.isArray(disposable)) { 118 | disposeAll(...disposable); 119 | } 120 | } 121 | if (errorToThrow !== undefined) { 122 | throw errorToThrow; 123 | } 124 | return result; 125 | }; 126 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/RoaringArenaAllocator.ts: -------------------------------------------------------------------------------- 1 | import type { IDisposable } from "./IDisposable"; 2 | import { dispose } from "./IDisposable"; 3 | 4 | import { RoaringUint8Array } from "./RoaringUint8Array"; 5 | import { RoaringBitmap32 } from "./RoaringBitmap32"; 6 | import { 7 | _roaringArenaAllocator_head, 8 | _roaringArenaAllocator_pop, 9 | _roaringArenaAllocator_push, 10 | } from "./lib/roaring-arena-allocator-stack"; 11 | import { RoaringBitmap32Iterator } from "./RoaringBitmap32Iterator"; 12 | import type { BasicTypedArray } from "./utils"; 13 | 14 | export class RoaringArenaAllocator { 15 | #refs: Set | null; 16 | #escaped: Set | null; 17 | #started: number; 18 | 19 | public static get current(): RoaringArenaAllocator | null { 20 | return _roaringArenaAllocator_head; 21 | } 22 | 23 | /** 24 | * Starts a new arena allocator. 25 | * @returns The new arena allocator. 26 | */ 27 | public static start(): RoaringArenaAllocator { 28 | return new RoaringArenaAllocator().start(); 29 | } 30 | 31 | /** 32 | * Stops the current arena allocator. 33 | * @returns The stopped arena allocator. 34 | * @see start 35 | * @see current 36 | * @see with 37 | */ 38 | public static stop(): RoaringArenaAllocator | null { 39 | const instance = _roaringArenaAllocator_head; 40 | return instance && instance.stop(); 41 | } 42 | 43 | /** 44 | * Gets the number of references currently registered. 45 | * @returns The number of references, escaped or not. 46 | */ 47 | public get size(): number { 48 | const refs = this.#refs; 49 | return refs ? refs.size : 0; 50 | } 51 | 52 | /** 53 | * Gets the number of references currently escaped. 54 | * Escaped references are not disposed when the arena is stopped. 55 | * @returns The number of escaped references. 56 | * @see escape 57 | */ 58 | public get escaped(): number { 59 | const escaped = this.#escaped; 60 | return escaped ? escaped.size : 0; 61 | } 62 | 63 | public static with( 64 | fn: (allocator: RoaringArenaAllocator) => void, 65 | allocator: RoaringArenaAllocator = new RoaringArenaAllocator(), 66 | ): void { 67 | allocator.with(fn); 68 | } 69 | 70 | public constructor() { 71 | this.#refs = null; 72 | this.#escaped = null; 73 | this.#started = 0; 74 | } 75 | 76 | public disposeAll(): number { 77 | const refs = this.#refs; 78 | let result = 0; 79 | if (refs) { 80 | const escaped = this.#escaped; 81 | this.#refs = null; 82 | for (const ref of refs) { 83 | if (ref && (!escaped || !escaped.has(ref))) { 84 | if (dispose(ref)) { 85 | ++result; 86 | } 87 | } 88 | } 89 | } 90 | return result; 91 | } 92 | 93 | public start(): this { 94 | ++this.#started; 95 | _roaringArenaAllocator_push(this); 96 | return this; 97 | } 98 | 99 | public stop(): this { 100 | if (this.#started > 0) { 101 | _roaringArenaAllocator_pop(this); 102 | --this.#started; 103 | } 104 | this.disposeAll(); 105 | return this; 106 | } 107 | 108 | public with(fn: (allocator: RoaringArenaAllocator) => T): T { 109 | this.start(); 110 | try { 111 | return fn(this); 112 | } finally { 113 | this.stop(); 114 | } 115 | } 116 | 117 | public register(disposable: T): T { 118 | (this.#refs || (this.#refs = new Set())).add(disposable); 119 | return disposable; 120 | } 121 | 122 | public unregister(disposable: IDisposable | null | undefined): boolean { 123 | const refs = this.#refs; 124 | return !!refs && refs.delete(disposable!); 125 | } 126 | 127 | public escape(disposable: T): T { 128 | (this.#escaped || (this.#escaped = new Set())).add(disposable); 129 | return disposable; 130 | } 131 | 132 | public newRoaringUint8Array(lengthOrArray?: number | Iterable | ArrayLike | null | undefined) { 133 | // eslint-disable-next-line @typescript-eslint/no-use-before-define 134 | return new RoaringUint8Array(lengthOrArray, this); 135 | } 136 | 137 | public newRoaringBitmap32Iterator(bitmap?: RoaringBitmap32 | null | undefined): RoaringBitmap32Iterator { 138 | // eslint-disable-next-line @typescript-eslint/no-use-before-define 139 | return new RoaringBitmap32Iterator(bitmap, this); 140 | } 141 | 142 | public newRoaringBitmap32( 143 | valuesOrCapacity?: 144 | | RoaringBitmap32 145 | | BasicTypedArray 146 | | Iterable 147 | | readonly (number | null | undefined | false | string)[] 148 | | number 149 | | null 150 | | undefined, 151 | ): RoaringBitmap32 { 152 | // eslint-disable-next-line @typescript-eslint/no-use-before-define 153 | return new RoaringBitmap32(valuesOrCapacity, this); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/RoaringBitmap32Iterator.ts: -------------------------------------------------------------------------------- 1 | import type { IDisposable } from "./IDisposable"; 2 | import { _free_finalizationRegistry, _free_finalizationRegistry_init } from "./lib/free-finalization-registry"; 3 | import { _roaringArenaAllocator_head } from "./lib/roaring-arena-allocator-stack"; 4 | import type { NullablePtr } from "./lib/roaring-wasm"; 5 | import { roaringWasm } from "./lib/roaring-wasm"; 6 | import type { RoaringArenaAllocator } from "./RoaringArenaAllocator"; 7 | import type { RoaringBitmap32 } from "./RoaringBitmap32"; 8 | 9 | export class RoaringBitmap32Iterator implements IDisposable, IterableIterator { 10 | #bmp: RoaringBitmap32 | null; 11 | #p: NullablePtr; 12 | #r: IteratorResult; 13 | #alloc: RoaringArenaAllocator | null; 14 | 15 | public constructor( 16 | bitmap: RoaringBitmap32 | null = null, 17 | arenaAllocator: RoaringArenaAllocator | null = _roaringArenaAllocator_head, 18 | ) { 19 | this.#bmp = bitmap; 20 | this.#p = 0; 21 | this.#r = { done: true, value: undefined }; 22 | this.#alloc = arenaAllocator; 23 | } 24 | 25 | public get isDisposed(): boolean { 26 | return this.#p === false; 27 | } 28 | 29 | public get value(): number | undefined { 30 | return this.#r.value; 31 | } 32 | 33 | public get done(): boolean { 34 | return this.#p === false; 35 | } 36 | 37 | public return(_value?: unknown): IteratorResult { 38 | this.dispose(); 39 | return this.#r; 40 | } 41 | 42 | public throw(e?: unknown): IteratorResult | never { 43 | this.dispose(); 44 | // eslint-disable-next-line @typescript-eslint/no-throw-literal 45 | throw e; 46 | } 47 | 48 | [Symbol.iterator](): IterableIterator { 49 | return this; 50 | } 51 | 52 | public clone(allocator?: RoaringArenaAllocator | null | undefined): RoaringBitmap32Iterator { 53 | const thisPtr = this.#p; 54 | const result = new RoaringBitmap32Iterator(this.#bmp, allocator); 55 | result.#p = thisPtr ? roaringWasm._roaring_iterator_js_clone(thisPtr) : thisPtr; 56 | if (result.#p) { 57 | result.#init(); 58 | } 59 | return result; 60 | } 61 | 62 | public next(): IteratorResult { 63 | const r = this.#r; 64 | let p = this.#p; 65 | const bitmap = this.#bmp; 66 | if (!p) { 67 | p = this.#init(); 68 | if (!p) { 69 | return r; 70 | } 71 | } 72 | const value = roaringWasm._roaring_iterator_js_next(p, bitmap!._p, bitmap!.v); 73 | if (value < 0) { 74 | this.#end(); 75 | } else { 76 | r.value = value; 77 | } 78 | return r; 79 | } 80 | 81 | public reset(): this { 82 | const r = this.#r; 83 | const ptr = this.#p; 84 | if (ptr) { 85 | if (_free_finalizationRegistry) { 86 | _free_finalizationRegistry.unregister(this); 87 | } 88 | roaringWasm._free(ptr); 89 | } 90 | this.#p = 0; 91 | r.done = false; 92 | r.value = undefined; 93 | return this; 94 | } 95 | 96 | public moveToGreaterEqual(minimumValue: number): this { 97 | let p = this.#p; 98 | if (!p) { 99 | p = this.#init(); 100 | if (!p) { 101 | return this; 102 | } 103 | } 104 | const bitmap = this.#bmp; 105 | const v = roaringWasm._roaring_iterator_js_gte(p, bitmap!._p, bitmap!.v, minimumValue); 106 | if (v < 0) { 107 | this.#end(); 108 | } else { 109 | this.#p = p; 110 | const r = this.#r; 111 | r.value = v; 112 | r.done = false; 113 | } 114 | return this; 115 | } 116 | 117 | public dispose(): boolean { 118 | const ptr = this.#p; 119 | if (ptr) { 120 | roaringWasm._free(ptr); 121 | } else if (ptr === false) { 122 | return false; 123 | } 124 | this.#end(); 125 | return true; 126 | } 127 | 128 | #init() { 129 | const r = this.#r; 130 | const bitmap = this.#bmp; 131 | const ptr = this.#p !== false && !!bitmap && (roaringWasm._roaring_iterator_js_new(bitmap._p, bitmap.v) || false); 132 | 133 | if (ptr) { 134 | const allocator = this.#alloc; 135 | if (allocator) { 136 | allocator.register(this); 137 | } 138 | const finalizationRegistry = _free_finalizationRegistry || _free_finalizationRegistry_init(); 139 | if (finalizationRegistry) { 140 | finalizationRegistry.register(this, this.#p as number, this); 141 | } 142 | r.done = false; 143 | } else { 144 | r.value = undefined; 145 | r.done = true; 146 | } 147 | this.#p = ptr; 148 | return ptr; 149 | } 150 | 151 | #end() { 152 | const r = this.#r; 153 | const alloc = this.#alloc; 154 | if (alloc) { 155 | alloc.unregister(this); 156 | } 157 | if (_free_finalizationRegistry && this.#p) { 158 | _free_finalizationRegistry.unregister(this); 159 | } 160 | this.#p = false; 161 | r.done = true; 162 | r.value = undefined; 163 | return r; 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/RoaringUint8Array.ts: -------------------------------------------------------------------------------- 1 | import type { IDisposable } from "./IDisposable"; 2 | import { _free_finalizationRegistry, _free_finalizationRegistry_init } from "./lib/free-finalization-registry"; 3 | import { _roaringArenaAllocator_head } from "./lib/roaring-arena-allocator-stack"; 4 | import { roaringWasm } from "./lib/roaring-wasm"; 5 | import type { RoaringArenaAllocator } from "./RoaringArenaAllocator"; 6 | 7 | /** 8 | * Array of bytes allocted directly in roaring library WASM memory. 9 | * Note: to release memory as soon as possible, you are responsible to free the allocated memory calling "dispose" method. 10 | */ 11 | export class RoaringUint8Array implements IDisposable { 12 | #p: number; 13 | #size: number; 14 | #alloc: RoaringArenaAllocator | null; 15 | 16 | /** 17 | * The length in bytes of the array. 18 | * For RoaringUint8Array it is equal to this.length 19 | */ 20 | public get byteLength(): number { 21 | return this.#size; 22 | } 23 | 24 | /** 25 | * Returns true if this object was deallocated. 26 | */ 27 | public get isDisposed(): boolean { 28 | return !this.#p; 29 | } 30 | 31 | /** 32 | * Allocates an array in the roaring WASM heap. 33 | * 34 | * Note: Memory is not garbage collected, you are responsible to free the allocated memory calling "dispose" method. 35 | * 36 | * If the parameter is a number, it creates a new uninitialized array of the given length. 37 | * If the parameter is an Iterable, it creates a copy of the given iterable. 38 | * 39 | * @param lengthOrArray - Length of the array to allocate or the array to copy 40 | */ 41 | public constructor( 42 | lengthOrArray: number | Iterable | ArrayLike | null | undefined = 0, 43 | arenaAllocator: RoaringArenaAllocator | null | undefined = _roaringArenaAllocator_head, 44 | ) { 45 | this.#p = 0; 46 | this.#size = 0; 47 | this.#alloc = arenaAllocator; 48 | 49 | if (lengthOrArray) { 50 | let length: number; 51 | if (typeof lengthOrArray === "number") { 52 | length = Math.ceil(lengthOrArray); 53 | } else if (lengthOrArray !== null && typeof lengthOrArray === "object") { 54 | length = (lengthOrArray as unknown as ArrayLike).length; 55 | if (typeof length !== "number") { 56 | const copy = new Uint8Array(lengthOrArray as Iterable); 57 | lengthOrArray = copy; 58 | length = copy.length; 59 | } 60 | } else { 61 | throw new TypeError("Invalid argument"); 62 | } 63 | 64 | if (length > 0) { 65 | length = Math.ceil(length); 66 | if (length >= 0x10000000) { 67 | throw new RangeError(`RoaringUint8Array too big, ${length} bytes`); 68 | } 69 | const pointer = roaringWasm._jsalloc_zero(length) >>> 0; 70 | if (!pointer) { 71 | throw new Error(`RoaringUint8Array failed to allocate ${length} bytes`); 72 | } 73 | 74 | this.#p = pointer; 75 | this.#size = length; 76 | 77 | const finalizationRegistry = _free_finalizationRegistry || _free_finalizationRegistry_init(); 78 | if (finalizationRegistry) { 79 | finalizationRegistry.register(this, pointer, this); 80 | } 81 | if (arenaAllocator) { 82 | arenaAllocator.register(this); 83 | } 84 | 85 | if (typeof lengthOrArray !== "number") { 86 | try { 87 | this.set(lengthOrArray as Iterable); 88 | } catch (error) { 89 | this.dispose(); 90 | throw error; 91 | } 92 | } 93 | } 94 | } 95 | } 96 | 97 | /** 98 | * Throws an error if the memory was freed. 99 | */ 100 | public throwIfDisposed(): void | never { 101 | if (this.isDisposed) { 102 | throw new TypeError("RoaringUint8Array is disposed"); 103 | } 104 | } 105 | 106 | /** 107 | * Frees the allocated memory. 108 | * Is safe to call this method more than once. 109 | * @returns True if memory gets freed during this call, false if not. 110 | */ 111 | public dispose(): boolean { 112 | const ptr = this.#p; 113 | if (ptr) { 114 | this.#p = 0; 115 | this.#size = 0; 116 | 117 | const allocator = this.#alloc; 118 | if (allocator) { 119 | this.#alloc = null; 120 | allocator.unregister(this); 121 | } 122 | if (_free_finalizationRegistry) { 123 | _free_finalizationRegistry.unregister(this); 124 | } 125 | roaringWasm._free(ptr); 126 | return true; 127 | } 128 | return false; 129 | } 130 | 131 | /** 132 | * Decreases the size of the allocated memory. 133 | * It does nothing if the new length is greater or equal to the current length. 134 | * If the new length is less than 1, it disposes the allocated memory. 135 | * NOTE: if the value is non zero, this does not reallocate the consumed memory, it just chances the reported size in byteLength and length properties. 136 | * @param newLength - The new length in bytes. 137 | * @returns True if the memory was shrunk, false if not. 138 | */ 139 | public shrink(newLength: number): boolean { 140 | if (Number.isNaN(newLength)) { 141 | return false; 142 | } 143 | if (newLength < 1) { 144 | return this.dispose(); 145 | } 146 | if (newLength >= this.#size) { 147 | return false; 148 | } 149 | this.#size = newLength >>> 0; 150 | return true; 151 | } 152 | 153 | /** 154 | * Writes the given array at the specified position 155 | * @param array - A typed or untyped array of values to set. 156 | * @param offset - The index in the current array at which the values are to be written. 157 | */ 158 | public set(array: ArrayLike | Iterable, offset: number = 0): this { 159 | if ((array as ArrayLike).length) { 160 | this.asTypedArray().set(array as ArrayLike, offset); 161 | } else { 162 | let typedArray: Uint8Array | undefined; 163 | for (const value of array as Iterable) { 164 | (typedArray || (typedArray = this.asTypedArray()))[offset++] = value; 165 | } 166 | } 167 | return this; 168 | } 169 | 170 | /** 171 | * Gets a new JS typed array instance that shares the memory used by this buffer. 172 | * Note that the buffer may point to an outdated WASM memory if the WASM allocated memory grows while using the returned buffer. 173 | * Use the returned array for short periods of time. 174 | * 175 | * @returns A new typed array that shares the memory with this array. 176 | */ 177 | public asTypedArray(): Uint8Array { 178 | const ptr = this.#p; 179 | return roaringWasm.HEAPU8.subarray(ptr, ptr + this.#size); 180 | } 181 | 182 | /** 183 | * Copies the content of this buffer to a typed array and returns it 184 | * 185 | * @param output - The typed array to copy to. If not provided, a new typed array is created. 186 | * @returns A typed array with the content of this buffer. It could be smaller than the buffer if the output array is smaller. 187 | */ 188 | public toTypedArray(output?: Uint8Array): Uint8Array { 189 | const ptr = this.#p; 190 | const size = this.#size; 191 | if (!output) { 192 | return roaringWasm.HEAPU8.slice(ptr, ptr + size); 193 | } 194 | let outlen = output.length; 195 | if (outlen > size) { 196 | outlen = size; 197 | output = output.subarray(0, size); 198 | } 199 | output.set(roaringWasm.HEAPU8.subarray(ptr, ptr + outlen)); 200 | return output; 201 | } 202 | 203 | /** 204 | * Returns a string representation of an array. 205 | */ 206 | public toString(): string { 207 | return this.asTypedArray().toString(); 208 | } 209 | 210 | /** 211 | * The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array. 212 | * Follows the specification for array.at(). 213 | * If the computed index is less than 0, or equal to length, undefined is returned. 214 | * @param index - Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if index < 0, index + array.length is accessed. 215 | * @returns The element in the array matching the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property. 216 | */ 217 | public at(index: number): number | undefined { 218 | const ptr = this.#p; 219 | const length = this.#size; 220 | if (index < 0) { 221 | index += length; 222 | } 223 | return ptr && index >= 0 && index < length ? roaringWasm.HEAPU8[(ptr + index) >>> 0] : undefined; 224 | } 225 | 226 | /** 227 | * Sets the value at the given index. 228 | * @param index - Zero-based index of the array element to be set, converted to an integer. Negative index counts back from the end of the array — if index < 0, index + array.length is accessed. 229 | * @param value - The value to set at the given index. 230 | * @returns True if the value was set, false if the index is out of bounds. 231 | */ 232 | public setAt(index: number, value: number): boolean { 233 | const ptr = this.#p; 234 | const length = this.#size; 235 | if (index < 0) { 236 | index += length; 237 | } 238 | if (ptr && index >= 0 && index < length) { 239 | roaringWasm.HEAPU8[(ptr + index) >>> 0] = value; 240 | return true; 241 | } 242 | return false; 243 | } 244 | 245 | /** 246 | * Internal property, do not use. 247 | * @internal 248 | */ 249 | get _p(): number { 250 | return this.#p; 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/cpp/global.h: -------------------------------------------------------------------------------- 1 | #ifndef __GLOBAL__H__ 2 | #define __GLOBAL__H__ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define CROARING_SILENT_BUILD 9 | 10 | // Optimization - disable IO and assertions 11 | 12 | #define printf(...) (0) 13 | #define fprintf(...) (0) 14 | #define assert(...) 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/cpp/roaring.c: -------------------------------------------------------------------------------- 1 | #include "global.h" 2 | 3 | #include 4 | 5 | #pragma clang diagnostic push 6 | #pragma clang diagnostic ignored "-Wunused-variable" 7 | #pragma clang diagnostic ignored "-Wunused-but-set-variable" 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #pragma clang diagnostic pop 31 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/enums.ts: -------------------------------------------------------------------------------- 1 | export enum SerializationFormat { 2 | /** 3 | * Stable Optimized non portable C/C++ format. Used by croaring. Can be smaller than the portable format. 4 | */ 5 | croaring = "croaring", 6 | 7 | /** 8 | * Stable Portable Java and Go format. 9 | */ 10 | portable = "portable", 11 | 12 | /** 13 | * Non portable C/C++ frozen format. 14 | * Is considered unsafe and unstable because the format might change at any new version. 15 | * Can be useful for temporary storage or for sending data over the network between similar machines. 16 | * If the content is corrupted when deserialized or when a frozen view is create, the behavior is undefined! 17 | * The application may crash, buffer overrun, could be a vector of attack! 18 | * 19 | * When this option is used in the serialize function, the new returned buffer (if no buffer was provided) will be aligned to a 32 bytes boundary. 20 | * This is required to create a frozen view with the method unsafeFrozenView. 21 | * 22 | */ 23 | unsafe_frozen_croaring = "unsafe_frozen_croaring", 24 | 25 | /** 26 | * A plain binary array of 32 bits integers in little endian format. 4 bytes per value. 27 | */ 28 | uint32_array = "uint32_array", 29 | } 30 | 31 | export type SerializationFormatType = 32 | | SerializationFormat 33 | | "croaring" 34 | | "portable" 35 | | "unsafe_frozen_croaring" 36 | | "uint32_array" 37 | | boolean; 38 | 39 | export enum DeserializationFormat { 40 | /** Stable Optimized non portable C/C++ format. Used by croaring. Can be smaller than the portable format. */ 41 | croaring = "croaring", 42 | 43 | /** Stable Portable Java and Go format. */ 44 | portable = "portable", 45 | 46 | /** 47 | * Non portable C/C++ frozen format. 48 | * Is considered unsafe and unstable because the format might change at any new version. 49 | * Can be useful for temporary storage or for sending data over the network between similar machines. 50 | * If the content is corrupted when loaded or the buffer is modified when a frozen view is create, the behavior is undefined! 51 | * The application may crash, buffer overrun, could be a vector of attack! 52 | */ 53 | unsafe_frozen_croaring = "unsafe_frozen_croaring", 54 | 55 | /** 56 | * Portable version of the frozen view, compatible with Go and Java. 57 | * Is considered unsafe and unstable because the format might change at any new version. 58 | * Can be useful for temporary storage or for sending data over the network between similar machines. 59 | * If the content is corrupted when loaded or the buffer is modified when a frozen view is create, the behavior is undefined! 60 | * The application may crash, buffer overrun, could be a vector of attack! 61 | */ 62 | unsafe_frozen_portable = "unsafe_frozen_portable", 63 | 64 | /** 65 | * A plain binary array of 32 bits integers in little endian format. 4 bytes per value. 66 | */ 67 | uint32_array = "uint32_array", 68 | } 69 | 70 | export type DeserializationFormatType = 71 | | DeserializationFormat 72 | | "croaring" 73 | | "portable" 74 | | "unsafe_frozen_croaring" 75 | | "unsafe_frozen_portable" 76 | | "uint32_array" 77 | | boolean; 78 | 79 | export type SerializationDeserializationFormatType = SerializationFormatType & DeserializationFormatType; 80 | 81 | export type SerializationDeserializationFormat = SerializationDeserializationFormatType; 82 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./enums"; 2 | 3 | export * from "./IDisposable"; 4 | 5 | export { roaringLibraryInitialize, roaringLibraryIsReady } from "./lib/roaring-wasm"; 6 | 7 | export { RoaringUint8Array } from "./RoaringUint8Array"; 8 | 9 | export { RoaringBitmap32 } from "./RoaringBitmap32"; 10 | 11 | export { RoaringBitmap32Iterator } from "./RoaringBitmap32Iterator"; 12 | 13 | export { RoaringArenaAllocator } from "./RoaringArenaAllocator"; 14 | 15 | export { type BasicTypedArray } from "./utils"; 16 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/lib/free-finalization-registry.ts: -------------------------------------------------------------------------------- 1 | import { roaringWasm } from "./roaring-wasm"; 2 | 3 | export let _free_finalizationRegistry: FinalizationRegistry | undefined; 4 | 5 | export const _free_finalizationRegistry_init = ( 6 | typeof FinalizationRegistry !== "undefined" 7 | ? () => { 8 | return (_free_finalizationRegistry = new FinalizationRegistry(roaringWasm._free)); 9 | } 10 | : () => {} 11 | ) as () => FinalizationRegistry | undefined; 12 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/lib/roaring-arena-allocator-stack.ts: -------------------------------------------------------------------------------- 1 | import type { RoaringArenaAllocator } from "../RoaringArenaAllocator"; 2 | 3 | export let _roaringArenaAllocator_head: RoaringArenaAllocator | null = null; 4 | 5 | let _stack: RoaringArenaAllocator[] | null = null; 6 | 7 | export const _roaringArenaAllocator_push = (allocator: RoaringArenaAllocator): unknown => 8 | (_stack || (_stack = [])).push((_roaringArenaAllocator_head = allocator)); 9 | 10 | export const _roaringArenaAllocator_pop = (allocator: RoaringArenaAllocator): void => { 11 | const stack = _stack!; 12 | if (_roaringArenaAllocator_head === allocator) { 13 | stack.pop(); 14 | _roaringArenaAllocator_head = stack[stack.length - 1] || null; 15 | } else { 16 | const index = stack.lastIndexOf(allocator); 17 | if (index >= 0) { 18 | stack.splice(index, 1); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/lib/roaring-wasm-module.d.ts: -------------------------------------------------------------------------------- 1 | declare const roaring_wasm_module_init: (Module?: any) => TModule | Promise; 2 | 3 | export default roaring_wasm_module_init; 4 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/lib/roaring-wasm.ts: -------------------------------------------------------------------------------- 1 | import roaring_wasm_module_init from "./roaring-wasm-module"; 2 | 3 | export type NullablePtr = number | false; 4 | 5 | export type WasmBool = number | boolean; 6 | 7 | export type Ptr = number; 8 | 9 | export type RoaringWasm = { 10 | readonly HEAP8: Int8Array; 11 | readonly HEAP16: Int16Array; 12 | readonly HEAP32: Int32Array; 13 | readonly HEAPU8: Uint8Array; 14 | readonly HEAPU16: Uint16Array; 15 | readonly HEAPU32: Uint32Array; 16 | readonly HEAPF32: Float32Array; 17 | readonly HEAPF64: Float64Array; 18 | 19 | _jsalloc_unsafe(size: number): Ptr; 20 | _jsalloc_zero(size: number): Ptr; 21 | _free(pointer: NullablePtr): void; 22 | _roaring_bitmap_create_js(): number; 23 | _roaring_bitmap_create_with_capacity(capacity: number): number; 24 | _roaring_bitmap_free(roaring: number): void; 25 | _roaring_bitmap_is_empty(roaring: number): WasmBool; 26 | _roaring_bitmap_add_checked(roaring: number, value: number): WasmBool; 27 | _roaring_bitmap_remove_checked(roaring: number, value: number): WasmBool; 28 | _roaring_bitmap_maximum(roaring: number): number; 29 | _roaring_bitmap_minimum(roaring: number): number; 30 | _roaring_bitmap_is_subset(roaring1: number, roaring2: number): WasmBool; 31 | _roaring_bitmap_is_strict_subset(roaring1: number, roaring2: number): WasmBool; 32 | _roaring_bitmap_to_uint32_array(roaring: number, arrayPtr: number): void; 33 | _roaring_bitmap_equals(roaring1: number, roaring2: number): WasmBool; 34 | _roaring_bitmap_optimize_js(roaring: NullablePtr): WasmBool; 35 | _roaring_bitmap_at_js(roaring: NullablePtr, index: number): number; 36 | _roaring_bitmap_select_js(roaring: NullablePtr, rank: number): number; 37 | _roaring_bitmap_get_index_js(roaring: NullablePtr, rank: number): number; 38 | _roaring_bitmap_and_cardinality(roaring1: number, roaring2: number): number; 39 | _roaring_bitmap_or_cardinality(roaring1: number, roaring2: number): number; 40 | _roaring_bitmap_andnot_cardinality(roaring1: number, roaring2: number): number; 41 | _roaring_bitmap_xor_cardinality(roaring1: number, roaring2: number): number; 42 | _roaring_bitmap_rank(roaring: number, value: number): number; 43 | _roaring_bitmap_and_inplace(roaring1: number, roaring2: number): void; 44 | _roaring_bitmap_or_inplace(roaring1: number, roaring2: number): void; 45 | _roaring_bitmap_xor_inplace(roaring1: number, roaring2: number): void; 46 | _roaring_bitmap_andnot_inplace(roaring1: number, roaring2: number): void; 47 | _roaring_bitmap_intersect(roaring1: number, roaring2: number): WasmBool; 48 | _roaring_bitmap_jaccard_index_js(roaring1: NullablePtr, roaring2: NullablePtr): number; 49 | _roaring_bitmap_add_many(roaring: number, size: number, uint32Array: number): void; 50 | 51 | _roaring_bitmap_portable_size_in_bytes(roaring: number): number; 52 | _roaring_bitmap_frozen_size_in_bytes(roaring: number): number; 53 | _roaring_bitmap_portable_serialize(roaring: number, buf: number): number; 54 | _roaring_bitmap_frozen_serialize(roaring: number, buf: number): number; 55 | _roaring_bitmap_portable_deserialize_safe(buf: number, maxBytes: number): number; 56 | _roaring_bitmap_frozen_view(buf: number, size: number): number; 57 | _roaring_bitmap_portable_deserialize_frozen(buf: number, maxBytes: number): number; 58 | 59 | _roaring_bitmap_size_in_bytes(roaring: number): number; 60 | _roaring_bitmap_serialize(roaring: number, buf: number): number; 61 | _roaring_bitmap_deserialize_safe(buf: number, maxBytes: number): number; 62 | 63 | _roaring_bitmap_get_cardinality_js(roaring: NullablePtr): number; 64 | _roaring_bitmap_from_range_js(min: number, max: number, step: number): number; 65 | _roaring_bitmap_contains_range_js(roaring: NullablePtr, min: number, max: number): WasmBool; 66 | _roaring_bitmap_add_range_js(roaring: number, min: number, max: number): WasmBool; 67 | _roaring_bitmap_remove_range_js(roaring: NullablePtr, min: number, max: number): WasmBool; 68 | _roaring_bitmap_flip_range_inplace_js(roaring: number, start: number, end: number): WasmBool; 69 | _roaring_bitmap_range_cardinality_js(roaring: NullablePtr, start: number, end: number): number; 70 | _roaring_bitmap_add_offset_js(roaring: NullablePtr, offset: number): number; 71 | _roaring_bitmap_copy(roaring: number): number; 72 | _roaring_bitmap_overwrite(roaring: number, other: number): void; 73 | _roaring_bitmap_run_optimize(roaring: number): WasmBool; 74 | _roaring_bitmap_shrink_to_fit_js(roaring: NullablePtr): number; 75 | _roaring_bitmap_remove_run_compression(roaring: number): WasmBool; 76 | _roaring_bitmap_flip_range_static_js(roaring: NullablePtr, start: number, end: number): number; 77 | _roaring_bitmap_and_js(roaring1: NullablePtr, roaring2: NullablePtr): number; 78 | _roaring_bitmap_or_js(roaring1: NullablePtr, roaring2: NullablePtr): number; 79 | _roaring_bitmap_xor_js(roaring1: NullablePtr, roaring2: NullablePtr): number; 80 | _roaring_bitmap_andnot_js(roaring1: NullablePtr, roaring2: NullablePtr): number; 81 | _roaring_bitmap_or_many(count: number, bitmapsPtrs: number): number; 82 | _roaring_bitmap_or_many_heap(count: number, bitmapsPtrs: number): number; 83 | _roaring_bitmap_xor_many(count: number, bitmapsPtrs: number): number; 84 | _roaring_bitmap_intersect_with_range_js(bitmap: NullablePtr, rangeStart: number, rangeEnd: number): WasmBool; 85 | 86 | _roaring_iterator_js_new(roaring: NullablePtr, version: number): number; 87 | _roaring_iterator_js_clone(iterator: number): number; 88 | _roaring_iterator_js_next(iterator: number, bitmap: NullablePtr, version: number): number; 89 | _roaring_iterator_js_gte(iterator: number, bitmap: NullablePtr, version: number, minimumValue: number): number; 90 | 91 | _roaring_sync_iter_init(bitmap: NullablePtr, maxLength: number): number; 92 | _roaring_sync_iter_next(): number; 93 | _roaring_sync_iter_min(minimumValue: number): number; 94 | 95 | _roaring_sync_bulk_add_init(bitmap: NullablePtr): number; 96 | _roaring_sync_bulk_add_chunk(chunkSize: number): void; 97 | 98 | _roaring_sync_bulk_remove_init(bitmap: NullablePtr): number; 99 | _roaring_sync_bulk_remove_chunk(chunkSize: number): void; 100 | _roaring_bitmap_remove_many(roaring: number, count: number, valuesPtr: number): void; 101 | _roaring_bitmap_has_js(roaring: NullablePtr, value: number): WasmBool; 102 | }; 103 | 104 | const _loadedModule = roaring_wasm_module_init(); 105 | let _initializePromise: Promise; 106 | 107 | export let roaringWasm: RoaringWasm; 108 | 109 | /** 110 | * In browser, roaring library initialization is done asynchronously, this method returns true after roaring library WASM is initialized. 111 | * The library cannot be used until this function returns true. 112 | * You can await initialization with roaringLibraryInitialize function that returns a promise. 113 | * @returns true if roaring library WASM is initialized. 114 | */ 115 | export const roaringLibraryIsReady = (): boolean => !!roaringWasm; 116 | 117 | /** 118 | * In browser, roaring library initialization is done asynchronously, this method returns a promise that resolves when roaring library WASM is initialized. 119 | * The library cannot be used until this promise is resolved. 120 | * @returns a promise that resolves when roaring library WASM is initialized. 121 | * @example 122 | * await roaringLibraryInitialize(); 123 | * const bitmap = new RoaringBitmap32([123]); 124 | * console.log(bitmap.toArray()); // [123] 125 | */ 126 | export const roaringLibraryInitialize = (): Promise => _initializePromise; 127 | 128 | if (typeof (_loadedModule as { then?: unknown }).then === "function") { 129 | _initializePromise = (_loadedModule as Promise).then((m) => { 130 | roaringWasm = m; 131 | }); 132 | } else { 133 | roaringWasm = _loadedModule as RoaringWasm; 134 | _initializePromise = Promise.resolve(); 135 | } 136 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "roaring-wasm-src", 3 | "private": true, 4 | "version": "0.0.0", 5 | "description": "source code for roaring-wasm package", 6 | "author": "Salvatore Previti", 7 | "license": "Apache-2.0", 8 | "homepage": "https://github.com/SalvatorePreviti/roaring-wasm", 9 | "bugs": { 10 | "url": "https://github.com/SalvatorePreviti/roaring-wasm/issues" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "\"git+https://github.com/SalvatorePreviti/roaring-wasm.git\"" 15 | }, 16 | "engines": { 17 | "node": ">=14" 18 | }, 19 | "browser": { 20 | "./lib/roaring-wasm-module/index.js": "./lib/roaring-wasm-module/index.browser.mjs" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": { 4 | "declaration": true, 5 | "stripInternal": true, 6 | "allowJs": false, 7 | "noEmit": true 8 | }, 9 | "include": ["."], 10 | "exclude": ["node_modules/**/*"] 11 | } 12 | -------------------------------------------------------------------------------- /packages/roaring-wasm-src/utils.ts: -------------------------------------------------------------------------------- 1 | export type BasicTypedArray = 2 | | Int8Array 3 | | Uint8ClampedArray 4 | | Uint8Array 5 | | Int16Array 6 | | Uint16Array 7 | | Int32Array 8 | | Uint32Array 9 | | Float32Array 10 | | Float64Array; 11 | -------------------------------------------------------------------------------- /packages/roaring-wasm/.npmignore: -------------------------------------------------------------------------------- 1 | tsconfig*.json 2 | tsconfig.json 3 | 4 | # excluded files for security 5 | .npmrc 6 | .env 7 | .env.test 8 | *.pem 9 | 10 | # test files 11 | *.test.* 12 | *.spec.* 13 | **/test/**/* 14 | **/tests/**/* 15 | **/*-test/**/* 16 | **/*-tests/**/* 17 | **/__mocks__/**/* 18 | **/__specs__/**/* 19 | **/__tests__/**/* 20 | **/__mock__/**/* 21 | **/__spec__/**/* 22 | **/__test__/**/* 23 | **/.mocharc.* 24 | 25 | # CI 26 | CI/ 27 | Jenkinsfile 28 | .gitignore 29 | .travis.* 30 | .nvmrc 31 | .github 32 | 33 | # Diagnostic reports (https://nodejs.org/api/report.html) 34 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 35 | 36 | # Dependency directories 37 | bower_components 38 | node_modules 39 | jspm_packages 40 | /.pnp 41 | .pnp.js 42 | 43 | # Build outputs 44 | .serverless 45 | .webpack 46 | /build 47 | /out/ 48 | .next/ 49 | build/Release 50 | build/Debug 51 | *.tgz 52 | *.tmp-browserify-* 53 | ipch 54 | 55 | # Go 56 | goMakeIt 57 | *.iml 58 | 59 | # Binaries for programs and plugins 60 | *.exe 61 | *.exe~ 62 | *.dll 63 | *.so 64 | *.dylib 65 | 66 | # Output of the go coverage tool, specifically when used with LiteIDE 67 | *.out 68 | 69 | # logs 70 | logs 71 | *.log 72 | lerna-debug.log* 73 | 74 | # Cache and lockfiles 75 | .clangd 76 | .cache 77 | .fuse_hidden* 78 | .fusebox 79 | .dynamodb 80 | tsbuildinfo 81 | *.tsbuildinfo 82 | .npm 83 | .history 84 | .node_repl_history 85 | .yarn-integrity 86 | .grunt 87 | .lock-wscript 88 | pids 89 | *.pid 90 | *.seed 91 | *.pid.lock 92 | .eslintcache 93 | .prettiercache 94 | .git 95 | .tmp 96 | .temp 97 | .cache 98 | .fuse_hidden* 99 | 100 | # Test coverage 101 | lib-cov 102 | coverage 103 | .nyc_output 104 | *.lcov 105 | 106 | # IDEs and OS 107 | .idea 108 | .DocumentRevisions-V100 109 | .fseventsd 110 | .Spotlight-V100 111 | .TemporaryItems 112 | .Trashes 113 | .Trash-* 114 | .VolumeIcon.icns 115 | .com.apple.timemachine.donotpresent 116 | .AppleDouble 117 | .LSOverride 118 | .apdisk 119 | .AppleDB 120 | .AppleDesktop 121 | Network Trash Folder 122 | Temporary Items 123 | Thumbs.db 124 | Thumbs.db:encryptable 125 | ehthumbs.db 126 | ehthumbs_vista.db 127 | *.stackdump 128 | [Dd]esktop.ini 129 | $RECYCLE.BIN 130 | *.lnk 131 | .DS_Store 132 | 133 | # debug 134 | npm-debug.log* 135 | yarn-debug.log* 136 | yarn-error.log* 137 | 138 | # local env files 139 | .env.local 140 | .env.development.local 141 | .env.test.local 142 | .env.production.local 143 | 144 | # vercel 145 | .vercel 146 | -------------------------------------------------------------------------------- /packages/roaring-wasm/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /packages/roaring-wasm/README.md: -------------------------------------------------------------------------------- 1 | # roaring-wasm 2 | 3 | WebAssembly port of [Roaring Bitmaps](http://roaringbitmap.org) for Node, Browser and Deno. 4 | It is interoperable with other implementations via the [Roaring format](https://github.com/RoaringBitmap/RoaringFormatSpec/). 5 | 6 | Roaring bitmaps are compressed bitmaps. They can be hundreds of times faster. 7 | 8 | ## NOTE 9 | 10 | This package is intended as a stripped down cross platform and broewser alternative to [roaring-node](https://www.npmjs.com/package/roaring), [repository](https://github.com/SalvatorePreviti/roaring-node). 11 | If you are using just NodeJS, [roaring-node](https://github.com/SalvatorePreviti/roaring-node) is faster, has a better API that fully leverages the v8 garbage collector and the native CPU SIMD instructions, and has also asynchronous operations. 12 | 13 | # WARNING ⚠️ - breaking API changes introduced in version 1.0.0 14 | 15 | Please update your codebase accordingly. 16 | 17 | - remove cardinality() method, replaced with "size" property 18 | - convert method isEmpty() to a property isEmpty: boolean 19 | - serialize and deserialize now require a format argument 20 | - removed RoaringUint32Array - since we have "streaming" functions now that copy chunks data in chunks between JS 21 | - removed some utility methods 22 | - removed usage of Node buffer 23 | 24 | ## installation 25 | 26 | ```sh 27 | npm install --save roaring-wasm 28 | ``` 29 | 30 | Try it live - 31 | 32 | Code sample: 33 | 34 | ```javascript 35 | // npm install --save roaring-wasm 36 | // create this file as demo.js 37 | // type node demo.js or nodejs demo.js depending on your system 38 | 39 | import { RoaringBitmap32, roaringLibraryInitialize } from "roaring-wasm"; 40 | 41 | // This is needed in browser (and in this case we are using top level await), in nodejs this is not required. 42 | await roaringLibraryInitialize(); 43 | 44 | var bitmap1 = new RoaringBitmap32(); 45 | bitmap1.addMany([1, 2, 3, 4, 5, 100, 1000]); 46 | console.log("bitmap1.toSet():", bitmap1.toSet()); 47 | 48 | var bitmap2 = new RoaringBitmap32(); 49 | bitmap2.addMany([3, 4, 1000]); 50 | console.log("bitmap2.toSet():", bitmap1.toSet()); 51 | 52 | var bitmap3 = new RoaringBitmap32(); 53 | console.log("bitmap1.size:", bitmap1.size); 54 | console.log("bitmap2.has(3):", bitmap2.has(3)); 55 | 56 | bitmap3.add(111); 57 | bitmap3.add(544); 58 | bitmap3.orInPlace(bitmap1); 59 | bitmap1.optimize(); 60 | console.log(bitmap3.toString()); 61 | 62 | console.log("bitmap3.toArray():", bitmap3.toArray()); 63 | console.log("bitmap3.maximum():", bitmap3.maximum()); 64 | console.log("bitmap3.rank(100):", bitmap3.rank(100)); 65 | 66 | bitmap1.dispose(); 67 | bitmap2.dispose(); 68 | bitmap3.dispose(); 69 | ``` 70 | 71 | ## Documentation 72 | 73 | [https://salvatorepreviti.github.io/roaring-wasm](https://salvatorepreviti.github.io/roaring-wasm/modules.html) 74 | 75 | ## References 76 | 77 | - [roaring for NodeJS](https://www.npmjs.com/package/roaring), [repository](https://github.com/SalvatorePreviti/roaring-node) 78 | 79 | - This package - 80 | 81 | - Source code and build tools for this package - 82 | 83 | - Roaring Bitmaps - 84 | 85 | - Portable Roaring bitmaps in C - 86 | 87 | - emscripten - 88 | 89 | # Licenses 90 | 91 | - This package is provided as open source software using Apache License. 92 | 93 | - CRoaring is provided as open source software using Apache License. 94 | 95 | # API 96 | 97 | See the [roaring module documentation](https://salvatorepreviti.github.io/roaring-wasm/modules.html) 98 | 99 | # Other 100 | 101 | Wanna play an open source game made by the author of this library? Try [Dante](https://github.com/SalvatorePreviti/js13k-2022) 102 | 103 | # Development, local building 104 | 105 | This project requires emsdk installed and activated. See . 106 | 107 | On mac you can install emscripten with homebrew: 108 | 109 | ``` 110 | brew install emscripten 111 | ``` 112 | 113 | To download the repository: 114 | 115 | ``` 116 | git clone https://github.com/SalvatorePreviti/roaring-wasm.git 117 | 118 | cd roaring-wasm 119 | 120 | git submodule update --init --recursive 121 | 122 | npm install 123 | ``` 124 | 125 | To compile and run test 126 | 127 | ``` 128 | npm run build 129 | ``` 130 | 131 | Output will be generated in the `packages/roaring-wasm` folder 132 | 133 | The build system was tried on Linux and MacOSX, is not tested/maintained for other system or Windows. 134 | -------------------------------------------------------------------------------- /packages/roaring-wasm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "roaring-wasm", 3 | "version": "1.1.0", 4 | "description": "WebAssembly port of Roaring Bitmaps for NodeJS", 5 | "author": "Salvatore Previti", 6 | "license": "Apache-2.0", 7 | "homepage": "https://github.com/SalvatorePreviti/roaring-wasm", 8 | "keywords": [ 9 | "roaring", 10 | "CRoaring", 11 | "WASM", 12 | "WebAssembly" 13 | ], 14 | "bugs": { 15 | "url": "https://github.com/SalvatorePreviti/roaring-wasm/issues" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "\"git+https://github.com/SalvatorePreviti/roaring-wasm.git\"" 20 | }, 21 | "types": "index.d.ts", 22 | "engines": { 23 | "node": ">=14" 24 | }, 25 | "sideEffects": false, 26 | "type": "commonjs", 27 | "main": "index.js", 28 | "typings": "./index.d.ts", 29 | "browser": { 30 | ".": "./browser/index.mjs", 31 | "./index": "./browser/index.mjs", 32 | "./index.js": "./browser/index.mjs", 33 | "./index.mjs": "./browser/index.mjs", 34 | "./index.wasm": "./index.wasm", 35 | "./package.json": "./package.json", 36 | "./browser": "./browser/index.mjs", 37 | "./browser/index": "./browser/index.mjs", 38 | "./browser/index.js": "./browser/index.mjs", 39 | "./browser/index.mjs": "./browser/index.mjs", 40 | "./browser/index.wasm": "./index.wasm", 41 | "./browser/package.json": "./package.json" 42 | }, 43 | "exports": { 44 | "./index.wasm": "./index.wasm", 45 | "./index.cjs": "./index.js", 46 | ".": { 47 | "types": "./index.d.ts", 48 | "browser": "./browser/index.mjs", 49 | "deno": "./browser/index.mjs", 50 | "default": "./index.js" 51 | }, 52 | "./index": { 53 | "types": "./index.d.ts", 54 | "browser": "./browser/index.mjs", 55 | "deno": "./browser/index.mjs", 56 | "default": "./index.js" 57 | }, 58 | "./index.js": { 59 | "types": "./index.d.ts", 60 | "browser": "./browser/index.mjs", 61 | "deno": "./browser/index.mjs", 62 | "default": "./index.js" 63 | }, 64 | "./browser": "./browser/index.mjs", 65 | "./browser/index": "./browser/index.mjs", 66 | "./browser/index.js": "./browser/index.mjs", 67 | "./browser/index.mjs": "./browser/index.mjs", 68 | "./browser/index.wasm": "./index.wasm", 69 | "./package.json": "./package.json" 70 | }, 71 | "scripts": { 72 | "prepack": "node ../../scripts/test.js --test-package" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /packages/roaring-wasm/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": {}, 4 | "include": ["index.d.ts"], 5 | "exclude": ["node_modules/**/*"] 6 | } 7 | -------------------------------------------------------------------------------- /playwright.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig, devices } from "@playwright/test"; 2 | 3 | /** 4 | * Read environment variables from file. 5 | * https://github.com/motdotla/dotenv 6 | */ 7 | // require('dotenv').config(); 8 | 9 | /** 10 | * See https://playwright.dev/docs/test-configuration. 11 | */ 12 | export default defineConfig({ 13 | testDir: "./test/playwright", 14 | /* Run tests in files in parallel */ 15 | fullyParallel: true, 16 | /* Fail the build on CI if you accidentally left test.only in the source code. */ 17 | forbidOnly: !!process.env.CI, 18 | /* Retry on CI only */ 19 | retries: process.env.CI ? 2 : 0, 20 | /* Opt out of parallel tests on CI. */ 21 | workers: process.env.CI ? 1 : undefined, 22 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */ 23 | reporter: "html", 24 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ 25 | use: { 26 | /* Base URL to use in actions like `await page.goto('/')`. */ 27 | // baseURL: 'http://127.0.0.1:3000', 28 | 29 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ 30 | trace: "on-first-retry", 31 | }, 32 | 33 | /* Configure projects for major browsers */ 34 | projects: [ 35 | { name: "chromium", use: { ...devices["Desktop Chrome"] } }, 36 | { name: "firefox", use: { ...devices["Desktop Firefox"] } }, 37 | { name: "webkit", use: { ...devices["Desktop Safari"] } }, 38 | ], 39 | 40 | /* Run your local dev server before starting the tests */ 41 | webServer: { 42 | command: "npm run web-app", 43 | reuseExistingServer: !process.env.CI, 44 | port: 3000, 45 | stderr: "pipe", 46 | stdout: "pipe", 47 | }, 48 | }); 49 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - "packages/*" 3 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { timed, runMain } = require("./lib/utils"); 4 | const { compileWasm } = require("./compile-wasm"); 5 | const { compileTs } = require("./compile-ts"); 6 | const { test } = require("./test"); 7 | 8 | async function build() { 9 | await timed("compileWasm", compileWasm); 10 | await timed("compileTs", compileTs); 11 | await timed("test", () => test(["--test-package"])); 12 | } 13 | 14 | module.exports = { build }; 15 | 16 | if (require.main === module) { 17 | runMain(build); 18 | } 19 | -------------------------------------------------------------------------------- /scripts/clean.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { colors, runMain, removeTrailingSlash } = require("./lib/utils"); 4 | const { 5 | ROOT_FOLDER, 6 | ROARING_WASM_OUT_FOLDER, 7 | ROARING_WASM_EMCC_BUILD_FOLDER, 8 | ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, 9 | } = require("./config/paths"); 10 | 11 | const fs = require("fs"); 12 | const globby = require("fast-glob"); 13 | 14 | async function cleanDistFiles() { 15 | const distFiles = await globby([`${removeTrailingSlash(ROARING_WASM_OUT_FOLDER)}/**/*.{js,mjs,cjs,ts,wasm}`], { 16 | ignore: ["**/node_modules/**"], 17 | cwd: ROOT_FOLDER, 18 | onlyFiles: true, 19 | }); 20 | 21 | let deletedFiles = 0; 22 | 23 | const deleteFile = (file) => 24 | fs.promises 25 | .unlink(file) 26 | .then(() => ++deletedFiles) 27 | .catch(() => {}); 28 | 29 | const promises = []; 30 | for (const file of distFiles) { 31 | promises.push(deleteFile(file)); 32 | } 33 | 34 | await Promise.all(promises); 35 | 36 | if (deletedFiles) { 37 | console.log(colors.yellow(`• cleaned ${deletedFiles} dist files`)); 38 | } 39 | 40 | return deletedFiles; 41 | } 42 | 43 | async function clean() { 44 | console.log(); 45 | const promises = []; 46 | 47 | let deletedDirectories = 0; 48 | 49 | const deleteDir = (dir) => 50 | fs.promises 51 | .rm(dir, { force: true, recursive: true }) 52 | .then(() => ++deletedDirectories) 53 | .catch(() => {}); 54 | 55 | promises.push(cleanDistFiles()); 56 | promises.push(deleteDir(ROARING_WASM_EMCC_BUILD_FOLDER)); 57 | promises.push(deleteDir(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER)); 58 | 59 | await Promise.all(promises); 60 | 61 | if (deletedDirectories) { 62 | console.log(colors.yellow(`• cleaned ${deletedDirectories} build directories`)); 63 | } 64 | console.log(); 65 | } 66 | 67 | module.exports = { cleanDistFiles, clean }; 68 | 69 | if (require.main === module) { 70 | runMain(clean); 71 | } 72 | -------------------------------------------------------------------------------- /scripts/compile-ts.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { timed, runMain, getFileSizesAsync, colors, removeTrailingSlash } = require("./lib/utils"); 4 | const { 5 | ROARING_WASM_SRC_FOLDER, 6 | ROARING_WASM_OUT_FOLDER, 7 | ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, 8 | ROOT_FOLDER, 9 | } = require("./config/paths"); 10 | const path = require("path"); 11 | const terserConfig = require("./config/terser-config"); 12 | const fs = require("fs"); 13 | const fastGlob = require("fast-glob"); 14 | const prettier = require("prettier"); 15 | const { cleanDistFiles } = require("./clean"); 16 | 17 | const { build: tsupBuild } = require("tsup"); 18 | 19 | async function compileTs() { 20 | const outFastGlobOptions = { cwd: ROOT_FOLDER, ignore: ["**/node_modules/**"], onlyFiles: true }; 21 | 22 | await cleanDistFiles(); 23 | 24 | /** @type {import('tsup').Options} */ 25 | const commonTsupOptions = { 26 | entry: [path.resolve(ROARING_WASM_SRC_FOLDER, "index.ts")], 27 | splitting: false, 28 | sourcemap: false, 29 | clean: false, 30 | config: false, 31 | treeshake: true, 32 | minify: "terser", 33 | terserOptions: terserConfig, 34 | minifySyntax: true, 35 | target: "es2022", 36 | }; 37 | 38 | const tsupNode = () => 39 | timed("tsup node", async () => { 40 | await tsupBuild({ 41 | ...commonTsupOptions, 42 | outDir: ROARING_WASM_OUT_FOLDER, 43 | module: "mjs", 44 | format: "cjs", 45 | dts: true, 46 | skipNodeModulesBundle: true, 47 | platform: "node", 48 | }); 49 | }); 50 | 51 | const tsupBrowser = () => 52 | timed("tsup browser", async () => { 53 | await tsupBuild({ 54 | ...commonTsupOptions, 55 | outDir: path.resolve(ROARING_WASM_OUT_FOLDER, "browser"), 56 | platform: "browser", 57 | module: "esm", 58 | format: "es", 59 | dts: false, 60 | skipNodeModulesBundle: false, 61 | esbuildPlugins: [ 62 | { 63 | name: "import wasm module", 64 | setup(build) { 65 | build.onResolve({ filter: /roaring-wasm-module[/\\]?$/i }, (args) => { 66 | return { path: path.resolve(args.resolveDir, args.path, "index.browser.mjs") }; 67 | }); 68 | }, 69 | }, 70 | ], 71 | }); 72 | 73 | await fs.promises.rename( 74 | path.resolve(ROARING_WASM_OUT_FOLDER, "browser/index.js"), 75 | path.resolve(ROARING_WASM_OUT_FOLDER, "browser/index.mjs"), 76 | ); 77 | }); 78 | 79 | await Promise.all([tsupNode(), tsupBrowser()]); 80 | 81 | // Run prettier on the output folder 82 | 83 | await timed("prettier", async () => { 84 | const files = await fastGlob([`${removeTrailingSlash(ROARING_WASM_OUT_FOLDER)}/**/*.{js,mjs,cjs,ts}`], { 85 | ...outFastGlobOptions, 86 | absolute: true, 87 | }); 88 | await Promise.all( 89 | files.map(async (file) => { 90 | const content = await fs.promises.readFile(file, "utf-8"); 91 | const fcontent = await prettier.format(content, { 92 | filepath: file, 93 | parser: file.endsWith(".ts") ? "typescript" : "espree", 94 | }); 95 | if (fcontent !== content) { 96 | await fs.promises.writeFile(file, fcontent); 97 | } 98 | }), 99 | ); 100 | }); 101 | 102 | const copyWasmFile = () => { 103 | return fs.promises.copyFile( 104 | path.resolve(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, "index.wasm"), 105 | path.resolve(ROARING_WASM_OUT_FOLDER, "index.wasm"), 106 | ); 107 | }; 108 | 109 | const copyIndexDTsToBrowser = () => 110 | fs.promises.copyFile( 111 | path.resolve(ROARING_WASM_OUT_FOLDER, "index.d.ts"), 112 | path.resolve(ROARING_WASM_OUT_FOLDER, "browser/index.d.ts"), 113 | ); 114 | 115 | await Promise.all([copyWasmFile(), copyIndexDTsToBrowser()]); 116 | 117 | // Print file sizes 118 | 119 | console.log(); 120 | for (const f of await getFileSizesAsync( 121 | [`${removeTrailingSlash(ROARING_WASM_OUT_FOLDER)}/**/*.{js,mjs,cjs,ts,wasm}`], 122 | outFastGlobOptions, 123 | )) { 124 | console.log(`${colors.magentaBright("•")} ${colors.green(f.path)} ${colors.cyanBright(`${f.sizeString}`)}`); 125 | } 126 | console.log(); 127 | } 128 | 129 | module.exports = { compileTs }; 130 | 131 | if (require.main === module) { 132 | runMain(compileTs); 133 | } 134 | -------------------------------------------------------------------------------- /scripts/compile-wasm.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const path = require("path"); 4 | const fs = require("fs"); 5 | const fastGlob = require("fast-glob"); 6 | const prettier = require("prettier"); 7 | const exportedFunctions = require("./config/exportedFunctions"); 8 | const { 9 | colors, 10 | getFileSizesAsync, 11 | spawnAsync, 12 | timed, 13 | executablePathFromEnv, 14 | runMain, 15 | prettyElapsedTime, 16 | removeTrailingSlash, 17 | } = require("./lib/utils"); 18 | const { 19 | ROARING_WASM_CPP_SRC_FOLDER, 20 | ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, 21 | ROARING_WASM_EMCC_BUILD_FOLDER, 22 | ROOT_FOLDER, 23 | } = require("./config/paths"); 24 | 25 | function buildLinkArgs(environment) { 26 | const linkargs = []; 27 | 28 | // see https://github.com/kripken/emscripten/blob/master/src/settings.js 29 | 30 | if (environment === "browser") { 31 | linkargs.push("-s", "SINGLE_FILE"); 32 | } 33 | 34 | linkargs.push("-s", `EXPORTED_FUNCTIONS=${JSON.stringify(exportedFunctions)}`); 35 | linkargs.push("-s", "INCOMING_MODULE_JS_API=[]"); 36 | 37 | linkargs.push("-s", `WASM_ASYNC_COMPILATION=${environment === "browser" ? "1" : "0"}`); 38 | 39 | linkargs.push("-s", "ALLOW_MEMORY_GROWTH=1"); 40 | linkargs.push("-s", "DISABLE_EXCEPTION_CATCHING=1"); 41 | linkargs.push("-s", "INVOKE_RUN=1"); 42 | linkargs.push("-s", "MODULARIZE=1"); 43 | linkargs.push("-s", "FILESYSTEM=0"); 44 | linkargs.push("-s", "EXIT_RUNTIME=0"); 45 | linkargs.push("-s", "FILESYSTEM=0"); 46 | linkargs.push("-s", "NODEJS_CATCH_EXIT=0"); 47 | linkargs.push("-s", "NODEJS_CATCH_REJECTION=0"); 48 | linkargs.push("-s", "ABORTING_MALLOC=0"); 49 | linkargs.push("-s", "SUPPORT_LONGJMP=0"); 50 | linkargs.push("-s", "EXPORT_NAME=roaring_wasm"); 51 | linkargs.push("-s", "MIN_NODE_VERSION=160000"); 52 | linkargs.push("-s", `ENVIRONMENT=${environment === "browser" ? "web,worker" : "node"}`); 53 | 54 | linkargs.push("-s", "ASSERTIONS"); // useful when debugging 55 | 56 | if (environment === "browser") { 57 | linkargs.push("-s", "USE_ES6_IMPORT_META=0"); 58 | } 59 | 60 | // optimizations 61 | linkargs.push("-s", "EVAL_CTORS=2"); 62 | linkargs.push("-s", "AGGRESSIVE_VARIABLE_ELIMINATION=1"); 63 | linkargs.push("-s", "ASSERTIONS=0"); 64 | 65 | // optimizations 66 | linkargs.push("-flto=full"); 67 | linkargs.push("-ffast-math"); 68 | linkargs.push("-fno-exceptions"); 69 | 70 | // js settings 71 | linkargs.push("--output_eol", "linux"); 72 | linkargs.push("--closure", "0"); 73 | 74 | return linkargs; 75 | } 76 | 77 | async function compileWasm() { 78 | process.chdir(ROOT_FOLDER); 79 | 80 | const emccPath = executablePathFromEnv("EMSCRIPTEN", null, "emcc"); 81 | 82 | const emccFlags = []; 83 | emccFlags.push(`-I${ROOT_FOLDER}`); 84 | emccFlags.push("-Isubmodules/CRoaring/include"); 85 | emccFlags.push("-O3"); 86 | emccFlags.push("-g0"); 87 | emccFlags.push("-msimd128"); 88 | emccFlags.push("-mfpu=neon"); 89 | emccFlags.push("-DCROARING_USENEON"); 90 | emccFlags.push("-DSIMDE_NO_CONVERT_VECTOR"); 91 | 92 | const cflags = []; 93 | cflags.push("-O3"); 94 | cflags.push("-Wall"); 95 | cflags.push("-Wno-error=unused-local-typedefs"); 96 | cflags.push("-flto=full"); 97 | cflags.push("-ffast-math"); 98 | cflags.push("-fno-exceptions"); 99 | 100 | const emccSpawnOptions = { 101 | cwd: ROOT_FOLDER, 102 | env: { 103 | ...process.env, 104 | NODE_JS: process.execPath, 105 | EMCC_CFLAGS: `${cflags.join(" ")} ${process.env.EMCC_CFLAGS || ""}`, 106 | EMMAKEN_CXXFLAGS: `${cflags.join(" ")} ${process.env.EMMAKEN_CXXFLAGS || ""}`, 107 | }, 108 | }; 109 | 110 | await fs.promises.rm(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, { recursive: true, force: true }); 111 | 112 | await Promise.all([ 113 | fs.promises.mkdir(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, { recursive: true }), 114 | fs.promises.mkdir(ROARING_WASM_EMCC_BUILD_FOLDER, { recursive: true }), 115 | ]); 116 | 117 | const oFiles = []; 118 | const srcFiles = await fastGlob([`${removeTrailingSlash(ROARING_WASM_CPP_SRC_FOLDER)}/**/*.{c,cpp}`], { 119 | onlyFiles: true, 120 | cwd: ROOT_FOLDER, 121 | }); 122 | 123 | const compileObjectFile = async (file) => { 124 | const start = performance.now(); 125 | let ofile = path.relative(ROARING_WASM_CPP_SRC_FOLDER, file); 126 | ofile = path.join("build", "emcc", `${ofile.slice(0, ofile.lastIndexOf("."))}.o`); 127 | oFiles.push(ofile); 128 | await spawnAsync(emccPath, [file, ...emccFlags, "-c", "-o", ofile], emccSpawnOptions); 129 | console.log( 130 | `${colors.magenta(" - compile")} ${colors.magentaBright(ofile.padEnd(30, " "))} ${colors.gray( 131 | ` ${prettyElapsedTime(performance.now() - start)}`, 132 | )}`, 133 | ); 134 | }; 135 | 136 | await timed("emcc compile", async () => { 137 | await spawnAsync(emccPath, ["--version"], {}); 138 | const promises = []; 139 | for (const file of srcFiles) { 140 | promises.push(compileObjectFile(file)); 141 | } 142 | return Promise.all(promises); 143 | }); 144 | 145 | const emccLink = (environment, ofile) => { 146 | return timed(`emcc link ${environment}`, async () => { 147 | const start = performance.now(); 148 | const filename = path.resolve(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, ofile); 149 | 150 | console.log(colors.blueBright(` - linking ${path.relative(ROOT_FOLDER, filename)}`)); 151 | 152 | await spawnAsync( 153 | emccPath, 154 | [...oFiles, ...emccFlags, ...buildLinkArgs(environment), "-o", filename], 155 | emccSpawnOptions, 156 | ); 157 | 158 | let src = await fs.promises.readFile(filename, "utf8"); 159 | 160 | src = src.replace('typeof atob == "function"', "true").replace('"function" == typeof atob', true); 161 | 162 | src = `// AUTO-GENERATED: This file was autogenerated by scripts/compile-wasm.js, do not modify.\n\n${src}`; 163 | 164 | if (environment === "node") { 165 | src = `"use strict";\n${src}`; 166 | src = `if (typeof exports === "object")\nObject.defineProperty(exports, "__esModule", { value: true });\n${src}`; 167 | src += 'if (typeof exports === "object")\nexports.default = roaring_wasm;'; 168 | } 169 | 170 | src = await prettier.format(src, { parser: "espree" }); 171 | 172 | await fs.promises.writeFile(filename, src); 173 | 174 | console.log( 175 | `${colors.magenta(" - link")} ${colors.magentaBright(ofile.padEnd(30, " "))} ${colors.gray( 176 | ` ${prettyElapsedTime(performance.now() - start)}`, 177 | )}`, 178 | ); 179 | return filename; 180 | }); 181 | }; 182 | 183 | const emccBuildNode = async () => { 184 | await emccLink("node", "index.js"); 185 | }; 186 | 187 | const emccBuildBrowser = async () => { 188 | await emccLink("browser", "index.browser.mjs"); 189 | }; 190 | 191 | const buildDts = async () => { 192 | let content = ""; 193 | content += "// AUTO-GENERATED: This file was autogenerated by scripts/compile-wasm.js, do not modify.\n\n"; 194 | content += "declare const roaring_wasm_module_init: (Module?: any) => TModule;\n\n"; 195 | content += "export default roaring_wasm_module_init;\n"; 196 | await fs.promises.writeFile(path.resolve(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, "index.d.ts"), content); 197 | }; 198 | 199 | await timed("emcc link", () => Promise.all([emccBuildNode(), emccBuildBrowser(), buildDts()])); 200 | 201 | const fileSizes = await getFileSizesAsync([ 202 | `${removeTrailingSlash(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER)}/**/*.{js,mjs,cjs,wasm}`, 203 | ]); 204 | console.log(); 205 | for (const f of fileSizes) { 206 | console.log(`• ${colors.green(f.path)} ${colors.cyanBright(`${f.sizeString}`)}`); 207 | } 208 | console.log(); 209 | } 210 | 211 | module.exports = { compileWasm }; 212 | 213 | if (require.main === module) { 214 | runMain(compileWasm); 215 | } 216 | -------------------------------------------------------------------------------- /scripts/config/exportedFunctions.js: -------------------------------------------------------------------------------- 1 | const exportedFunctions = [ 2 | "_jsalloc_unsafe", 3 | "_jsalloc_zero", 4 | "_free", 5 | 6 | "_roaring_bitmap_create_js", 7 | "_roaring_bitmap_create_with_capacity", 8 | "_roaring_bitmap_free", 9 | "_roaring_bitmap_is_empty", 10 | "_roaring_bitmap_add", 11 | "_roaring_bitmap_remove", 12 | "_roaring_bitmap_maximum", 13 | "_roaring_bitmap_minimum", 14 | "_roaring_bitmap_is_subset", 15 | "_roaring_bitmap_is_strict_subset", 16 | "_roaring_bitmap_to_uint32_array", 17 | "_roaring_bitmap_equals", 18 | "_roaring_bitmap_optimize_js", 19 | "_roaring_bitmap_select_js", 20 | "_roaring_bitmap_get_index_js", 21 | "_roaring_bitmap_at_js", 22 | "_roaring_bitmap_and_cardinality", 23 | "_roaring_bitmap_or_cardinality", 24 | "_roaring_bitmap_andnot_cardinality", 25 | "_roaring_bitmap_xor_cardinality", 26 | "_roaring_bitmap_rank", 27 | "_roaring_bitmap_and_inplace", 28 | "_roaring_bitmap_or_inplace", 29 | "_roaring_bitmap_xor_inplace", 30 | "_roaring_bitmap_andnot_inplace", 31 | "_roaring_bitmap_intersect", 32 | "_roaring_bitmap_jaccard_index_js", 33 | "_roaring_bitmap_has_js", 34 | 35 | "_roaring_bitmap_add_checked", 36 | "_roaring_bitmap_remove_checked", 37 | 38 | "_roaring_bitmap_add_many", 39 | "_roaring_bitmap_portable_size_in_bytes", 40 | "_roaring_bitmap_frozen_size_in_bytes", 41 | "_roaring_bitmap_portable_serialize", 42 | "_roaring_bitmap_portable_deserialize_safe", 43 | "_roaring_bitmap_frozen_serialize", 44 | "_roaring_bitmap_frozen_view", 45 | "_roaring_bitmap_portable_deserialize_frozen", 46 | "_roaring_bitmap_size_in_bytes", 47 | "_roaring_bitmap_serialize", 48 | "_roaring_bitmap_deserialize_safe", 49 | 50 | "_roaring_bitmap_get_cardinality_js", 51 | "_roaring_bitmap_flip_range_static_js", 52 | "_roaring_bitmap_from_range_js", 53 | "_roaring_bitmap_contains_range_js", 54 | "_roaring_bitmap_add_range_js", 55 | "_roaring_bitmap_remove_range_js", 56 | "_roaring_bitmap_flip_range_inplace_js", 57 | "_roaring_bitmap_range_cardinality_js", 58 | "_roaring_bitmap_add_offset_js", 59 | "_roaring_bitmap_copy", 60 | "_roaring_bitmap_overwrite", 61 | "_roaring_bitmap_run_optimize", 62 | "_roaring_bitmap_shrink_to_fit_js", 63 | "_roaring_bitmap_remove_run_compression", 64 | "_roaring_bitmap_and_js", 65 | "_roaring_bitmap_or_js", 66 | "_roaring_bitmap_xor_js", 67 | "_roaring_bitmap_andnot_js", 68 | "_roaring_bitmap_or_many", 69 | "_roaring_bitmap_xor_many", 70 | "_roaring_bitmap_intersect_with_range_js", 71 | 72 | "_roaring_iterator_js_new", 73 | "_roaring_iterator_js_next", 74 | "_roaring_iterator_js_clone", 75 | "_roaring_iterator_js_gte", 76 | 77 | "_roaring_sync_iter_init", 78 | "_roaring_sync_iter_next", 79 | "_roaring_sync_iter_min", 80 | 81 | "_roaring_sync_bulk_add_init", 82 | "_roaring_sync_bulk_add_chunk", 83 | 84 | "_roaring_bitmap_remove_many", 85 | "_roaring_sync_bulk_remove_init", 86 | "_roaring_sync_bulk_remove_chunk", 87 | ]; 88 | 89 | module.exports = exportedFunctions; 90 | -------------------------------------------------------------------------------- /scripts/config/paths.d.ts: -------------------------------------------------------------------------------- 1 | export const ROOT_FOLDER: string; 2 | 3 | export const ROARING_WASM_OUT_FOLDER: string; 4 | 5 | export const ROARING_WASM_SRC_FOLDER: string; 6 | 7 | export const ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER: string; 8 | 9 | export const ROARING_WASM_EMCC_BUILD_FOLDER: string; 10 | 11 | export const ROARING_WASM_CPP_SRC_FOLDER: string; 12 | -------------------------------------------------------------------------------- /scripts/config/paths.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | 3 | const ROOT_FOLDER = path.resolve(__dirname, "../../"); 4 | 5 | const ROARING_WASM_SRC_FOLDER = path.resolve(ROOT_FOLDER, "packages/roaring-wasm-src"); 6 | const ROARING_WASM_CPP_SRC_FOLDER = path.resolve(ROARING_WASM_SRC_FOLDER, "cpp"); 7 | const ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER = path.resolve(ROARING_WASM_SRC_FOLDER, "lib/roaring-wasm-module"); 8 | const ROARING_WASM_EMCC_BUILD_FOLDER = path.resolve(ROOT_FOLDER, "build/emcc"); 9 | const ROARING_WASM_OUT_FOLDER = path.resolve(ROOT_FOLDER, "packages/roaring-wasm"); 10 | 11 | module.exports = { 12 | ROOT_FOLDER, 13 | ROARING_WASM_OUT_FOLDER, 14 | ROARING_WASM_SRC_FOLDER, 15 | ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, 16 | ROARING_WASM_EMCC_BUILD_FOLDER, 17 | ROARING_WASM_CPP_SRC_FOLDER, 18 | }; 19 | -------------------------------------------------------------------------------- /scripts/config/terser-config.js: -------------------------------------------------------------------------------- 1 | const ecma = 2019; 2 | 3 | module.exports = { 4 | // Use when minifying an ES6 module. 5 | // "use strict" is implied and names can be mangled on the top scope. 6 | // If compress or mangle is enabled then the toplevel option will be enabled. 7 | module, 8 | 9 | // set to true if you wish to enable top level variable and function name mangling 10 | // and to drop unused variables and functions. 11 | toplevel: true, 12 | 13 | // Sourcemap support 14 | sourceMap: false, 15 | 16 | ecma, 17 | ie8: false, 18 | safari10: false, 19 | keep_classnames: true, 20 | keep_fnames: true, 21 | 22 | // Parser options 23 | parse: { 24 | bare_returns: true, 25 | ecma, 26 | html5_comments: true, 27 | shebang: true, 28 | }, 29 | 30 | // Compress options 31 | compress: { 32 | ecma, 33 | ie8: false, 34 | 35 | // Global definitions for conditional compilation 36 | global_defs: {}, 37 | 38 | // Inline single-use functions when possible. Depends on reduce_vars being enabled. 39 | // Disabling this option sometimes improves performance of the output code. 40 | reduce_funcs: true, 41 | 42 | // Class and object literal methods are converted will also be converted to arrow expressions 43 | // if the resultant code is shorter: m(){return x} becomes m:()=>x 44 | arrows: true, 45 | 46 | // replace arguments[index] with function parameter name whenever possible. 47 | arguments: true, 48 | 49 | // various optimizations for boolean context, for example !!a ? b : c → a ? b : c 50 | booleans: true, 51 | 52 | // Turn booleans into 0 and 1, also makes comparisons with booleans use == and != instead of === and !== 53 | booleans_as_integers: false, 54 | 55 | // Collapse single-use non-constant variables, side effects permitting. 56 | collapse_vars: true, 57 | 58 | // apply certain optimizations to binary nodes, 59 | // e.g. !(a <= b) → a > b (only when unsafe_comps), attempts to negate binary nodes, 60 | // e.g. a = !b && !c && !d && !e → a=!(b||c||d||e) etc. 61 | comparisons: true, 62 | 63 | // Transforms constant computed properties into regular ones: 64 | // {["computed"]: 1} is converted to {computed: 1} 65 | computed_props: true, 66 | 67 | // apply optimizations for if-s and conditional expressions 68 | conditionals: true, 69 | 70 | // remove unreachable code 71 | dead_code: true, 72 | 73 | // remove redundant or non-standard directives 74 | directives: true, 75 | 76 | // discard calls to console.* functions. 77 | // If you wish to drop a specific function call such as console.info 78 | drop_console: false, 79 | 80 | // remove debugger; statements 81 | drop_debugger: false, 82 | 83 | // attempt to evaluate constant expressions 84 | evaluate: true, 85 | 86 | // Pass true to preserve completion values from terminal statements without return, e.g. in bookmarklets. 87 | expression: false, 88 | 89 | // hoist function declarations 90 | hoist_funs: false, 91 | 92 | // hoist properties from constant object and array literals into regular variables subject to a set of constraints. 93 | // For example: var o={p:1, q:2}; f(o.p, o.q); is converted to f(1, 2) 94 | hoist_props: true, 95 | 96 | // hoist var declarations 97 | // (this is false by default because it seems to increase the size of the output in general) 98 | hoist_vars: false, 99 | 100 | // optimizations for if/return and if/continue 101 | if_return: true, 102 | 103 | // inline calls to function with simple/return statement 104 | inline: true, 105 | 106 | // join consecutive var statements 107 | join_vars: true, 108 | 109 | // Pass true to prevent the compressor from discarding class names. 110 | // Pass a regular expression to only keep class names matching that regex. 111 | keep_classnames: true, 112 | 113 | // Prevents the compressor from discarding unused function arguments. 114 | // You need this for code which relies on Function.length 115 | keep_fargs: false, 116 | 117 | // Pass true to prevent the compressor from discarding function names. 118 | // Pass a regular expression to only keep function names matching that regex 119 | keep_fnames: true, 120 | 121 | // Pass true to prevent Infinity from being compressed into 1/0, 122 | // which may cause performance issues on Chrome. 123 | keep_infinity: false, 124 | 125 | // optimizations for do, while and for loops when we can statically determine the condition. 126 | loops: true, 127 | 128 | // Pass true when compressing an ES6 module. Strict mode is implied and the toplevel option as well. 129 | module: true, 130 | 131 | // negate "Immediately-Called Function Expressions" where the return value is discarded, 132 | // to avoid the parens that the code generator would insert. 133 | negate_iife: true, 134 | 135 | // The maximum number of times to run compress. 136 | // In some cases more than one pass leads to further compressed code. 137 | passes: 5, 138 | 139 | pure_funcs: ["atob", "btoa"], 140 | 141 | // Rewrite property access using the dot notation, for example foo["bar"] → foo.bar 142 | properties: true, 143 | 144 | // If you pass true for this, Terser will assume that object property access 145 | // (e.g. foo.bar or foo["bar"]) doesn't have any side effects. Specify "strict" 146 | // to treat foo.bar as side-effect-free only when foo is certain to not throw, 147 | // i.e. not null or undefined. 148 | pure_getters: true, 149 | 150 | // Improve optimization on variables assigned with and used as constant values. 151 | reduce_vars: true, 152 | 153 | // join consecutive simple statements using the comma operator. If set as positive integer 154 | // specifies the maximum number of consecutive comma sequences that will be generated. 155 | // If this option is set to true then the default sequences limit is 200 156 | sequences: false, 157 | 158 | // Remove expressions which have no side effects and whose results aren't used. 159 | side_effects: true, 160 | 161 | // de-duplicate and remove unreachable switch branches 162 | switches: true, 163 | 164 | // drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope. 165 | // Set to true to drop both unreferenced functions and variables) 166 | toplevel: true, 167 | 168 | // prevent specific toplevel functions and variables from unused removal. Implies toplevel. 169 | top_retain: null, 170 | 171 | // Transforms typeof foo == "undefined" into foo === void 0 172 | typeofs: true, 173 | 174 | // apply "unsafe" transformations. It enables some transformations that might break code 175 | // logic in certain contrived cases, but should be fine for most code. 176 | // It assumes that standard built-in ECMAScript functions and classes have not been 177 | // altered or replaced. 178 | unsafe: true, 179 | 180 | // Convert ES5 style anonymous function expressions to arrow functions if the function 181 | // body does not reference this. Note: it is not always safe to perform this conversion 182 | // if code relies on the the function having a prototype, which arrow functions lack. 183 | unsafe_arrows: true, 184 | 185 | // Reverse < and <= to > and >= to allow improved compression. 186 | // This might be unsafe when an at least one of two operands is an object with 187 | // computed values due the use of methods like get, or valueOf. 188 | // This could cause change in execution order after operands in the comparison are switching. 189 | unsafe_comps: true, 190 | 191 | // compress and mangle Function(args, code) when both args and code are string literals. 192 | unsafe_Function: true, 193 | 194 | // optimize numerical expressions like 2 * x * 3 into 6 * x, which may give imprecise floating point results. 195 | unsafe_math: true, 196 | 197 | // removes keys from native Symbol declarations, e.g Symbol("kDog") becomes Symbol(). 198 | unsafe_symbols: true, 199 | 200 | // Converts { m: function(){} } to { m(){} }. 201 | // If unsafe_methods is a RegExp then key/value pairs with keys matching the 202 | // RegExp will be converted to concise methods. 203 | // Note: if enabled there is a risk of getting a " is not a constructor" 204 | // TypeError should any code try to new the former function. 205 | unsafe_methods: true, 206 | 207 | // optimize expressions like Array.prototype.slice.call(a) into [].slice.call(a) 208 | unsafe_proto: true, 209 | 210 | // enable substitutions of variables with RegExp values the same way as if they are constants. 211 | unsafe_regexp: true, 212 | 213 | // substitute void 0 if there is a variable named undefined in scope 214 | // (variable name will be mangled, typically reduced to a single character) 215 | unsafe_undefined: true, 216 | 217 | // drop unreferenced functions and variables (simple direct variable assignments 218 | // do not count as references unless set to "keep_assign") 219 | unused: true, 220 | }, 221 | 222 | // Mangle options 223 | mangle: false, 224 | 225 | // Output options 226 | format: { 227 | ie8: false, 228 | 229 | // set desired EcmaScript standard version for output. 230 | ecma, 231 | 232 | /** Emit shorthand properties {a} instead of {a: a} */ 233 | shorthand: true, 234 | 235 | // escape Unicode characters in strings and regexps 236 | // (affects directives with non-ascii characters becoming invalid) 237 | ascii_only: true, 238 | 239 | // whether to actually beautify the output 240 | beautify: true, 241 | 242 | // always insert braces in if, for, do, while or with statements, even if their body is a single statement. 243 | braces: false, 244 | 245 | // false to omit comments in the output 246 | comments: false, 247 | 248 | // escape HTML comments and the slash in occurrences of in strings 249 | inline_script: true, 250 | 251 | // when turned on, prevents stripping quotes from property names in object literals. 252 | keep_quoted_props: true, 253 | 254 | // maximum line length (for minified code) 255 | max_line_len: false, 256 | 257 | // when passed it must be a string and it will be prepended to the output literally. 258 | // The source map will adjust for this text. 259 | // Can be used to insert a comment containing licensing information, for example. 260 | preamble: undefined, 261 | 262 | // pass true to quote all keys in literal objects 263 | quote_keys: false, 264 | 265 | // preferred quote style for strings (affects quoted property names and directives as well): 266 | // 0 -- prefers double quotes, switches to single quotes when there are more double quotes in the string itself. 0 is best for gzip size. 267 | // 1 -- always use single quotes 268 | // 2 -- always use double quotes 269 | // 3 -- always use the original quotes 270 | quote_style: 0, 271 | 272 | // Preserve Terser annotations in the output. 273 | preserve_annotations: true, 274 | 275 | // set this option to true to work around the Safari 10/11 await bug. 276 | safari10: false, 277 | 278 | // separate statements with semicolons. 279 | // If you pass false then whenever possible we will use a newline instead of a semicolon, 280 | // leading to more readable output of minified code (size before gzip could be smaller; size after gzip insignificantly larger). 281 | semicolons: true, 282 | 283 | // preserve shebang #! in preamble (bash scripts) 284 | shebang: false, 285 | 286 | // enable workarounds for WebKit bugs. PhantomJS users should set this option to true. 287 | webkit: false, 288 | 289 | // pass true to wrap immediately invoked function expressions. 290 | wrap_iife: true, 291 | 292 | // pass false if you do not want to wrap function expressions that are passed as arguments, in parenthesis. 293 | // Passing to true, optimize for faster initial execution and parsing, 294 | // by wrapping all immediately-invoked functions or likely-to-be-invoked functions in parentheses. 295 | wrap_func_args: false, 296 | }, 297 | }; 298 | -------------------------------------------------------------------------------- /scripts/lib/logging.js: -------------------------------------------------------------------------------- 1 | /* eslint no-console:0 */ 2 | 3 | const chalk = require("chalk").default; 4 | 5 | const hasIcons = !!(chalk.supportsColor.has256 || process.env.CI); 6 | const icons = { 7 | info: chalk.cyan(hasIcons ? "•" : "*"), 8 | success: chalk.green(hasIcons ? "✔" : "√"), 9 | warning: chalk.yellow(hasIcons ? "⚠" : "‼"), 10 | error: chalk.red(hasIcons ? "✖" : "×"), 11 | bulletSuccess: chalk.green(hasIcons ? "•" : "*"), 12 | block: chalk.blueBright(hasIcons ? chalk.bold("▪") : "-"), 13 | }; 14 | 15 | const logging = { 16 | chalk, 17 | 18 | log(...args) { 19 | console.log(...args); 20 | }, 21 | 22 | keyValue(key, value) { 23 | console.log(`${icons.bulletSuccess} ${chalk.green(key)} ${chalk.cyanBright(`${value}`)}`); 24 | }, 25 | 26 | info(description) { 27 | console.log(`• ${chalk.cyan(description)}`); 28 | }, 29 | 30 | success(description) { 31 | console.log(this.getSuccess(description)); 32 | }, 33 | 34 | failure(description) { 35 | console.log(`${icons.error} ${chalk.yellow(description)}: ${chalk.redBright.bold("Failed.")}`); 36 | }, 37 | 38 | error(error) { 39 | console.log(`${icons.error} ${chalk.redBright((error && (error.stack || error)) || "Error")}\n`); 40 | }, 41 | 42 | warning(description) { 43 | console.log(`${icons.warning} ${chalk.yellow(description)}`); 44 | }, 45 | 46 | getSuccess(description) { 47 | return chalk.greenBright(`${chalk.bold(icons.success)} ${description}`); 48 | }, 49 | 50 | time(description, functor = null) { 51 | if (!functor) { 52 | if (typeof description === "function") { 53 | functor = description; 54 | description = description.name; 55 | } else { 56 | console.time(description); 57 | return description; 58 | } 59 | } 60 | 61 | const successText = logging.getSuccess(description); 62 | console.log(); 63 | console.log(`${icons.block} ${chalk.cyanBright(description)} ...`); 64 | console.time(successText); 65 | let result; 66 | try { 67 | result = typeof functor === "function" ? functor() : functor; 68 | } catch (error) { 69 | logging.failure(description); 70 | throw error; 71 | } 72 | if (result && typeof result.then === "function") { 73 | result = result.then((x) => { 74 | logging.timeEnd(successText); 75 | return x; 76 | }); 77 | 78 | if (typeof result.catch === "function") { 79 | result = result.catch((error) => { 80 | logging.failure(description); 81 | console.log(); 82 | throw error; 83 | }); 84 | } 85 | } else { 86 | logging.timeEnd(successText); 87 | } 88 | return result; 89 | }, 90 | 91 | timeEnd(description) { 92 | console.timeEnd(description); 93 | }, 94 | }; 95 | 96 | module.exports = logging; 97 | -------------------------------------------------------------------------------- /scripts/lib/utils.js: -------------------------------------------------------------------------------- 1 | const colors = require("chalk"); 2 | const util = require("util"); 3 | const path = require("path"); 4 | const fs = require("fs"); 5 | const { spawn, fork } = require("child_process"); 6 | const { ROOT_FOLDER } = require("../config/paths"); 7 | 8 | module.exports = { 9 | colors, 10 | timed, 11 | runMain, 12 | execAsync, 13 | spawnAsync, 14 | forkAsync, 15 | logError, 16 | getFileSizesAsync, 17 | executablePathFromEnv, 18 | prettyElapsedTime, 19 | removeTrailingSlash, 20 | isCI: (!!process.env.CI && process.env.CI !== "false") || process.argv.includes("--ci"), 21 | }; 22 | 23 | function logError(e) { 24 | console.log(colors.redBright("❌ ", util.inspect(e, { colors: colors.level > 0 }))); 25 | } 26 | 27 | function runMain(fn, title = fn.title) { 28 | if (title) { 29 | console.log(colors.blueBright(`\n⬢ ${colors.cyanBright(title)}\n`)); 30 | } 31 | 32 | if (!fn.name) { 33 | Reflect.defineProperty(fn, "name", { 34 | value: "main", 35 | configurable: true, 36 | enumerable: false, 37 | writable: false, 38 | }); 39 | } 40 | 41 | const totalTime = () => (title ? `${colors.cyan(title)}` : "") + colors.italic(` ⌚ ${process.uptime().toFixed(2)}s`); 42 | 43 | let _processCompleted = false; 44 | 45 | const processCompleted = () => { 46 | if (!process.exitCode) { 47 | console.log(colors.greenBright("✅ OK"), totalTime()); 48 | } else { 49 | console.log(colors.redBright(`❌ Failed: exitCode${process.exitCode}`), totalTime()); 50 | } 51 | console.log(); 52 | }; 53 | 54 | process.on("exit", () => { 55 | if (!_processCompleted) { 56 | _processCompleted = true; 57 | processCompleted(); 58 | } 59 | }); 60 | 61 | const handleMainError = (e) => { 62 | if (!process.exitCode) { 63 | process.exitCode = 1; 64 | } 65 | console.log("❌ ", colors.redBright(util.inspect(e, { colors: colors.level > 0 }))); 66 | console.log(totalTime()); 67 | console.log(); 68 | }; 69 | 70 | try { 71 | const result = fn(); 72 | if (typeof result === "object" && result && typeof result.then === "function") { 73 | result.then(() => {}, handleMainError); 74 | } 75 | } catch (e) { 76 | handleMainError(e); 77 | } 78 | } 79 | 80 | function timed(title, fn) { 81 | if (typeof title === "function" || typeof title === "object") { 82 | fn = title; 83 | } 84 | if (typeof title !== "string") { 85 | title = fn.name || ""; 86 | } 87 | console.log(colors.cyan(`${colors.cyan("◆")} ${title}`) + colors.gray(" started...")); 88 | const startTime = performance.now(); 89 | const logSuccess = (x) => { 90 | const elapsed = performance.now() - startTime; 91 | const elapsedStr = elapsed < 1000 ? `${elapsed.toFixed(0)}ms` : `${(elapsed / 1000).toFixed(2)}s`; 92 | const msg = `${colors.greenBright("✔")} ${colors.greenBright(title)} ${colors.greenBright.bold("OK")} ${colors.gray( 93 | `⌚ ${elapsedStr}`, 94 | )}`; 95 | console.log(msg); 96 | return x; 97 | }; 98 | const handleError = (e) => { 99 | const elapsed = performance.now() - startTime; 100 | const elapsedStr = elapsed < 1000 ? `${elapsed.toFixed(0)}ms` : `${(elapsed / 1000).toFixed(2)}s`; 101 | const msg = `${colors.redBright("✖")} ${colors.redBright.redBright(title)} ${colors.redBright.underline.bold( 102 | "FAILED", 103 | )} ${colors.gray(`⌚ ${elapsedStr}`)}`; 104 | console.log(msg); 105 | throw e; 106 | }; 107 | try { 108 | const ret = typeof fn === "function" ? fn() : fn; 109 | if (typeof ret === "object" && ret !== null && typeof ret.then === "function") { 110 | return ret.then(logSuccess, handleError); 111 | } 112 | return logSuccess(ret); 113 | } catch (error) { 114 | handleError(error); 115 | throw error; 116 | } 117 | } 118 | 119 | function execAsync(command, options) { 120 | return new Promise((resolve, reject) => { 121 | require("child_process").exec(command, options, (error, stdout, stderr) => { 122 | if (error) { 123 | reject(error); 124 | } else { 125 | resolve({ stdout, stderr }); 126 | } 127 | }); 128 | }); 129 | } 130 | 131 | function spawnAsync(command, args, options) { 132 | return new Promise((resolve, reject) => { 133 | const childProcess = spawn(command, args, { stdio: "inherit", ...options }); 134 | childProcess.on("error", (e) => { 135 | reject(e); 136 | }); 137 | childProcess.on("close", (code) => { 138 | if (code === 0) { 139 | resolve(); 140 | } else { 141 | reject(new Error(`${command} exited with code ${code}`)); 142 | } 143 | }); 144 | }); 145 | } 146 | 147 | function forkAsync(modulePath, args, options) { 148 | return new Promise((resolve, reject) => { 149 | const childProcess = fork(modulePath, args, { stdio: "inherit", ...options }); 150 | childProcess.on("error", (e) => { 151 | reject(e); 152 | }); 153 | childProcess.on("close", (code) => { 154 | if (code === 0) { 155 | resolve(); 156 | } else { 157 | reject(new Error(`${modulePath} exited with code ${code}`)); 158 | } 159 | }); 160 | }); 161 | } 162 | 163 | async function getFileSizesAsync(patterns, options) { 164 | const files = await require("fast-glob")(patterns, options); 165 | const result = Promise.all( 166 | files.map(async (filePath) => { 167 | const stats = await fs.promises.stat(filePath); 168 | return { 169 | path: path.relative(ROOT_FOLDER, filePath), 170 | size: stats.size, 171 | sizeString: `${(stats.size * 0.001).toFixed(1)}kb`, 172 | }; 173 | }), 174 | ); 175 | return (await result).sort((a, b) => b.size - a.size || a.path.localeCompare(b.path)); 176 | } 177 | 178 | function executablePathFromEnv(envVariableName, subfolder, executableName) { 179 | const v = process.env[envVariableName]; 180 | if (!v) { 181 | return executableName; 182 | } 183 | if (subfolder) { 184 | return path.resolve(path.join(v, subfolder, executableName)); 185 | } 186 | return path.resolve(path.join(v, executableName)); 187 | } 188 | 189 | function prettyElapsedTime(elapsed) { 190 | if (elapsed < 1000) { 191 | return `${elapsed.toFixed(0)}ms`; 192 | } 193 | return `${(elapsed / 1000).toFixed(2)}s`; 194 | } 195 | 196 | function removeTrailingSlash(s) { 197 | if (s && s.length > 1 && (s.endsWith("/") || s.endsWith("\\"))) { 198 | return s.slice(0, -1); 199 | } 200 | return s; 201 | } 202 | -------------------------------------------------------------------------------- /scripts/lint.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { isCI, forkAsync, spawnAsync, timed, runMain } = require("./lib/utils"); 4 | const { typecheck } = require("./typecheck.js"); 5 | const { ROOT_FOLDER } = require("./config/paths"); 6 | 7 | async function lint(args = process.argv.slice(2)) { 8 | const isFix = (args.includes("--fix") || !isCI) && !args.includes("--no-fix"); 9 | 10 | let typecheckError; 11 | let typecheckPromise = timed("typecheck", typecheck); 12 | if (isFix) { 13 | await typecheckPromise; 14 | } else { 15 | typecheckPromise = typecheckPromise.catch((e) => (typecheckError = e || "typecheckError")); 16 | } 17 | 18 | let eslintPromise = timed(isFix ? "eslint fix" : "eslint check", () => 19 | spawnAsync("npx", ["eslint", ".", "--no-error-on-unmatched-pattern", isFix ? "--fix" : "--max-warnings=0"], { 20 | title: isFix ? "eslint fix" : "eslint check", 21 | cwd: ROOT_FOLDER, 22 | showStack: false, 23 | }), 24 | ); 25 | 26 | let eslintError; 27 | if (isFix) { 28 | await eslintPromise; 29 | } else { 30 | eslintPromise = eslintPromise.catch((e) => (eslintError = e || "eslintError")); 31 | } 32 | 33 | const prettierPromise = timed(isFix ? "prettier fix" : "prettier check", () => 34 | forkAsync(require.resolve("prettier/bin/prettier.cjs"), ["--loglevel=warn", isFix ? "--write" : "--check", "."], { 35 | cwd: ROOT_FOLDER, 36 | }), 37 | ); 38 | 39 | await Promise.all([typecheckPromise, eslintPromise, prettierPromise]); 40 | 41 | if (typecheckError) { 42 | throw typecheckError; 43 | } 44 | if (eslintError) { 45 | throw eslintError; 46 | } 47 | } 48 | 49 | module.exports = { 50 | lint, 51 | }; 52 | 53 | if (require.main === module) { 54 | runMain(lint); 55 | } 56 | -------------------------------------------------------------------------------- /scripts/precommit.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { execSync } = require("child_process"); 4 | const { runMain } = require("./lib/utils"); 5 | 6 | runMain(() => { 7 | execSync("npx lint-staged", { stdio: "inherit" }); 8 | execSync("npx pretty-quick --staged", { stdio: "inherit" }); 9 | }, "precommit"); 10 | -------------------------------------------------------------------------------- /scripts/prepush.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { execSync } = require("child_process"); 4 | 5 | const { runMain } = require("./lib/utils"); 6 | 7 | runMain(() => { 8 | execSync("npm run lint:ci", { stdio: "inherit" }); 9 | execSync("npm run test", { stdio: "inherit" }); 10 | }, "prepush"); 11 | -------------------------------------------------------------------------------- /scripts/test.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { ROOT_FOLDER, ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER } = require("./config/paths"); 4 | const { runMain, forkAsync } = require("./lib/utils"); 5 | const fs = require("fs"); 6 | const path = require("path"); 7 | 8 | if (require.main === module) { 9 | process.chdir(ROOT_FOLDER); 10 | 11 | require("ts-node").register(); 12 | 13 | runMain(() => { 14 | if (!fs.existsSync(path.resolve(ROARING_WASM_SRC_WASM_MODULE_OUT_FOLDER, "index.wasm"))) { 15 | throw new Error("Please run `npm run build` before running tests"); 16 | } 17 | 18 | process.argv.push("--recursive"); 19 | process.argv.push("test/unit/**/*.test.ts"); 20 | 21 | if (process.argv.includes("--test-package")) { 22 | process.argv.push("test/package-test/*.test.ts"); 23 | } 24 | 25 | require("mocha/bin/mocha"); 26 | }, "test"); 27 | } else { 28 | module.exports = { 29 | test(args = []) { 30 | return forkAsync(__filename, args, { stdio: "inherit", cwd: ROOT_FOLDER }); 31 | }, 32 | }; 33 | } 34 | -------------------------------------------------------------------------------- /scripts/typecheck.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const ts = require("typescript"); 4 | const fs = require("fs"); 5 | const path = require("path"); 6 | const { runMain } = require("./lib/utils"); 7 | const { ROOT_FOLDER } = require("./config/paths"); 8 | 9 | async function loadProject(tsconfigFile) { 10 | const configFileName = tsconfigFile; 11 | const configFileText = await fs.promises.readFile(configFileName, "utf8"); 12 | const result = ts.parseConfigFileTextToJson(configFileName, configFileText); 13 | const configObject = result.config; 14 | const configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, path.dirname(configFileName)); 15 | return configParseResult; 16 | } 17 | 18 | /** @type {{parent:any; tsconfigPath:string; tsconfig: ts.ParsedCommandLine; files:Set}} */ 19 | const projectsStack = []; 20 | 21 | const projects = []; 22 | 23 | const exploredDirectories = new Set(); 24 | 25 | /** @type {Map}>} */ 26 | const filesMap = new Map(); 27 | 28 | const exploreDir = async (dir) => { 29 | if (exploredDirectories.has(dir)) { 30 | return; 31 | } 32 | exploredDirectories.add(dir); 33 | 34 | const dirBasename = path.basename(dir).toLowerCase(); 35 | if (dirBasename === "node_modules" || dirBasename.startsWith(".")) { 36 | return; // ignored directory 37 | } 38 | 39 | const items = await fs.promises.readdir(dir, { withFileTypes: true }); 40 | 41 | const tsconfigEntry = items.find((item) => item.isFile() && item.name === "tsconfig.json"); 42 | 43 | let project = projectsStack[projectsStack.length - 1]; 44 | 45 | if (tsconfigEntry) { 46 | const tsconfigPath = path.resolve(dir, tsconfigEntry.name); 47 | 48 | // Load the tsconfig 49 | const tsconfig = await loadProject(tsconfigPath); 50 | 51 | project = { 52 | parent: project, 53 | tsconfigPath, 54 | tsconfig, 55 | files: new Set(), 56 | }; 57 | 58 | // push in the stack 59 | projectsStack.push(project); 60 | projects.push(project); 61 | } 62 | 63 | // Recurse subdirectories 64 | const promises = []; 65 | for (const item of items) { 66 | if (item.isDirectory()) { 67 | promises.push(exploreDir(path.resolve(dir, item.name))); 68 | } 69 | } 70 | if (promises.length) { 71 | await Promise.all(promises); 72 | } 73 | 74 | if (tsconfigEntry) { 75 | for (let file of project.tsconfig.fileNames) { 76 | file = path.resolve(dir, file); 77 | 78 | if (!filesMap.has(file) && !file.includes("node_modules")) { 79 | filesMap.set(file, project); 80 | project.files.add(file); 81 | } 82 | } 83 | 84 | projectsStack.pop(); 85 | } 86 | }; 87 | 88 | async function typecheck() { 89 | await exploreDir(ROOT_FOLDER); 90 | 91 | let errors = 0; 92 | let warnings = 0; 93 | 94 | for (const project of projects) { 95 | const files = Array.from(project.files); 96 | const program = ts.createProgram(files, project.tsconfig.options); 97 | const diagnostics = ts.getPreEmitDiagnostics(program); 98 | 99 | const formatHost = { 100 | getCanonicalFileName: (fileName) => fileName, 101 | getCurrentDirectory: () => ROOT_FOLDER, 102 | getNewLine: () => ts.sys.newLine, 103 | }; 104 | const message = ts.formatDiagnosticsWithColorAndContext(diagnostics, formatHost); 105 | console.log(message); 106 | 107 | for (const diagnostic of diagnostics) { 108 | if (diagnostic.category === ts.DiagnosticCategory.Error) { 109 | ++errors; 110 | } else if (diagnostic.category === ts.DiagnosticCategory.Warning) { 111 | ++warnings; 112 | } 113 | } 114 | } 115 | 116 | if (errors || warnings) { 117 | throw new Error(`Typecheck failed, ${errors} errors, ${warnings} warnings`); 118 | } 119 | } 120 | 121 | module.exports = { 122 | typecheck, 123 | }; 124 | 125 | if (require.main === module) { 126 | runMain(typecheck, "typecheck"); 127 | } 128 | -------------------------------------------------------------------------------- /scripts/update-roaring.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | git submodule update --init --recursive 6 | 7 | cd submodules/CRoaring 8 | 9 | git checkout master 10 | git pull 11 | 12 | cd ../.. 13 | -------------------------------------------------------------------------------- /submodules/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[json]": { 3 | "editor.formatOnSave": false, 4 | "editor.formatOnType": false, 5 | }, 6 | "[jsonc]": { 7 | "editor.formatOnSave": false, 8 | "editor.formatOnType": false, 9 | }, 10 | "[css]": { 11 | "editor.formatOnSave": false, 12 | "editor.formatOnType": false, 13 | }, 14 | "[html]": { 15 | "editor.formatOnSave": false, 16 | "editor.formatOnType": false, 17 | }, 18 | "[javascript]": { 19 | "editor.formatOnSave": false, 20 | "editor.formatOnType": false, 21 | }, 22 | "[javascriptreact]": { 23 | "editor.formatOnSave": false, 24 | "editor.formatOnType": false, 25 | }, 26 | "[typescript]": { 27 | "editor.formatOnSave": false, 28 | "editor.formatOnType": false, 29 | }, 30 | "[typescriptreact]": { 31 | "editor.formatOnSave": false, 32 | "editor.formatOnType": false, 33 | }, 34 | "editor.codeActionsOnSave": { 35 | "editor.formatOnSave": false, 36 | "editor.formatOnType": false, 37 | }, 38 | "[c]": { 39 | "editor.formatOnSave": false, 40 | "editor.formatOnType": false, 41 | }, 42 | "[cpp]": { 43 | "editor.formatOnSave": false, 44 | "editor.formatOnType": false, 45 | }, 46 | "editor.detectIndentation": true, 47 | "editor.formatOnSave": false, 48 | "editor.lineNumbers": "on", 49 | "editor.formatOnType": false, 50 | "eslint.enable": false, 51 | "prettier.enable": false, 52 | "eslint.format.enable": false, 53 | "eslint.lintTask.enable": false, 54 | "files.eol": "\n", 55 | "git.detectSubmodules": true 56 | } 57 | -------------------------------------------------------------------------------- /test/benchmark.js: -------------------------------------------------------------------------------- 1 | /* eslint node/no-unpublished-require:0 */ 2 | 3 | const RoaringUint32Array = require("../dist/RoaringUint32Array"); 4 | const RoaringBitmap32 = require("../dist/RoaringBitmap32"); 5 | const { timed } = require("../scripts/lib/utils"); 6 | 7 | function randomRoaringUint32Array(size, maxValue, seed = 18397123) { 8 | const set = new Set(); 9 | while (set.size < size) { 10 | seed = (seed * 16807) % 2147483647; 11 | set.add(seed & maxValue); 12 | } 13 | 14 | return new RoaringUint32Array(set); 15 | } 16 | 17 | let src; 18 | 19 | timed("random data", () => { 20 | src = randomRoaringUint32Array(1000000, 0xffffff); 21 | }); 22 | 23 | timed(`sort`, () => { 24 | src.asTypedArray().sort(); 25 | }); 26 | 27 | const bitmap = new RoaringBitmap32(); 28 | 29 | timed(`add ${src.length} values`, () => { 30 | bitmap.addMany(src); 31 | }); 32 | 33 | let buf; 34 | 35 | timed("serialize", () => { 36 | buf = bitmap.serializeToRoaringUint8Array(); 37 | }); 38 | 39 | // eslint-disable-next-line no-console 40 | console.log("*", buf.byteLength, "bytes serialized"); 41 | 42 | timed("dispose", () => { 43 | src.dispose(); 44 | buf.dispose(); 45 | bitmap.dispose(); 46 | }); 47 | -------------------------------------------------------------------------------- /test/package-test/package.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | 3 | // @ts-ignore 4 | import * as roaring from "roaring-wasm"; 5 | 6 | /** 7 | * This tests are executed by loading the compiled package 8 | */ 9 | describe("package test", () => { 10 | before(roaring.roaringLibraryInitialize); 11 | beforeEach(roaring.RoaringArenaAllocator.start); 12 | afterEach(roaring.RoaringArenaAllocator.stop); 13 | 14 | it("loads the package correctly", () => { 15 | const bitmap = new roaring.RoaringBitmap32([1, 2, 3]); 16 | expect(bitmap.toArray()).deep.eq([1, 2, 3]); 17 | 18 | const a = new roaring.RoaringUint8Array([1, 2, 3]); 19 | expect(Array.from(a.asTypedArray())).deep.eq([1, 2, 3]); 20 | }); 21 | 22 | it("allow iterating a large array", () => { 23 | const bitmap = new roaring.RoaringBitmap32(); 24 | bitmap.addRange(100, 50000); 25 | const iter = new roaring.RoaringBitmap32Iterator(bitmap); 26 | const arr = new Uint32Array(bitmap.size); 27 | let sz = 0; 28 | for (const x of iter) { 29 | arr[sz++] = x; 30 | } 31 | expect(sz).eq(50000 - 100); 32 | expect(iter.done).eq(true); 33 | expect(iter.value).eq(undefined); 34 | expect(iter.isDisposed).eq(true); 35 | for (let i = 0; i < arr.length; i++) { 36 | if (arr[i] !== i + 100) { 37 | expect(arr[i]).eq(i + 100); 38 | } 39 | } 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /test/playwright/browser-mocha.spec.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable mocha/no-global-tests */ 2 | /* eslint-disable no-console */ 3 | import { test, expect } from "@playwright/test"; 4 | 5 | test("run browser mocha tests", async ({ page }) => { 6 | console.log("Running browser mocha tests"); 7 | await page.goto("/"); 8 | const timeout = 50000; 9 | const progressEl = await page.waitForSelector("#completed-status", { timeout }); 10 | await progressEl.waitForElementState("stable", { timeout }); 11 | const progressClass = await progressEl.getAttribute("class"); 12 | const message = await progressEl.innerText(); 13 | expect(progressClass, message).toBe("passed"); 14 | }); 15 | -------------------------------------------------------------------------------- /test/stress/index.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const path = require("path"); 3 | 4 | const RoaringBitmap32 = require("../../dist/RoaringBitmap32"); 5 | const RoaringUint32Array = require("../../dist/RoaringUint32Array"); 6 | const { timed } = require("../../scripts/lib/utils"); 7 | 8 | const randoms = []; 9 | for (let i = 0; i < 500; ++i) { 10 | randoms[i] = (Math.random() * 20000) >>> 0; 11 | } 12 | 13 | const buffers = fs 14 | .readFileSync(path.join(__dirname, "data.txt"), "utf8") 15 | .split("\n") 16 | .map((x) => Buffer.from(x.substr(2), "hex")); 17 | 18 | timed("stress test", () => { 19 | const additional = new RoaringUint32Array(randoms); 20 | for (let repeat = 0; repeat < 100; ++repeat) { 21 | const disposables = []; 22 | for (const buffer of buffers) { 23 | const bmp = RoaringBitmap32.deserialize(buffer); 24 | bmp.addMany(additional); 25 | disposables.push(bmp); 26 | } 27 | for (const d of disposables) { 28 | d.dispose(); 29 | } 30 | } 31 | additional.dispose(); 32 | }); 33 | -------------------------------------------------------------------------------- /test/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "no-empty": false, 5 | "missing-jsdoc": false, 6 | "no-implicit-dependencies": false, 7 | "no-console": false, 8 | "typedef": false, 9 | "completed-docs": false, 10 | "promise-function-async": false, 11 | "import-name": [ 12 | true, 13 | { 14 | "idisposable": "IDisposable" 15 | } 16 | ] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/unit/IDisposable.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { dispose, disposeThis, isDisposable, tryDispose, using } from "roaring-wasm-src"; 3 | 4 | describe("IDisposable utils", () => { 5 | describe("isDisposable", () => { 6 | it("should return true for an object with a dispose method", () => { 7 | expect(isDisposable({ dispose: () => true })).eq(true); 8 | }); 9 | it("should return false for an object without a dispose method", () => { 10 | expect(isDisposable({})).eq(false); 11 | }); 12 | it("should return false for a null object", () => { 13 | expect(isDisposable(null)).eq(false); 14 | }); 15 | it("should return false for a number", () => { 16 | expect(isDisposable(1)).eq(false); 17 | }); 18 | it("should return false for a string", () => { 19 | expect(isDisposable("")).eq(false); 20 | }); 21 | it("should return false for a boolean", () => { 22 | expect(isDisposable(true)).eq(false); 23 | }); 24 | it("should return false for undefined", () => { 25 | expect(isDisposable(undefined)).eq(false); 26 | }); 27 | }); 28 | 29 | describe("dispose", () => { 30 | it("should return false for undefined", () => { 31 | expect(dispose(undefined)).eq(false); 32 | }); 33 | it("should return false for null", () => { 34 | expect(dispose(null)).eq(false); 35 | }); 36 | it("should return false for an object without a dispose method", () => { 37 | expect(dispose({} as any)).eq(false); 38 | }); 39 | it("should return true for an object with a dispose method", () => { 40 | expect(dispose({ dispose: () => true })).eq(true); 41 | }); 42 | }); 43 | 44 | describe("disposeThis", () => { 45 | it("should return false for undefined", () => { 46 | // eslint-disable-next-line no-useless-call 47 | expect(disposeThis.call(undefined)).eq(false); 48 | }); 49 | it("should return false for null", () => { 50 | // eslint-disable-next-line no-useless-call 51 | expect(disposeThis.call(null)).eq(false); 52 | }); 53 | it("should return false for an object without a dispose method", () => { 54 | expect(disposeThis.call({} as any)).eq(false); 55 | }); 56 | it("should return true for an object with a void dispose method", () => { 57 | expect(disposeThis.call({ dispose: () => {} })).eq(true); 58 | }); 59 | it("should return true for an object with a dispose method", () => { 60 | let disposeCount = 0; 61 | const obj = { 62 | dispose: () => { 63 | return ++disposeCount === 1; 64 | }, 65 | }; 66 | expect(disposeThis.call(obj)).eq(true); 67 | expect(disposeCount).eq(1); 68 | expect(disposeThis.call(obj)).eq(false); 69 | expect(disposeCount).eq(2); 70 | }); 71 | }); 72 | 73 | describe("tryDispose", () => { 74 | it("should return false for undefined", () => { 75 | expect(tryDispose(undefined)).eq(false); 76 | }); 77 | it("should return false for null", () => { 78 | expect(tryDispose(null)).eq(false); 79 | }); 80 | it("should return false for an object without a dispose method", () => { 81 | expect(tryDispose({} as any)).eq(false); 82 | }); 83 | it("should return true for an object with a void dispose method", () => { 84 | expect(tryDispose({ dispose: () => {} })).eq(true); 85 | }); 86 | it("should return true for an object with a dispose method", () => { 87 | let disposeCount = 0; 88 | const obj = { 89 | dispose: () => { 90 | return ++disposeCount === 1; 91 | }, 92 | }; 93 | expect(tryDispose(obj)).eq(true); 94 | expect(disposeCount).eq(1); 95 | expect(tryDispose(obj)).eq(false); 96 | expect(disposeCount).eq(2); 97 | }); 98 | it("should return false if dispose throws", () => { 99 | const obj = { 100 | dispose: () => { 101 | throw new Error("test"); 102 | }, 103 | }; 104 | expect(tryDispose(obj)).eq(false); 105 | }); 106 | }); 107 | 108 | describe("using", () => { 109 | describe("using with function", () => { 110 | it("should dispose the object if the callback throws", () => { 111 | let disposeCount = 0; 112 | const obj = { 113 | dispose: () => { 114 | ++disposeCount; 115 | }, 116 | }; 117 | expect(() => 118 | using(obj, (v) => { 119 | expect(v).eq(obj); 120 | throw new Error("using-test"); 121 | }), 122 | ).to.throw("using-test"); 123 | expect(disposeCount).eq(1); 124 | }); 125 | 126 | it("should dispose the object if the callback returns a value", () => { 127 | let disposeCount = 0; 128 | const obj = { 129 | dispose: () => { 130 | ++disposeCount; 131 | }, 132 | }; 133 | expect( 134 | using(obj, (v) => { 135 | expect(v).eq(obj); 136 | return 112; 137 | }), 138 | ).eq(112); 139 | expect(disposeCount).eq(1); 140 | }); 141 | 142 | it("should dispose the object if the callback returns a promise that rejects", async () => { 143 | let disposeCount = 0; 144 | const obj = { 145 | dispose: () => { 146 | ++disposeCount; 147 | }, 148 | }; 149 | const error = new Error("using-test"); 150 | let thrown: unknown; 151 | try { 152 | await using(obj, (v) => { 153 | expect(v).eq(obj); 154 | return Promise.reject(error); 155 | }); 156 | } catch (e) { 157 | thrown = e; 158 | } 159 | expect(disposeCount).eq(1); 160 | expect(thrown).eq(error); 161 | }); 162 | 163 | it("should dispose the object if the callback returns a promise that resolves", async () => { 164 | let disposeCount = 0; 165 | const obj = { 166 | dispose: () => { 167 | ++disposeCount; 168 | }, 169 | }; 170 | await using(obj, (v) => { 171 | expect(v).eq(obj); 172 | return Promise.resolve(); 173 | }); 174 | expect(disposeCount).eq(1); 175 | }); 176 | }); 177 | 178 | describe("using with value", () => { 179 | it("should just dispose the object and return the value if is not a promise", () => { 180 | let disposeCount = 0; 181 | const obj = { 182 | dispose: () => { 183 | ++disposeCount; 184 | }, 185 | }; 186 | expect(using(obj, 112)).eq(112); 187 | expect(disposeCount).eq(1); 188 | }); 189 | 190 | it("should dispose the object if the value is a promise that rejects", async () => { 191 | let disposeCount = 0; 192 | const obj = { 193 | dispose: () => { 194 | ++disposeCount; 195 | }, 196 | }; 197 | const error = new Error("using-test"); 198 | let thrown: unknown; 199 | try { 200 | await using(obj, Promise.reject(error)); 201 | } catch (e) { 202 | thrown = e; 203 | } 204 | expect(disposeCount).eq(1); 205 | expect(thrown).eq(error); 206 | }); 207 | 208 | it("should dispose the object if the value is a promise that resolves", async () => { 209 | let disposeCount = 0; 210 | const obj = { 211 | dispose: () => { 212 | ++disposeCount; 213 | }, 214 | }; 215 | await using(obj, Promise.resolve()); 216 | expect(disposeCount).eq(1); 217 | }); 218 | }); 219 | }); 220 | }); 221 | -------------------------------------------------------------------------------- /test/unit/RoaringArenaAllocator.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { RoaringArenaAllocator, RoaringBitmap32, RoaringUint8Array } from "roaring-wasm-src"; 3 | 4 | describe("RoaringArenaAllocator", () => { 5 | it("should start and stop an arena allocator, and should dispose only non escaped objects", () => { 6 | expect(RoaringArenaAllocator.current).eq(null); 7 | const rootAllocator = RoaringArenaAllocator.start(); 8 | expect(rootAllocator).instanceOf(RoaringArenaAllocator); 9 | expect(rootAllocator.size).eq(0); 10 | expect(rootAllocator.escaped).eq(0); 11 | 12 | let counter1 = 0; 13 | let counter2 = 0; 14 | let counter3 = 0; 15 | 16 | const allocator = new RoaringArenaAllocator(); 17 | expect(RoaringArenaAllocator.current).eq(rootAllocator); 18 | allocator.start(); 19 | 20 | expect(RoaringArenaAllocator.current).eq(allocator); 21 | expect(allocator.size).eq(0); 22 | expect(allocator.escaped).eq(0); 23 | allocator.register({ dispose: () => ++counter1 === 1 }); 24 | const ref2 = allocator.register({ dispose: () => ++counter2 === 1 }); 25 | allocator.register({ dispose: () => ++counter3 === 1 }); 26 | expect(allocator.size).eq(3); 27 | expect(allocator.escaped).eq(0); 28 | expect(allocator.escape(ref2)).eq(ref2); 29 | expect(allocator.size).eq(3); 30 | expect(allocator.escaped).eq(1); 31 | 32 | expect(allocator.stop()).eq(allocator); 33 | 34 | expect(RoaringArenaAllocator.current).eq(rootAllocator); 35 | 36 | expect(allocator.size).eq(0); 37 | expect(allocator.escaped).eq(1); 38 | 39 | expect(counter1).eq(1); 40 | expect(counter2).eq(0); 41 | expect(counter3).eq(1); 42 | 43 | expect(rootAllocator.register(ref2)).eq(ref2); 44 | 45 | expect(RoaringArenaAllocator.current).eq(rootAllocator); 46 | 47 | expect(rootAllocator.size).eq(1); 48 | rootAllocator.stop(); 49 | expect(rootAllocator.size).eq(0); 50 | 51 | expect(RoaringArenaAllocator.current).eq(null); 52 | expect(counter1).eq(1); 53 | expect(counter2).eq(1); 54 | expect(counter3).eq(1); 55 | 56 | rootAllocator.stop(); 57 | expect(RoaringArenaAllocator.current).eq(null); 58 | expect(counter1).eq(1); 59 | expect(counter2).eq(1); 60 | expect(counter3).eq(1); 61 | }); 62 | 63 | it("should allocate a new RoaringUint8Array", () => { 64 | const allocator = new RoaringArenaAllocator(); 65 | const array = allocator.newRoaringUint8Array(5); 66 | expect(array).instanceOf(RoaringUint8Array); 67 | expect(array.isDisposed).eq(false); 68 | allocator.stop(); 69 | expect(array.isDisposed).eq(true); 70 | }); 71 | 72 | it("should allocate a RoaringBitmap32", () => { 73 | const allocator = new RoaringArenaAllocator(); 74 | const array = allocator.newRoaringBitmap32(); 75 | expect(array).instanceOf(RoaringBitmap32); 76 | expect(array.isDisposed).eq(false); 77 | allocator.stop(); 78 | expect(array.isDisposed).eq(true); 79 | }); 80 | 81 | describe("self registration", () => { 82 | it("should register to current when creating a new RoaringUint8Array", () => { 83 | RoaringArenaAllocator.start(); 84 | const instance = new RoaringUint8Array(2); 85 | expect(instance.isDisposed).eq(false); 86 | RoaringArenaAllocator.stop(); 87 | expect(instance.isDisposed).eq(true); 88 | }); 89 | 90 | it("should register to current when creating a new RoaringBitmap32", () => { 91 | RoaringArenaAllocator.start(); 92 | const instance = new RoaringBitmap32([1, 2, 3]); 93 | expect(instance.isDisposed).eq(false); 94 | RoaringArenaAllocator.stop(); 95 | expect(instance.isDisposed).eq(true); 96 | }); 97 | }); 98 | }); 99 | -------------------------------------------------------------------------------- /test/unit/RoaringBitmap32/RoaringBitmap32-empty.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { RoaringArenaAllocator, RoaringBitmap32, roaringLibraryInitialize } from "roaring-wasm-src"; 3 | 4 | describe("RoaringBitmap32 empty", () => { 5 | before(roaringLibraryInitialize); 6 | beforeEach(RoaringArenaAllocator.start); 7 | afterEach(RoaringArenaAllocator.stop); 8 | 9 | it("should have isEmpty() === true", () => { 10 | expect(new RoaringBitmap32().isEmpty).eq(true); 11 | }); 12 | 13 | it("should have size === 0", () => { 14 | expect(new RoaringBitmap32().size).eq(0); 15 | }); 16 | 17 | it("has a toArray() that returns an empty array", () => { 18 | expect(new RoaringBitmap32().toArray()).deep.eq([]); 19 | }); 20 | 21 | it("should have minimum === 4294967295", () => { 22 | expect(new RoaringBitmap32().minimum()).eq(4294967295); 23 | }); 24 | 25 | it("should have maximum === 0", () => { 26 | expect(new RoaringBitmap32().maximum()).eq(0); 27 | }); 28 | 29 | it("should not contain 0", () => { 30 | expect(new RoaringBitmap32().has(0)).eq(false); 31 | }); 32 | 33 | it("should have a portable serialization size 8", () => { 34 | expect(new RoaringBitmap32().getSerializationSizeInBytes(true)).eq(8); 35 | }); 36 | 37 | it('should serialize as "empty" (portable)', () => { 38 | const buf = new RoaringBitmap32().serializeToRoaringUint8Array(true); 39 | expect(Array.from(buf.asTypedArray())).deep.eq([58, 48, 0, 0, 0, 0, 0, 0]); 40 | }); 41 | 42 | it("should have a native serialization size 5", () => { 43 | expect(new RoaringBitmap32().getSerializationSizeInBytes("croaring")).eq(5); 44 | }); 45 | 46 | it('should serialize as "empty" (native)', () => { 47 | const buf = new RoaringBitmap32().serializeToRoaringUint8Array("croaring"); 48 | expect(Array.from(buf.asTypedArray())).deep.eq([1, 0, 0, 0, 0]); 49 | }); 50 | 51 | it("should be a subset of itself", () => { 52 | expect(new RoaringBitmap32().isSubset(new RoaringBitmap32())).eq(true); 53 | }); 54 | 55 | it("should not be a strict subset of itself", () => { 56 | expect(new RoaringBitmap32().isStrictSubset(new RoaringBitmap32())).eq(false); 57 | }); 58 | }); 59 | -------------------------------------------------------------------------------- /test/unit/RoaringBitmap32/RoaringBitmap32-many.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { RoaringArenaAllocator, RoaringBitmap32, roaringLibraryInitialize } from "roaring-wasm-src"; 3 | 4 | describe("RoaringBitmap32 many", () => { 5 | before(roaringLibraryInitialize); 6 | beforeEach(RoaringArenaAllocator.start); 7 | afterEach(RoaringArenaAllocator.stop); 8 | 9 | describe("addMany", () => { 10 | it("works with empty arrays", () => { 11 | const bitmap = new RoaringBitmap32(); 12 | bitmap.addMany(new Uint32Array([])); 13 | bitmap.addMany(new Int32Array([])); 14 | bitmap.addMany(new Uint8Array([])); 15 | bitmap.addMany([]); 16 | bitmap.addMany(null); 17 | bitmap.addMany(undefined); 18 | expect(bitmap.toArray()).deep.eq([]); 19 | }); 20 | 21 | it("works with a small Uint32Array", () => { 22 | const bitmap = new RoaringBitmap32(); 23 | bitmap.addMany(new Uint32Array([1, 5, 10, 10, 0xffffffff, 4, 2, 10, 2, 2, 1, 5])); 24 | expect(bitmap.toArray()).deep.eq([1, 2, 4, 5, 10, 0xffffffff]); 25 | }); 26 | 27 | it("works with a small Int16Array", () => { 28 | const bitmap = new RoaringBitmap32(); 29 | bitmap.addMany(new Int16Array([2, 5, 0x7fff, 4, 1])); 30 | expect(bitmap.toArray()).deep.eq([1, 2, 4, 5, 0x7fff]); 31 | }); 32 | 33 | it("works with a small array", () => { 34 | const bitmap = new RoaringBitmap32(); 35 | bitmap.addMany([1, 5, 10, 10, 0xffffffff, null, undefined, NaN, false, 4, 2, 10, 2, 1, 2, 5, 2]); 36 | expect(bitmap.toArray()).deep.eq([1, 2, 4, 5, 10, 0xffffffff]); 37 | }); 38 | 39 | it("works with a small set", () => { 40 | const bitmap = new RoaringBitmap32(); 41 | bitmap.addMany(new Set([1, 5, 10, 0xffffffff, 4, 2, 1, 5])); 42 | expect(bitmap.toArray()).deep.eq([1, 2, 4, 5, 10, 0xffffffff]); 43 | }); 44 | 45 | it("works with a large Uint32Array", () => { 46 | const bitmap = new RoaringBitmap32(); 47 | const arr = new Uint32Array(1070000); 48 | for (let i = 0; i < arr.length; i++) { 49 | arr[i] = i; 50 | } 51 | bitmap.addMany(arr); 52 | const o = bitmap.toArray(); 53 | for (let i = 0; i < arr.length; i++) { 54 | if (o[i] !== i) { 55 | expect(o[i]).eq(i); 56 | } 57 | } 58 | }); 59 | 60 | it("works with a large array", () => { 61 | const bitmap = new RoaringBitmap32(); 62 | const arr = new Array(1070000); 63 | for (let i = 0; i < arr.length; i++) { 64 | arr[i] = i; 65 | } 66 | bitmap.addMany(arr); 67 | const o = bitmap.toArray(); 68 | for (let i = 0; i < arr.length; i++) { 69 | if (o[i] !== i) { 70 | expect(o[i]).eq(i); 71 | } 72 | } 73 | }); 74 | 75 | it("works with a large set", () => { 76 | const bitmap = new RoaringBitmap32(); 77 | const arr = new Set(); 78 | for (let i = 0; i < 100000; i++) { 79 | arr.add(i); 80 | } 81 | bitmap.addMany(arr); 82 | const o = bitmap.toArray(); 83 | for (let i = 0; i < arr.size; i++) { 84 | if (o[i] !== i) { 85 | expect(o[i]).eq(i); 86 | } 87 | } 88 | }); 89 | 90 | it("works with a RoaringBitmap32", () => { 91 | const bitmap = new RoaringBitmap32([1, 12, 3]); 92 | bitmap.addMany(new RoaringBitmap32([11, 2, 0xffffffff])); 93 | expect(bitmap.toArray()).deep.eq([1, 2, 3, 11, 12, 0xffffffff]); 94 | }); 95 | }); 96 | 97 | describe("removeMany", () => { 98 | it("works with empty arrays", () => { 99 | const bitmap = new RoaringBitmap32([1, 2, 3, 4]); 100 | bitmap.removeMany(new Uint32Array([])); 101 | bitmap.removeMany(new Int32Array([])); 102 | bitmap.removeMany(new Uint8Array([])); 103 | bitmap.removeMany([]); 104 | bitmap.removeMany(null); 105 | bitmap.removeMany(undefined); 106 | expect(bitmap.toArray()).deep.eq([1, 2, 3, 4]); 107 | }); 108 | 109 | it("works with a small RoaringUint32Array", () => { 110 | const bitmap = new RoaringBitmap32([1, 2, 3, 4, 5, 6, 7]); 111 | bitmap.removeMany(new Uint32Array([2, 3, 11, 4])); 112 | expect(bitmap.toArray()).deep.eq([1, 5, 6, 7]); 113 | }); 114 | 115 | it("works with a small Uint32Array", () => { 116 | const bitmap = new RoaringBitmap32([1, 2, 3, 4, 5, 6, 7]); 117 | bitmap.removeMany(new Uint32Array([2, 3, 4, 11])); 118 | expect(bitmap.toArray()).deep.eq([1, 5, 6, 7]); 119 | }); 120 | 121 | it("works with a small Int16Array", () => { 122 | const bitmap = new RoaringBitmap32([1, 2, 3, 4, 5, 6, 7]); 123 | bitmap.removeMany(new Int16Array([2, 3, 4, 11])); 124 | expect(bitmap.toArray()).deep.eq([1, 5, 6, 7]); 125 | }); 126 | 127 | it("works with a small array", () => { 128 | const bitmap = new RoaringBitmap32([1, 2, 3, 4, 5, 6, 7]); 129 | bitmap.removeMany([2, 4, 3, 11, -19, -32, 0xffffffff, null, undefined, NaN, false]); 130 | expect(bitmap.toArray()).deep.eq([1, 5, 6, 7]); 131 | }); 132 | 133 | it("works with a small set", () => { 134 | const bitmap = new RoaringBitmap32([1, 2, 3, 4, 5, 6, 7]); 135 | bitmap.removeMany(new Set([2, 0xffffffff, 4, 3, 11, -19, -32])); 136 | expect(bitmap.toArray()).deep.eq([1, 5, 6, 7]); 137 | }); 138 | 139 | it("works with a RoaringBitmap32", () => { 140 | const bitmap = new RoaringBitmap32([1, 2, 3, 4, 5, 6, 7]); 141 | bitmap.removeMany(new RoaringBitmap32([2, 3, 4, 11])); 142 | expect(bitmap.toArray()).deep.eq([1, 5, 6, 7]); 143 | }); 144 | }); 145 | }); 146 | -------------------------------------------------------------------------------- /test/unit/RoaringBitmap32/RoaringBitmap32-one-element.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { RoaringArenaAllocator, RoaringBitmap32, roaringLibraryInitialize } from "roaring-wasm-src"; 3 | 4 | describe("RoaringBitmap32 one element", () => { 5 | before(roaringLibraryInitialize); 6 | beforeEach(RoaringArenaAllocator.start); 7 | afterEach(RoaringArenaAllocator.stop); 8 | 9 | describe("read", () => { 10 | it("should not be empty", () => { 11 | expect(new RoaringBitmap32([123]).isEmpty).eq(false); 12 | }); 13 | 14 | it("should have size === 1", () => { 15 | expect(new RoaringBitmap32([123]).size).eq(1); 16 | }); 17 | 18 | it("should have minimum === 123", () => { 19 | expect(new RoaringBitmap32([123]).minimum()).eq(123); 20 | }); 21 | 22 | it("should have maximum === 123", () => { 23 | expect(new RoaringBitmap32([123]).maximum()).eq(123); 24 | }); 25 | 26 | it("should not contain 0", () => { 27 | expect(new RoaringBitmap32([123]).has(0)).eq(false); 28 | }); 29 | 30 | it("should contain 123", () => { 31 | expect(new RoaringBitmap32([123]).has(123)).eq(true); 32 | }); 33 | 34 | it("has a toArray() that returns [123]", () => { 35 | expect(new RoaringBitmap32([123]).toArray()).deep.eq([123]); 36 | }); 37 | 38 | it("should have a portable serialization size 18", () => { 39 | expect(new RoaringBitmap32([123]).getSerializationSizeInBytes(true)).eq(18); 40 | }); 41 | 42 | it("should serialize as (portable)", () => { 43 | const buf = new RoaringBitmap32([123]).serializeToRoaringUint8Array(true); 44 | expect(Array.from(buf.asTypedArray())).deep.eq([58, 48, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 123, 0]); 45 | }); 46 | 47 | it("should have a native serialization size 9", () => { 48 | expect(new RoaringBitmap32([123]).getSerializationSizeInBytes(false)).eq(9); 49 | }); 50 | 51 | it("should serialize as (native)", () => { 52 | const buf = new RoaringBitmap32([123]).serializeToRoaringUint8Array(false); 53 | expect(Array.from(buf.asTypedArray())).deep.eq([1, 1, 0, 0, 0, 123, 0, 0, 0]); 54 | }); 55 | 56 | it("should be a subset of itself", () => { 57 | const instance = new RoaringBitmap32([123]); 58 | expect(instance.isSubset(instance)).eq(true); 59 | }); 60 | 61 | it("should not be a strict subset of itself", () => { 62 | const instance = new RoaringBitmap32([123]); 63 | expect(instance.isStrictSubset(instance)).eq(false); 64 | }); 65 | 66 | it("should be equal to itself", () => { 67 | const instance = new RoaringBitmap32([123]); 68 | expect(instance.isEqual(instance)).eq(true); 69 | }); 70 | 71 | it("should not be equal to an empty instance", () => { 72 | const instance = new RoaringBitmap32([123]); 73 | expect(instance.isEqual(new RoaringBitmap32([]))).eq(false); 74 | }); 75 | 76 | it("should select", () => { 77 | const instance = new RoaringBitmap32([123]); 78 | expect(instance.select(0)).eq(123); 79 | expect(isNaN(instance.select(1))).eq(true); 80 | }); 81 | 82 | it("should indexOf", () => { 83 | const instance = new RoaringBitmap32([123]); 84 | expect(instance.indexOf(123)).eq(0); 85 | expect(instance.indexOf(124)).eq(-1); 86 | }); 87 | 88 | it("should rank", () => { 89 | const instance = new RoaringBitmap32([123]); 90 | expect(instance.rank(1)).eq(0); 91 | expect(instance.rank(123)).eq(1); 92 | expect(instance.rank(12300)).eq(1); 93 | }); 94 | 95 | it("should have AND cardinality of 1 with itself", () => { 96 | const instance = new RoaringBitmap32([123]); 97 | expect(instance.andCardinality(instance)).eq(1); 98 | }); 99 | 100 | it("should have OR cardinality of 1 with itself", () => { 101 | const instance = new RoaringBitmap32([123]); 102 | expect(instance.orCardinality(instance)).eq(1); 103 | }); 104 | 105 | it("should have XOR cardinality of 0 with itself", () => { 106 | const instance = new RoaringBitmap32([123]); 107 | expect(instance.xorCardinality(instance)).eq(0); 108 | }); 109 | 110 | it("should have AND NOT cardinality of 0 with itself", () => { 111 | const instance = new RoaringBitmap32([123]); 112 | expect(instance.andNotCardinality(instance)).eq(0); 113 | }); 114 | 115 | it("has a valid jaccard index with itself", () => { 116 | const instance = new RoaringBitmap32([123]); 117 | expect(instance.jaccardIndex(instance)).eq(1); 118 | }); 119 | }); 120 | }); 121 | -------------------------------------------------------------------------------- /test/unit/RoaringBitmap32/RoaringBitmap32.static.test.ts: -------------------------------------------------------------------------------- 1 | import { RoaringArenaAllocator, roaringLibraryInitialize, RoaringBitmap32 } from "roaring-wasm-src"; 2 | import { expect } from "chai"; 3 | 4 | describe("RoaringBitmap32 static", () => { 5 | before(roaringLibraryInitialize); 6 | beforeEach(RoaringArenaAllocator.start); 7 | afterEach(RoaringArenaAllocator.stop); 8 | 9 | describe("addOffset", () => { 10 | it("returns an empty bitmap if the input bitmap is empty", () => { 11 | const input = new RoaringBitmap32(); 12 | const offsetted = RoaringBitmap32.addOffset(input, 10); 13 | expect(offsetted).to.not.eq(input); 14 | expect(offsetted.toArray()).deep.equal([]); 15 | expect(offsetted.isEmpty).to.be.true; 16 | }); 17 | 18 | it("increment values", () => { 19 | const input = new RoaringBitmap32([1, 2, 3, 100]); 20 | const offsetted = RoaringBitmap32.addOffset(input, 10); 21 | expect(offsetted.toArray()).deep.equal([11, 12, 13, 110]); 22 | expect(offsetted).to.not.eq(input); 23 | }); 24 | 25 | it("decrement values", () => { 26 | const input = new RoaringBitmap32([11, 12, 13, 1100]); 27 | const offsetted = RoaringBitmap32.addOffset(input, -10); 28 | expect(offsetted.toArray()).deep.equal([1, 2, 3, 1090]); 29 | expect(offsetted).to.not.eq(input); 30 | }); 31 | 32 | it("accepts out of range values and NaN", () => { 33 | const input = new RoaringBitmap32([1, 2, 30, 40, 0xffffffff]); 34 | expect(RoaringBitmap32.addOffset(input, -Infinity).toArray()).deep.equal([]); 35 | expect(RoaringBitmap32.addOffset(input, Infinity).toArray()).deep.equal([]); 36 | expect(RoaringBitmap32.addOffset(input, -0xffffffff - 1).toArray()).deep.equal([]); 37 | expect(RoaringBitmap32.addOffset(input, 0xffffffff).toArray()).deep.equal([]); 38 | expect(RoaringBitmap32.addOffset(input, -0xffffffff).toArray()).deep.equal([0]); 39 | expect(RoaringBitmap32.addOffset(input, 0xfffffffe).toArray()).deep.equal([4294967295]); 40 | expect(RoaringBitmap32.addOffset(input, -35).toArray()).deep.equal([5, 4294967260]); 41 | expect(RoaringBitmap32.addOffset(input, 35).toArray()).deep.equal([36, 37, 65, 75]); 42 | }); 43 | }); 44 | 45 | describe("static from", () => { 46 | it("creates an empty bitmap with an empty array", () => { 47 | const bitmap = RoaringBitmap32.from([]); 48 | expect(bitmap.size).eq(0); 49 | expect(bitmap.isEmpty).eq(true); 50 | }); 51 | 52 | it("creates an empty bitmap with an empty bitmap", () => { 53 | const bitmap = RoaringBitmap32.from(new RoaringBitmap32()); 54 | expect(bitmap.size).eq(0); 55 | expect(bitmap.isEmpty).eq(true); 56 | }); 57 | 58 | it("creates a bitmap from an array", () => { 59 | const bitmap = RoaringBitmap32.from([1, 3, 2, 100, 50]); 60 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 50, 100]); 61 | }); 62 | 63 | it("creates a bitmap from an Uint32Array", () => { 64 | const bitmap = RoaringBitmap32.from(new Uint32Array([1, 3, 2, 100, 50])); 65 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 50, 100]); 66 | }); 67 | 68 | it("creates a bitmap from an Int32Array", () => { 69 | const bitmap = RoaringBitmap32.from(new Int32Array([1, 3, 2, 100, 50])); 70 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 50, 100]); 71 | }); 72 | 73 | it("creates a bitmap from another bitmap", () => { 74 | const bitmap1 = new RoaringBitmap32([1, 3, 2, 100, 50]); 75 | const bitmap2 = RoaringBitmap32.from(bitmap1); 76 | expect(bitmap1 !== bitmap2).to.be.true; 77 | expect(bitmap2.toArray()).deep.equal([1, 2, 3, 50, 100]); 78 | }); 79 | }); 80 | 81 | describe("static and", () => { 82 | it("returns empty with empty bitmaps", () => { 83 | const bitmap = RoaringBitmap32.and(new RoaringBitmap32(), new RoaringBitmap32()); 84 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 85 | expect(bitmap.isEmpty).eq(true); 86 | expect(bitmap.size).eq(0); 87 | }); 88 | 89 | it("returns empty with an non empty bitmap", () => { 90 | const bitmap = RoaringBitmap32.and(new RoaringBitmap32(), new RoaringBitmap32([1, 2, 3])); 91 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 92 | expect(bitmap.isEmpty).eq(true); 93 | expect(bitmap.size).eq(0); 94 | }); 95 | 96 | it("ands two bitmaps", () => { 97 | const bitmap = RoaringBitmap32.and(new RoaringBitmap32([3, 1, 2]), new RoaringBitmap32([4, 2])); 98 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 99 | expect(bitmap.toArray()).deep.equal([2]); 100 | }); 101 | }); 102 | 103 | describe("static or", () => { 104 | it("returns empty with empty bitmaps", () => { 105 | const bitmap = RoaringBitmap32.or(new RoaringBitmap32(), new RoaringBitmap32()); 106 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 107 | expect(bitmap.isEmpty).eq(true); 108 | expect(bitmap.size).eq(0); 109 | }); 110 | 111 | it("performs or with empty and non empty", () => { 112 | const c = RoaringBitmap32.or(new RoaringBitmap32(), new RoaringBitmap32([1, 3, 2])); 113 | expect(c.toArray()).deep.equal([1, 2, 3]); 114 | }); 115 | 116 | it("ors two bitmaps", () => { 117 | const bitmap = RoaringBitmap32.or(new RoaringBitmap32([3, 1, 2]), new RoaringBitmap32([4, 2])); 118 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 4]); 119 | }); 120 | }); 121 | 122 | describe("static xor", () => { 123 | it("returns empty with empty bitmaps", () => { 124 | const c = RoaringBitmap32.xor(new RoaringBitmap32(), new RoaringBitmap32()); 125 | expect(c.isEmpty).eq(true); 126 | }); 127 | 128 | it("performs or with empty and non empty", () => { 129 | const bitmap = RoaringBitmap32.xor(new RoaringBitmap32(), new RoaringBitmap32([1, 2, 3])); 130 | expect(bitmap.toArray()).deep.equal([1, 2, 3]); 131 | }); 132 | 133 | it("xors two bitmaps", () => { 134 | const bitmap = RoaringBitmap32.xor(new RoaringBitmap32([3, 1, 2]), new RoaringBitmap32([4, 2])); 135 | expect(bitmap.toArray()).deep.equal([1, 3, 4]); 136 | }); 137 | }); 138 | 139 | describe("static andNot", () => { 140 | it("returns empty with empty bitmaps", () => { 141 | const c = RoaringBitmap32.andNot(new RoaringBitmap32(), new RoaringBitmap32()); 142 | expect(c.isEmpty).eq(true); 143 | }); 144 | 145 | it("returns empty with an non empty array", () => { 146 | const c = RoaringBitmap32.andNot(new RoaringBitmap32(), new RoaringBitmap32([1, 2, 3])); 147 | expect(c.isEmpty).eq(true); 148 | }); 149 | 150 | it("andnots two bitmaps", () => { 151 | const bitmap = RoaringBitmap32.andNot(new RoaringBitmap32([3, 1, 2]), new RoaringBitmap32([4, 2])); 152 | expect(bitmap.toArray()).deep.equal([1, 3]); 153 | }); 154 | }); 155 | 156 | describe("static orMany", () => { 157 | it("orManys multiple bitmaps (spread arguments)", () => { 158 | const bitmap = RoaringBitmap32.orMany([ 159 | new RoaringBitmap32([3, 1, 2]), 160 | new RoaringBitmap32([1, 2, 4]), 161 | new RoaringBitmap32([1, 2, 6]), 162 | ]); 163 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 4, 6]); 164 | }); 165 | 166 | it("orManys multiple bitmaps (array)", () => { 167 | const bitmap = RoaringBitmap32.orMany([ 168 | new RoaringBitmap32([3, 1, 2]), 169 | new RoaringBitmap32([1, 2, 4]), 170 | new RoaringBitmap32([1, 2, 6]), 171 | ]); 172 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 4, 6]); 173 | }); 174 | 175 | it("creates an empty bitmap with no argument passed", () => { 176 | const x = RoaringBitmap32.orMany([]); 177 | expect(x).to.be.instanceOf(RoaringBitmap32); 178 | expect(x.size).eq(0); 179 | expect(x.isEmpty).eq(true); 180 | }); 181 | 182 | it("creates an empty bitmap with a single empty bitmap passed", () => { 183 | const x = RoaringBitmap32.orMany([new RoaringBitmap32()]); 184 | expect(x).to.be.instanceOf(RoaringBitmap32); 185 | expect(x.size).eq(0); 186 | expect(x.isEmpty).eq(true); 187 | }); 188 | 189 | it("creates an empty bitmap with a single empty bitmap passed as array", () => { 190 | const x = RoaringBitmap32.orMany([new RoaringBitmap32()]); 191 | expect(x).to.be.instanceOf(RoaringBitmap32); 192 | expect(x.size).eq(0); 193 | expect(x.isEmpty).eq(true); 194 | }); 195 | 196 | it("creates an empty bitmap with multiple empty bitmap passed", () => { 197 | const x = RoaringBitmap32.orMany([new RoaringBitmap32(), new RoaringBitmap32(), new RoaringBitmap32()]); 198 | expect(x).to.be.instanceOf(RoaringBitmap32); 199 | expect(x.size).eq(0); 200 | expect(x.isEmpty).eq(true); 201 | }); 202 | 203 | it("creates an empty bitmap with a multiple empty bitmap passed as array", () => { 204 | const x = RoaringBitmap32.orMany([new RoaringBitmap32(), new RoaringBitmap32(), new RoaringBitmap32()]); 205 | expect(x).to.be.instanceOf(RoaringBitmap32); 206 | expect(x.size).eq(0); 207 | expect(x.isEmpty).eq(true); 208 | }); 209 | }); 210 | 211 | describe("static xorMany", () => { 212 | it("xorManys multiple bitmaps (spread arguments)", () => { 213 | const bitmap = RoaringBitmap32.xorMany([ 214 | new RoaringBitmap32([3, 1, 2]), 215 | new RoaringBitmap32([3, 2]), 216 | new RoaringBitmap32([6, 7, 8]), 217 | new RoaringBitmap32([7, 4]), 218 | ]); 219 | expect(bitmap.toArray()).deep.equal([1, 4, 6, 8]); 220 | }); 221 | 222 | it("xorManys multiple bitmaps (array)", () => { 223 | const bitmap = RoaringBitmap32.xorMany([ 224 | new RoaringBitmap32([3, 1, 2]), 225 | new RoaringBitmap32([3, 2]), 226 | new RoaringBitmap32([6, 7, 8]), 227 | new RoaringBitmap32([7, 4]), 228 | ]); 229 | expect(bitmap.toArray()).deep.equal([1, 4, 6, 8]); 230 | }); 231 | 232 | it("creates an empty bitmap with no argument passed", () => { 233 | const x = RoaringBitmap32.xorMany([]); 234 | expect(x).to.be.instanceOf(RoaringBitmap32); 235 | expect(x.size).eq(0); 236 | expect(x.isEmpty).eq(true); 237 | }); 238 | 239 | it("creates an empty bitmap with a single empty bitmap passed", () => { 240 | const x = RoaringBitmap32.xorMany([new RoaringBitmap32()]); 241 | expect(x).to.be.instanceOf(RoaringBitmap32); 242 | expect(x.size).eq(0); 243 | expect(x.isEmpty).eq(true); 244 | }); 245 | 246 | it("creates an empty bitmap with a single empty bitmap passed as array", () => { 247 | const x = RoaringBitmap32.xorMany([new RoaringBitmap32()]); 248 | expect(x).to.be.instanceOf(RoaringBitmap32); 249 | expect(x.size).eq(0); 250 | expect(x.isEmpty).eq(true); 251 | }); 252 | 253 | it("creates an empty bitmap with multiple empty bitmap passed", () => { 254 | const x = RoaringBitmap32.xorMany([new RoaringBitmap32(), new RoaringBitmap32(), new RoaringBitmap32()]); 255 | expect(x).to.be.instanceOf(RoaringBitmap32); 256 | expect(x.size).eq(0); 257 | expect(x.isEmpty).eq(true); 258 | }); 259 | 260 | it("creates an empty bitmap with a multiple empty bitmap passed as array", () => { 261 | const x = RoaringBitmap32.xorMany([new RoaringBitmap32(), new RoaringBitmap32(), new RoaringBitmap32()]); 262 | expect(x).to.be.instanceOf(RoaringBitmap32); 263 | expect(x.size).eq(0); 264 | expect(x.isEmpty).eq(true); 265 | }); 266 | }); 267 | 268 | describe("static swap", () => { 269 | it("swaps two empty bitmaps", () => { 270 | const a = new RoaringBitmap32(); 271 | const b = new RoaringBitmap32(); 272 | RoaringBitmap32.swap(a, b); 273 | expect(a.size).eq(0); 274 | expect(a.isEmpty).eq(true); 275 | expect(b.size).eq(0); 276 | expect(b.isEmpty).eq(true); 277 | }); 278 | 279 | it("swaps one empty with a non empty bitmap", () => { 280 | const a = new RoaringBitmap32(); 281 | const b = new RoaringBitmap32([1, 2, 3]); 282 | RoaringBitmap32.swap(a, b); 283 | expect(a.size).eq(3); 284 | expect(a.isEmpty).eq(false); 285 | expect(b.size).eq(0); 286 | expect(b.isEmpty).eq(true); 287 | }); 288 | 289 | it("swaps two bitmaps", () => { 290 | const a = new RoaringBitmap32([4, 5]); 291 | const b = new RoaringBitmap32([1, 2, 3]); 292 | RoaringBitmap32.swap(a, b); 293 | expect(a.size).eq(3); 294 | expect(a.isEmpty).eq(false); 295 | expect(b.size).eq(2); 296 | expect(b.isEmpty).eq(false); 297 | expect(a.toArray()).deep.equal([1, 2, 3]); 298 | expect(b.toArray()).deep.equal([4, 5]); 299 | }); 300 | }); 301 | 302 | describe("of", () => { 303 | it("creates an empty bitmap", () => { 304 | const bitmap = RoaringBitmap32.of(); 305 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 306 | expect(bitmap.size).eq(0); 307 | expect(bitmap.isEmpty).eq(true); 308 | }); 309 | 310 | it("creates a bitmap with one value", () => { 311 | const bitmap = RoaringBitmap32.of(1); 312 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 313 | expect(bitmap.size).eq(1); 314 | expect(bitmap.isEmpty).eq(false); 315 | expect(bitmap.toArray()).deep.equal([1]); 316 | }); 317 | 318 | it("creates a bitmap with multiple values", () => { 319 | const bitmap = RoaringBitmap32.of(1, 2, 2, 2, 0xffff, 3); 320 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 321 | expect(bitmap.size).eq(4); 322 | expect(bitmap.isEmpty).eq(false); 323 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 0xffff]); 324 | }); 325 | 326 | it("handles non-number values", () => { 327 | const bitmap = RoaringBitmap32.of( 328 | -100, 329 | -1, 330 | 1, 331 | 3, 332 | 2, 333 | 2, 334 | "123" as any, 335 | "foo" as any, 336 | null as any, 337 | undefined as any, 338 | NaN, 339 | false, 340 | 0xffff, 341 | 0xffffffff, 342 | 2, 343 | 3, 344 | 3.1, 345 | 3.8, 346 | 4.2, 347 | ); 348 | expect(bitmap).to.be.instanceOf(RoaringBitmap32); 349 | expect(bitmap.isEmpty).eq(false); 350 | expect(bitmap.toArray()).deep.equal([1, 2, 3, 4, 123, 0xffff, 0xffffffff]); 351 | }); 352 | }); 353 | }); 354 | -------------------------------------------------------------------------------- /test/unit/RoaringBitmap32/RoaringBitmap32.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { RoaringArenaAllocator, RoaringBitmap32, roaringLibraryInitialize } from "roaring-wasm-src"; 3 | 4 | describe("RoaringBitmap32", () => { 5 | before(roaringLibraryInitialize); 6 | beforeEach(RoaringArenaAllocator.start); 7 | afterEach(RoaringArenaAllocator.stop); 8 | 9 | describe("addChecked", () => { 10 | it("returns false if nothing changes", () => { 11 | const bitmap = new RoaringBitmap32([123]); 12 | expect(bitmap.tryAdd(123)).eq(false); 13 | expect(bitmap.size).eq(1); 14 | }); 15 | 16 | it("returns true if something changes", () => { 17 | const bitmap = new RoaringBitmap32([124]); 18 | expect(bitmap.tryAdd(123)).eq(true); 19 | expect(bitmap.size).eq(2); 20 | }); 21 | }); 22 | 23 | describe("delete", () => { 24 | it("returns false if nothing changes", () => { 25 | const bitmap = new RoaringBitmap32([125]); 26 | expect(bitmap.delete(123)).eq(false); 27 | expect(bitmap.size).eq(1); 28 | }); 29 | 30 | it("returns true if something changes", () => { 31 | const bitmap = new RoaringBitmap32([123]); 32 | expect(bitmap.remove(123)).eq(true); 33 | expect(bitmap.size).eq(0); 34 | }); 35 | }); 36 | 37 | describe("pop", () => { 38 | it("returns the last element", () => { 39 | const bitmap = new RoaringBitmap32([1, 2, 3]); 40 | expect(bitmap.pop()).eq(3); 41 | expect(bitmap.toArray()).deep.eq([1, 2]); 42 | }); 43 | 44 | it("returns undefined if empty", () => { 45 | const bitmap = new RoaringBitmap32(); 46 | expect(bitmap.pop()).eq(undefined); 47 | }); 48 | }); 49 | 50 | describe("shift", () => { 51 | it("returns the first element", () => { 52 | const bitmap = new RoaringBitmap32([1, 2, 3]); 53 | expect(bitmap.shift()).eq(1); 54 | expect(bitmap.toArray()).deep.eq([2, 3]); 55 | }); 56 | 57 | it("returns undefined if empty", () => { 58 | const bitmap = new RoaringBitmap32(); 59 | expect(bitmap.shift()).eq(undefined); 60 | }); 61 | }); 62 | 63 | describe("from array", () => { 64 | const array = [123, 189, 456, 789, 910]; 65 | 66 | it("adds the array one by one", () => { 67 | const bitmap = new RoaringBitmap32(); 68 | for (const item of array) { 69 | bitmap.add(item); 70 | } 71 | expect(bitmap.toArray()).deep.eq(array); 72 | }); 73 | 74 | it("adds a UInt32Array", () => { 75 | const buffer = new Uint32Array(array); 76 | const bitmap = new RoaringBitmap32(); 77 | bitmap.addMany(buffer); 78 | expect(bitmap.toArray()).deep.eq(array); 79 | }); 80 | 81 | it("adds a simple array", () => { 82 | const bitmap = new RoaringBitmap32(); 83 | bitmap.addMany(array); 84 | expect(bitmap.toArray()).deep.eq(array); 85 | }); 86 | 87 | it("works in the constructor", () => { 88 | const bitmap = new RoaringBitmap32(array); 89 | expect(bitmap.toArray()).deep.eq(array); 90 | }); 91 | }); 92 | 93 | it("has callable removeRunCompression, runOptimize, shrinkToFit", () => { 94 | const bitmap = new RoaringBitmap32([1, 2, 3, 100, 1000, 0xfffffffe, 0xffffffff]); 95 | bitmap.removeRunCompression(); 96 | bitmap.runOptimize(); 97 | bitmap.shrinkToFit(); 98 | }); 99 | 100 | it("indexOf", () => { 101 | const bitmap = new RoaringBitmap32([1, 2, 5, 124, 0xffffffff]); 102 | expect(bitmap.indexOf(1)).eq(0); 103 | expect(bitmap.indexOf(2)).eq(1); 104 | expect(bitmap.indexOf(5)).eq(2); 105 | expect(bitmap.indexOf(124)).eq(3); 106 | expect(bitmap.indexOf(0xffffffff)).eq(4); 107 | expect(bitmap.indexOf(0)).eq(-1); 108 | expect(bitmap.indexOf(3)).eq(-1); 109 | }); 110 | 111 | describe("overwrite", () => { 112 | it("should overwrite the bitmap", () => { 113 | const bitmap = new RoaringBitmap32([1, 2, 5, 124, 0xffffffff]); 114 | bitmap.overwrite(new RoaringBitmap32([1, 2, 3])); 115 | expect(bitmap.toArray()).deep.eq([1, 2, 3]); 116 | }); 117 | }); 118 | 119 | describe("clear", () => { 120 | it("should clear the bitmap", () => { 121 | const bitmap = new RoaringBitmap32([1, 2, 5, 124, 0xffffffff]); 122 | bitmap.clear(); 123 | expect(bitmap.toArray()).deep.eq([]); 124 | }); 125 | 126 | it("should do nothing with an empty bitmap", () => { 127 | const bitmap = new RoaringBitmap32(); 128 | bitmap.clear(); 129 | expect(bitmap.toArray()).deep.eq([]); 130 | }); 131 | }); 132 | 133 | describe("clone", () => { 134 | it("returns a cloned empty bitmap", () => { 135 | const bitmap1 = new RoaringBitmap32(); 136 | const bitmap2 = bitmap1.clone(); 137 | expect(bitmap1 !== bitmap2).eq(true); 138 | expect(bitmap2).to.be.instanceOf(RoaringBitmap32); 139 | expect(bitmap2.size).eq(0); 140 | expect(bitmap2.isEmpty).eq(true); 141 | }); 142 | 143 | it("returns a cloned bitmap", () => { 144 | const values = [1, 2, 100, 101, 200, 400, 0x7fffffff, 0xffffffff]; 145 | const bitmap1 = new RoaringBitmap32(values); 146 | const bitmap2 = bitmap1.clone(); 147 | expect(bitmap1 !== bitmap2).eq(true); 148 | expect(bitmap2).to.be.instanceOf(RoaringBitmap32); 149 | expect(bitmap2.size).eq(values.length); 150 | expect(bitmap2.isEmpty).eq(false); 151 | expect(Array.from(bitmap2.toUint32Array())).deep.equal(values); 152 | }); 153 | }); 154 | 155 | describe("at", () => { 156 | it("returns the value at the given index", () => { 157 | const bitmap = new RoaringBitmap32([1, 12, 30, 0xffff]); 158 | expect(bitmap.at(0)).eq(1); 159 | expect(bitmap.at(1)).eq(12); 160 | expect(bitmap.at(2)).eq(30); 161 | expect(bitmap.at(3)).eq(0xffff); 162 | expect(bitmap.at(4)).eq(undefined); 163 | expect(bitmap.at(5)).eq(undefined); 164 | expect(bitmap.at(-5)).eq(undefined); 165 | 166 | expect(bitmap.at(1.5)).eq(12); 167 | expect(bitmap.at("1.5" as any)).eq(12); 168 | }); 169 | 170 | it("works with negative indices", () => { 171 | const bitmap = new RoaringBitmap32([1, 12, 3]); 172 | expect(bitmap.at(-1)).eq(12); 173 | expect(bitmap.at(-1.4)).eq(12); 174 | expect(bitmap.at(-2)).eq(3); 175 | expect(bitmap.at(-2.9)).eq(3); 176 | expect(bitmap.at(-3)).eq(1); 177 | expect(bitmap.at("-3" as any)).eq(1); 178 | expect(bitmap.at(-4)).eq(undefined); 179 | }); 180 | }); 181 | }); 182 | -------------------------------------------------------------------------------- /test/unit/RoaringBitmap32Iterator.test.ts: -------------------------------------------------------------------------------- 1 | import { RoaringBitmap32, RoaringBitmap32Iterator } from "roaring-wasm-src"; 2 | import { expect } from "chai"; 3 | 4 | describe("RoaringBitmap32Iterator", () => { 5 | describe("constructor", () => { 6 | it("is a class", () => { 7 | expect(typeof RoaringBitmap32).eq("function"); 8 | }); 9 | 10 | it("creates an empty iterator with no arguments", () => { 11 | const iter = new RoaringBitmap32Iterator(); 12 | expect(iter).to.be.instanceOf(RoaringBitmap32Iterator); 13 | }); 14 | 15 | it("creates an iterator with a RoaringBitmap32", () => { 16 | const bitmap = new RoaringBitmap32([3, 4, 5]); 17 | const iter = new RoaringBitmap32Iterator(bitmap); 18 | expect(iter).to.be.instanceOf(RoaringBitmap32Iterator); 19 | }); 20 | }); 21 | 22 | describe("next", () => { 23 | it("returns an empty result if iterator is created without arguments", () => { 24 | const iter = new RoaringBitmap32Iterator(); 25 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 26 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 27 | }); 28 | 29 | it("returns an empty result if iterator is created with an empty RoaringBitmap32", () => { 30 | const iter = new RoaringBitmap32Iterator(new RoaringBitmap32()); 31 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 32 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 33 | }); 34 | 35 | it("allows iterating a small array", () => { 36 | const iter = new RoaringBitmap32Iterator(new RoaringBitmap32([123, 456, 999, 1000])); 37 | expect(iter.isDisposed).eq(false); 38 | expect(iter.done).eq(false); 39 | expect(iter.value).eq(undefined); 40 | expect(iter.next()).deep.equal({ value: 123, done: false }); 41 | expect(iter.isDisposed).eq(false); 42 | expect(iter.done).eq(false); 43 | expect(iter.value).eq(123); 44 | expect(iter.next()).deep.equal({ value: 456, done: false }); 45 | expect(iter.value).eq(456); 46 | expect(iter.next()).deep.equal({ value: 999, done: false }); 47 | expect(iter.value).eq(999); 48 | expect(iter.next()).deep.equal({ value: 1000, done: false }); 49 | expect(iter.value).eq(1000); 50 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 51 | expect(iter.value).eq(undefined); 52 | expect(iter.isDisposed).eq(true); 53 | expect(iter.done).eq(true); 54 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 55 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 56 | expect(iter.value).eq(undefined); 57 | expect(iter.isDisposed).eq(true); 58 | expect(iter.done).eq(true); 59 | 60 | expect(iter.reset().moveToGreaterEqual(900)).eq(iter); 61 | expect(iter.isDisposed).eq(false); 62 | expect(iter.done).eq(false); 63 | expect(iter.value).eq(999); 64 | expect(iter.next()).deep.equal({ value: 999, done: false }); 65 | expect(iter.next()).deep.equal({ value: 1000, done: false }); 66 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 67 | expect(iter.value).eq(undefined); 68 | expect(iter.isDisposed).eq(true); 69 | expect(iter.done).eq(true); 70 | 71 | iter.reset().moveToGreaterEqual(1001); 72 | expect(iter.next()).deep.equal({ value: undefined, done: true }); 73 | }); 74 | }); 75 | 76 | describe("iterable", () => { 77 | it("allow iterating, and disposes the iterator when done", () => { 78 | const iter = new RoaringBitmap32Iterator(new RoaringBitmap32([123, 456, 999, 1000])); 79 | const arr: number[] = []; 80 | for (const x of iter) { 81 | arr.push(x); 82 | } 83 | expect(iter.done).eq(true); 84 | expect(iter.value).eq(undefined); 85 | expect(iter.isDisposed).eq(true); 86 | expect(arr).deep.equal([123, 456, 999, 1000]); 87 | 88 | arr.length = 0; 89 | for (const x of iter.reset()) { 90 | arr.push(x); 91 | if (arr.length === 2) { 92 | break; 93 | } 94 | } 95 | expect(iter.done).eq(true); 96 | expect(iter.value).eq(undefined); 97 | expect(iter.isDisposed).eq(true); 98 | expect(arr).deep.equal([123, 456]); 99 | 100 | const expectedError = new Error("x"); 101 | let thrownError: unknown; 102 | arr.length = 0; 103 | try { 104 | for (const x of iter.reset()) { 105 | arr.push(x); 106 | if (arr.length === 2) { 107 | throw expectedError; 108 | } 109 | } 110 | } catch (e) { 111 | thrownError = e; 112 | } 113 | 114 | expect(iter.done).eq(true); 115 | expect(iter.value).eq(undefined); 116 | expect(iter.isDisposed).eq(true); 117 | expect(arr).deep.equal([123, 456]); 118 | expect(thrownError).eq(expectedError); 119 | }); 120 | 121 | it("allow iterating a large array", () => { 122 | const bitmap = new RoaringBitmap32(); 123 | bitmap.addRange(100, 50000); 124 | const iter = new RoaringBitmap32Iterator(bitmap); 125 | const arr = new Uint32Array(bitmap.size); 126 | let sz = 0; 127 | for (const x of iter) { 128 | arr[sz++] = x; 129 | } 130 | expect(sz).eq(50000 - 100); 131 | expect(iter.done).eq(true); 132 | expect(iter.value).eq(undefined); 133 | expect(iter.isDisposed).eq(true); 134 | for (let i = 0; i < arr.length; i++) { 135 | if (arr[i] !== i + 100) { 136 | expect(arr[i]).eq(i + 100); 137 | } 138 | } 139 | }); 140 | 141 | it("allow iterating while modifying", () => { 142 | const bitmap = RoaringBitmap32.fromRange(100, 1000); 143 | const iter = new RoaringBitmap32Iterator(bitmap); 144 | const arr: number[] = []; 145 | for (const x of iter) { 146 | arr.push(x); 147 | if (!(x & 1)) { 148 | bitmap.remove(x + 1); 149 | } 150 | } 151 | 152 | expect(iter.done).eq(true); 153 | expect(iter.value).eq(undefined); 154 | expect(iter.isDisposed).eq(true); 155 | for (let i = 0; i < arr.length; i++) { 156 | const v = i * 2 + 100; 157 | if (arr[i] !== v) { 158 | expect(arr[i]).eq(v); 159 | } 160 | } 161 | 162 | expect(arr.length).eq(450); 163 | }); 164 | }); 165 | 166 | describe("reset, moveToGreaterEqual", () => { 167 | it("resets the iterator", () => { 168 | const bitmap = new RoaringBitmap32([123, 456, 999, 1000]); 169 | const iter = new RoaringBitmap32Iterator(bitmap); 170 | expect(iter.next()).deep.equal({ value: 123, done: false }); 171 | expect(iter.next()).deep.equal({ value: 456, done: false }); 172 | iter.reset(); 173 | expect(iter.next()).deep.equal({ value: 123, done: false }); 174 | expect(iter.next()).deep.equal({ value: 456, done: false }); 175 | 176 | iter.reset(); 177 | const tmp: number[] = []; 178 | for (const x of iter) { 179 | tmp.push(x); 180 | } 181 | expect(tmp).deep.equal([123, 456, 999, 1000]); 182 | 183 | iter.reset().moveToGreaterEqual(500); 184 | expect(Array.from(iter)).deep.equal([999, 1000]); 185 | 186 | iter.moveToGreaterEqual(0xffffffff); 187 | expect(Array.from(iter)).deep.equal([]); 188 | 189 | bitmap.add(0xffffffff); 190 | 191 | iter.reset().moveToGreaterEqual(0xffffffff); 192 | expect(Array.from(iter)).deep.equal([0xffffffff]); 193 | 194 | iter.reset().moveToGreaterEqual(0x100000000); 195 | expect(Array.from(iter)).deep.equal([]); 196 | }); 197 | }); 198 | 199 | describe("Symbol.iterator", () => { 200 | it("is a function", () => { 201 | const iter = new RoaringBitmap32Iterator(); 202 | expect(typeof iter[Symbol.iterator]).deep.equal("function"); 203 | }); 204 | 205 | it("returns this", () => { 206 | const iter = new RoaringBitmap32Iterator(); 207 | expect(iter[Symbol.iterator]()).eq(iter); 208 | }); 209 | 210 | it("allows foreach (empty)", () => { 211 | const iter = new RoaringBitmap32Iterator(); 212 | expect(iter.next()).deep.equal({ done: true, value: undefined }); 213 | }); 214 | 215 | it("allows foreach (small array)", () => { 216 | const iter = new RoaringBitmap32Iterator(new RoaringBitmap32([123, 456, 789])); 217 | const values = []; 218 | for (const x of iter) { 219 | values.push(x); 220 | } 221 | expect(values).deep.equal([123, 456, 789]); 222 | }); 223 | 224 | it("allows Array.from", () => { 225 | const iter = new RoaringBitmap32Iterator(new RoaringBitmap32([123, 456, 789])); 226 | const values = Array.from(iter); 227 | expect(values).deep.equal([123, 456, 789]); 228 | }); 229 | }); 230 | 231 | describe("RoaringBitmap32 iterable", () => { 232 | it("returns a RoaringBitmap32Iterator", () => { 233 | const bitmap = new RoaringBitmap32(); 234 | const iterator = bitmap[Symbol.iterator](); 235 | expect(iterator).to.be.instanceOf(RoaringBitmap32Iterator); 236 | expect(typeof iterator.next).eq("function"); 237 | }); 238 | 239 | it("returns an empty iterator for an empty bitmap", () => { 240 | const bitmap = new RoaringBitmap32(); 241 | const iterator = bitmap[Symbol.iterator](); 242 | expect(iterator.next()).deep.equal({ 243 | done: true, 244 | value: undefined, 245 | }); 246 | expect(iterator.next()).deep.equal({ 247 | done: true, 248 | value: undefined, 249 | }); 250 | }); 251 | 252 | it("iterates a non empty bitmap", () => { 253 | const bitmap = new RoaringBitmap32([0xffffffff, 3]); 254 | const iterator = bitmap[Symbol.iterator](); 255 | expect(iterator.next()).deep.equal({ 256 | done: false, 257 | value: 3, 258 | }); 259 | expect(iterator.next()).deep.equal({ 260 | done: false, 261 | value: 0xffffffff, 262 | }); 263 | expect(iterator.next()).deep.equal({ 264 | done: true, 265 | value: undefined, 266 | }); 267 | }); 268 | }); 269 | }); 270 | -------------------------------------------------------------------------------- /test/unit/RoaringUint8Array.test.ts: -------------------------------------------------------------------------------- 1 | import { expect } from "chai"; 2 | import { roaringWasm } from "../../packages/roaring-wasm-src/lib/roaring-wasm"; 3 | import { RoaringArenaAllocator, RoaringUint8Array, roaringLibraryInitialize } from "roaring-wasm-src"; 4 | 5 | describe("RoaringUint8Array", () => { 6 | before(roaringLibraryInitialize); 7 | beforeEach(RoaringArenaAllocator.start); 8 | afterEach(RoaringArenaAllocator.stop); 9 | 10 | it("allows creating empty arrays", () => { 11 | const p = new RoaringUint8Array(0); 12 | expect(p.byteLength).eq(0); 13 | expect(p.asTypedArray().length).eq(0); 14 | expect(p.isDisposed).eq(true); 15 | }); 16 | 17 | it("allows creating a small array", () => { 18 | const p = new RoaringUint8Array(12); 19 | expect(p.byteLength).eq(12); 20 | expect(p.asTypedArray().length).eq(12); 21 | expect(p.isDisposed).eq(false); 22 | }); 23 | 24 | it("copies arrays", () => { 25 | const p = new RoaringUint8Array([1, 2, 3]); 26 | expect(p.byteLength).eq(3); 27 | expect(p.asTypedArray().length).eq(3); 28 | expect(Array.from(p.asTypedArray())).deep.eq([1, 2, 3]); 29 | expect(p.isDisposed).eq(false); 30 | }); 31 | 32 | describe("asTypedArray", () => { 33 | it("returns a valid view", () => { 34 | const p = new RoaringUint8Array([1, 2, 3]); 35 | const buf = p.asTypedArray(); 36 | expect(buf.length).eq(3); 37 | expect(buf[0]).eq(1); 38 | expect(buf[1]).eq(2); 39 | expect(buf[2]).eq(3); 40 | expect(buf.buffer === roaringWasm.HEAPU8.buffer).eq(true); 41 | }); 42 | }); 43 | 44 | describe("toTypedArray", () => { 45 | it("returns a copy", () => { 46 | const p = new RoaringUint8Array([1, 2, 3]); 47 | const buf = p.toTypedArray(); 48 | expect(buf.length).eq(3); 49 | expect(buf[0]).eq(1); 50 | expect(buf[1]).eq(2); 51 | expect(buf[2]).eq(3); 52 | expect(buf.buffer !== roaringWasm.HEAPU8.buffer).eq(true); 53 | }); 54 | 55 | it("accepts a smaller output array", () => { 56 | const p = new RoaringUint8Array([1, 2, 3]); 57 | const buf = new Uint8Array(2); 58 | p.toTypedArray(buf); 59 | expect(buf.length).eq(2); 60 | expect(buf[0]).eq(1); 61 | expect(buf[1]).eq(2); 62 | }); 63 | 64 | it("accepts a larger output array", () => { 65 | const p = new RoaringUint8Array([1, 2, 3]); 66 | const buf = new Uint8Array(4); 67 | const ret = p.toTypedArray(buf); 68 | expect(ret.buffer).eq(buf.buffer); 69 | expect(ret.length).eq(3); 70 | expect(ret[0]).eq(1); 71 | expect(ret[1]).eq(2); 72 | expect(ret[2]).eq(3); 73 | }); 74 | 75 | it("accepts same size output array", () => { 76 | const p = new RoaringUint8Array([1, 2, 3]); 77 | const buf = new Uint8Array(3); 78 | const ret = p.toTypedArray(buf); 79 | expect(ret).eq(buf); 80 | expect(ret.length).eq(3); 81 | expect(ret[0]).eq(1); 82 | expect(ret[1]).eq(2); 83 | expect(ret[2]).eq(3); 84 | }); 85 | }); 86 | 87 | describe("dispose", () => { 88 | it("can be called twice", () => { 89 | const p = new RoaringUint8Array([1, 2, 3]); 90 | expect(p.dispose()).eq(true); 91 | expect(p.isDisposed).eq(true); 92 | expect(p.dispose()).eq(false); 93 | expect(p.isDisposed).eq(true); 94 | }); 95 | 96 | it("resets everything", () => { 97 | const p = new RoaringUint8Array([1, 2, 3]); 98 | expect(p.dispose()).eq(true); 99 | expect(p.byteLength).eq(0); 100 | expect(p.asTypedArray().length).eq(0); 101 | expect(p.isDisposed).eq(true); 102 | }); 103 | }); 104 | 105 | describe("throwIfDisposed", () => { 106 | it("does not throw if not disposed", () => { 107 | const p = new RoaringUint8Array(5); 108 | p.throwIfDisposed(); 109 | }); 110 | 111 | it("throws if disposed", () => { 112 | const t = new RoaringUint8Array(4); 113 | t.dispose(); 114 | expect(() => { 115 | t.throwIfDisposed(); 116 | }).to.throw(); 117 | }); 118 | }); 119 | 120 | describe("shrink", () => { 121 | it("should shrink the allocated memory", () => { 122 | const array = new RoaringUint8Array(100); 123 | expect(array.byteLength).eq(100); 124 | expect(array.shrink(50)).true; 125 | expect(array.byteLength).eq(50); 126 | expect(array.shrink(50)).false; 127 | expect(array.byteLength).eq(50); 128 | expect(array.shrink(0)).true; 129 | expect(array.byteLength).eq(0); 130 | expect(array.shrink(0)).false; 131 | expect(array.byteLength).eq(0); 132 | expect(array.isDisposed).true; 133 | }); 134 | }); 135 | 136 | describe("at", () => { 137 | it("should return the value at the given index", () => { 138 | const array = new RoaringUint8Array([1, 2, 3]); 139 | expect(array.at(0)).eq(1); 140 | expect(array.at(1)).eq(2); 141 | expect(array.at(2)).eq(3); 142 | }); 143 | 144 | it("should behaves like array.at() if the index is negative", () => { 145 | const array = new RoaringUint8Array([1, 2, 3]); 146 | expect(array.at(-1)).eq(3); 147 | expect(array.at(-2)).eq(2); 148 | expect(array.at(-3)).eq(1); 149 | }); 150 | 151 | it("shoudl work for floating point values like array.at()", () => { 152 | const array = new RoaringUint8Array([1, 2, 3]); 153 | expect(array.at(0.1)).eq(1); 154 | expect(array.at(1.1)).eq(2); 155 | expect(array.at(2.1)).eq(3); 156 | }); 157 | }); 158 | 159 | describe("setAt", () => { 160 | it("should set the value at the given index", () => { 161 | const array = new RoaringUint8Array([1, 2, 3]); 162 | expect(array.setAt(0, 10)).true; 163 | expect(array.setAt(1, 20)).true; 164 | expect(array.setAt(2, 30)).true; 165 | expect(Array.from(array.asTypedArray())).deep.eq([10, 20, 30]); 166 | }); 167 | 168 | it("should behaves like array.at() if the index is negative", () => { 169 | const array = new RoaringUint8Array([1, 2, 3]); 170 | expect(array.setAt(-1, 10)).true; 171 | expect(array.setAt(-2, 20)).true; 172 | expect(array.setAt(-3, 30)).true; 173 | expect(Array.from(array.asTypedArray())).deep.eq([30, 20, 10]); 174 | }); 175 | 176 | it("should return false if the index is out of bounds", () => { 177 | const array = new RoaringUint8Array([1, 2, 3]); 178 | expect(array.setAt(3, 10)).false; 179 | expect(array.setAt(4, 20)).false; 180 | expect(array.setAt(-5, 30)).false; 181 | expect(Array.from(array.asTypedArray())).deep.eq([1, 2, 3]); 182 | }); 183 | 184 | it("shoudl work for floating point values like array.at()", () => { 185 | const array = new RoaringUint8Array([1, 2, 3]); 186 | expect(array.setAt(0.1, 10)).true; 187 | expect(array.setAt(1.1, 20)).true; 188 | expect(array.setAt(2.1, 30)).true; 189 | expect(Array.from(array.asTypedArray())).deep.eq([10, 20, 30]); 190 | }); 191 | }); 192 | }); 193 | -------------------------------------------------------------------------------- /test/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | roaring-wasm web app 8 | 9 | 10 |
...running
11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /test/web/main.ts: -------------------------------------------------------------------------------- 1 | import "mocha/mocha.css"; 2 | import "./styles.css"; 3 | import "mocha"; 4 | 5 | const progressEl = document.getElementById("progress")!; 6 | let setupCompleted = false; 7 | let failedTests = 0; 8 | 9 | const fail = (message: string) => { 10 | if (failedTests) { 11 | message += ` ${failedTests} failure${failedTests === 1 ? "" : "s"}.`; 12 | } 13 | const inner = document.createElement("div"); 14 | inner.innerText = message.trim(); 15 | inner.className = "failed"; 16 | progressEl.innerHTML = `❌  ${message}.`; 17 | document.body.appendChild(document.createTextNode(message)); 18 | }; 19 | 20 | const pass = () => { 21 | progressEl.classList.remove("running"); 22 | progressEl.classList.add("passed"); 23 | progressEl.innerHTML = '✅   All good!'; 24 | }; 25 | 26 | try { 27 | mocha.setup({ ui: "bdd" }); 28 | 29 | // eslint-disable-next-line @typescript-eslint/await-thenable 30 | const tests = await import.meta.glob("../**/*.test.ts"); 31 | 32 | for (const path in tests) { 33 | await tests[path](); 34 | } 35 | 36 | const runner = mocha.run(); 37 | 38 | runner.on("fail", () => { 39 | ++failedTests; 40 | }); 41 | 42 | runner.on("end", () => { 43 | if (failedTests) { 44 | fail(""); 45 | } else { 46 | pass(); 47 | } 48 | }); 49 | setupCompleted = true; 50 | } finally { 51 | if (!setupCompleted) { 52 | fail("Initialization failed"); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /test/web/roaring.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SalvatorePreviti/roaring-wasm/400554cd8d6f3bba1cb7fc2a812b0bffe0ce230c/test/web/roaring.jpg -------------------------------------------------------------------------------- /test/web/styles.css: -------------------------------------------------------------------------------- 1 | #progress { 2 | margin: 10px; 3 | padding: 8px; 4 | border-radius: 10px; 5 | border: 2px solid #05a; 6 | color: gray; 7 | background: #111; 8 | font-family: "Courier New", Courier, monospace; 9 | font-size: 20px; 10 | line-height: 32px; 11 | font-weight: bold; 12 | vertical-align: middle; 13 | } 14 | 15 | #progress.passed { 16 | color: #0f0; 17 | background-color: #121; 18 | } 19 | 20 | #progress button { 21 | color: #fff; 22 | border: none; 23 | padding: 5px 6px; 24 | margin-left: 32px; 25 | background: transparent; 26 | text-decoration: none; 27 | font-family: "Courier New", Courier, monospace; 28 | } 29 | 30 | #progress.failed { 31 | color: #f55; 32 | background-color: #300; 33 | } 34 | -------------------------------------------------------------------------------- /test/web/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": { 4 | "target": "es2022", 5 | "module": "ESNext", 6 | "lib": ["ES2023", "DOM", "DOM.Iterable"], 7 | "moduleResolution": "bundler", 8 | "allowImportingTsExtensions": true, 9 | "resolveJsonModule": true, 10 | "isolatedModules": true, 11 | "noEmit": true, 12 | "types": ["vite/client"] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /test/web/vite.config.ts: -------------------------------------------------------------------------------- 1 | import { resolve } from "path"; 2 | import { defineConfig } from "vite"; 3 | import { nodePolyfills } from "vite-plugin-node-polyfills"; 4 | 5 | export default defineConfig({ 6 | clearScreen: false, 7 | 8 | root: resolve(__dirname), 9 | define: { "process.env": {} }, 10 | plugins: [nodePolyfills()], 11 | server: { 12 | port: 3000, 13 | host: "127.0.0.1", 14 | strictPort: true, 15 | }, 16 | }); 17 | -------------------------------------------------------------------------------- /tsconfig-build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "emitDeclarationOnly": true, 5 | "declaration": true 6 | }, 7 | "include": ["src/ts/**/*"], 8 | "exclude": ["test/**/*", "node_modules/**/*", ".tmp/**/*", "temp/**/*", "packages/roaring-wasm/**/*", "docs/**/*"] 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": false, 4 | "checkJs": false, 5 | "noEmit": true, 6 | "allowSyntheticDefaultImports": true, 7 | "esModuleInterop": true, 8 | "resolveJsonModule": true, 9 | "allowUnreachableCode": false, 10 | "allowUnusedLabels": false, 11 | "alwaysStrict": true, 12 | "declaration": true, 13 | "emitDecoratorMetadata": false, 14 | "experimentalDecorators": false, 15 | "forceConsistentCasingInFileNames": true, 16 | "importHelpers": false, 17 | "lib": ["esnext", "DOM"], 18 | "module": "commonjs", 19 | "moduleResolution": "node", 20 | "newLine": "LF", 21 | "noFallthroughCasesInSwitch": true, 22 | "noImplicitAny": true, 23 | "noImplicitReturns": true, 24 | "noImplicitThis": true, 25 | "noStrictGenericChecks": false, 26 | "noUnusedLocals": false, 27 | "noUnusedParameters": false, 28 | "pretty": true, 29 | "removeComments": false, 30 | "strict": true, 31 | "skipLibCheck": false, 32 | "skipDefaultLibCheck": false, 33 | "strictFunctionTypes": true, 34 | "strictNullChecks": true, 35 | "strictPropertyInitialization": true, 36 | "target": "ES2022", 37 | "isolatedModules": true 38 | }, 39 | "exclude": ["node_modules", "node_modules/**/*", ".eslintcache/**/*", "temp/**/*", "packages/roaring-wasm/**/*"], 40 | "typeAcquisition": { 41 | "enable": true 42 | }, 43 | "typedocOptions": { 44 | "out": "docs", 45 | "entryPoints": "packages/roaring-wasm/index.d.ts" 46 | } 47 | } 48 | --------------------------------------------------------------------------------