├── .editorconfig ├── .gitattributes ├── .gitignore ├── .nvmrc ├── .watchmanconfig ├── .yarn ├── plugins │ └── @yarnpkg │ │ ├── plugin-interactive-tools.cjs │ │ └── plugin-workspace-tools.cjs └── releases │ └── yarn-3.6.1.cjs ├── .yarnrc.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── android ├── CMakeLists.txt ├── build.gradle ├── cpp-adapter.cpp ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ ├── AndroidManifestNew.xml │ └── java │ └── com │ └── fasturl │ ├── FastTrieBridge.java │ ├── FastTrieModule.java │ └── FastTriePackage.java ├── babel.config.js ├── benchmarks ├── galaxy_a10e.jpeg ├── iphone_11_pro_max.jpeg ├── iphone_15_pro_max.jpeg ├── iphone_7.jpeg ├── pixel_3a.jpeg └── pixel_5.jpeg ├── cpp ├── TrieHostObject.cpp ├── TrieHostObject.h ├── fast-trie.cpp ├── fast-trie.h ├── tsl │ ├── array-hash │ │ ├── array_growth_policy.h │ │ ├── array_hash.h │ │ ├── array_map.h │ │ └── array_set.h │ ├── htrie_hash.h │ ├── htrie_map.h │ └── htrie_set.h └── utils.h ├── example ├── .bundle │ └── config ├── .watchmanconfig ├── Gemfile ├── README.md ├── android │ ├── app │ │ ├── build.gradle │ │ ├── debug.keystore │ │ ├── proguard-rules.pro │ │ └── src │ │ │ ├── debug │ │ │ ├── AndroidManifest.xml │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── fasttrieexample │ │ │ │ └── ReactNativeFlipper.java │ │ │ ├── main │ │ │ ├── AndroidManifest.xml │ │ │ ├── java │ │ │ │ └── com │ │ │ │ │ └── fasttrieexample │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ └── MainApplication.java │ │ │ └── res │ │ │ │ ├── drawable │ │ │ │ └── rn_edit_text_material.xml │ │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ │ └── values │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ │ └── release │ │ │ └── java │ │ │ └── com │ │ │ └── fasttrieexample │ │ │ └── ReactNativeFlipper.java │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── app.json ├── babel.config.js ├── index.js ├── ios │ ├── .xcode.env │ ├── FastTrieExample-Bridging-Header.h │ ├── FastTrieExample.xcodeproj │ │ ├── project.pbxproj │ │ └── xcshareddata │ │ │ └── xcschemes │ │ │ ├── FastTrieExample.xcscheme │ │ │ ├── FastTrieExampleTests.xcscheme │ │ │ └── FastUrlExample.xcscheme.xml │ ├── FastTrieExample.xcworkspace │ │ ├── contents.xcworkspacedata │ │ ├── contents.xcworkspacedata.xml │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ ├── FastTrieExampleTests │ │ ├── FastUrlExampleTests.m │ │ └── Info.plist │ ├── FastUrlExample │ │ ├── AppDelegate.h │ │ ├── AppDelegate.mm │ │ ├── Images.xcassets │ │ │ ├── AppIcon.appiconset │ │ │ │ └── Contents.json │ │ │ └── Contents.json │ │ ├── Info.plist │ │ ├── LaunchScreen.storyboard.xml │ │ └── main.m │ ├── File.swift │ ├── Podfile │ └── Podfile.lock ├── jest.config.js ├── metro.config.js ├── package.json ├── react-native.config.js └── src │ ├── App.tsx │ ├── JsTrie.ts │ ├── Trie.ts │ ├── components │ ├── Button.tsx │ ├── CorrectResultItem.tsx │ ├── IncorrectResultItem.tsx │ ├── Indentator.tsx │ ├── NavigationButton.tsx │ ├── Suite.tsx │ ├── TestItem.tsx │ └── Text.tsx │ ├── screens │ ├── Benchmarks │ │ ├── Benchmarks.tsx │ │ ├── MemoryBenchmarks.tsx │ │ ├── SpeedBenchmarks.tsx │ │ └── benchmarks │ │ │ ├── bench.ts │ │ │ ├── contains.ts │ │ │ ├── find.ts │ │ │ ├── insert.ts │ │ │ └── utils.ts │ ├── Home.tsx │ ├── Tests │ │ ├── Tests.tsx │ │ ├── testList.tsx │ │ ├── tests │ │ │ ├── configurationAndErrorHandlingTests.ts │ │ │ ├── deletionTests.ts │ │ │ ├── findAndContainsTests.ts │ │ │ └── insertionTests.ts │ │ └── types.ts │ └── params.ts │ ├── testing │ ├── MochaRnAdapter.ts │ └── MochaSetup.ts │ └── wordlists │ ├── allWordlists.ts │ ├── wordlist.cz.ts │ ├── wordlist.en.ts │ ├── wordlist.es.ts │ ├── wordlist.fr.ts │ ├── wordlist.it.ts │ ├── wordlist.jp.ts │ ├── wordlist.kr.ts │ ├── wordlist.pt.ts │ ├── wordlist.zh.cn.ts │ └── wordlist.zh.tw.ts ├── ios ├── FastTrie.h └── FastTrie.mm ├── lefthook.yml ├── package.json ├── react-native-fast-trie.podspec ├── scripts └── pod-install.cjs ├── src └── index.tsx ├── tsconfig.build.json ├── tsconfig.json ├── turbo.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # Ruby 48 | example/vendor/ 49 | 50 | # node.js 51 | # 52 | node_modules/ 53 | npm-debug.log 54 | yarn-debug.log 55 | yarn-error.log 56 | 57 | # BUCK 58 | buck-out/ 59 | \.buckd/ 60 | android/app/libs 61 | android/keystores/debug.keystore 62 | 63 | # Yarn 64 | .yarn/* 65 | !.yarn/patches 66 | !.yarn/plugins 67 | !.yarn/releases 68 | !.yarn/sdks 69 | !.yarn/versions 70 | 71 | # Expo 72 | .expo/ 73 | 74 | # Turborepo 75 | .turbo/ 76 | 77 | # generated by bob 78 | lib/ 79 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | v18 2 | -------------------------------------------------------------------------------- /.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | nmHoistingLimits: workspaces 3 | 4 | plugins: 5 | - path: scripts/pod-install.cjs 6 | - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs 7 | spec: "@yarnpkg/plugin-interactive-tools" 8 | - path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs 9 | spec: "@yarnpkg/plugin-workspace-tools" 10 | 11 | yarnPath: .yarn/releases/yarn-3.6.1.cjs 12 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [INSERT CONTACT METHOD]. 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are always welcome, no matter how large or small! 4 | 5 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md). 6 | 7 | ## Development workflow 8 | 9 | This project is a monorepo managed using [Yarn workspaces](https://yarnpkg.com/features/workspaces). It contains the following packages: 10 | 11 | - The library package in the root directory. 12 | - An example app in the `example/` directory. 13 | 14 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package: 15 | 16 | ```sh 17 | yarn 18 | ``` 19 | 20 | > Since the project relies on Yarn workspaces, you cannot use [`npm`](https://github.com/npm/cli) for development. 21 | 22 | The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make. 23 | 24 | It is configured to use the local version of the library, so any changes you make to the library's source code will be reflected in the example app. Changes to the library's JavaScript code will be reflected in the example app without a rebuild, but native code changes will require a rebuild of the example app. 25 | 26 | If you want to use Android Studio or XCode to edit the native code, you can open the `example/android` or `example/ios` directories respectively in those editors. To edit the Objective-C or Swift files, open `example/ios/FastTrieExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-fast-trie`. 27 | 28 | To edit the Java or Kotlin files, open `example/android` in Android studio and find the source files at `react-native-fast-trie` under `Android`. 29 | 30 | You can use various commands from the root directory to work with the project. 31 | 32 | To start the packager: 33 | 34 | ```sh 35 | yarn example start 36 | ``` 37 | 38 | To run the example app on Android: 39 | 40 | ```sh 41 | yarn example android 42 | ``` 43 | 44 | To run the example app on iOS: 45 | 46 | ```sh 47 | yarn example ios 48 | ``` 49 | 50 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 51 | 52 | ```sh 53 | yarn typecheck 54 | yarn lint 55 | ``` 56 | 57 | To fix formatting errors, run the following: 58 | 59 | ```sh 60 | yarn lint --fix 61 | ``` 62 | 63 | Remember to add tests for your change if possible. Run the unit tests by: 64 | 65 | ```sh 66 | yarn test 67 | ``` 68 | 69 | ### Commit message convention 70 | 71 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 72 | 73 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 74 | - `feat`: new features, e.g. add new method to the module. 75 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 76 | - `docs`: changes into documentation, e.g. add usage example for the module.. 77 | - `test`: adding or updating tests, e.g. add integration tests using detox. 78 | - `chore`: tooling changes, e.g. change CI config. 79 | 80 | Our pre-commit hooks verify that your commit message matches this format when committing. 81 | 82 | ### Linting and tests 83 | 84 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 85 | 86 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. 87 | 88 | Our pre-commit hooks verify that the linter and tests pass when committing. 89 | 90 | ### Publishing to npm 91 | 92 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc. 93 | 94 | To publish new versions, run the following: 95 | 96 | ```sh 97 | yarn release 98 | ``` 99 | 100 | ### Scripts 101 | 102 | The `package.json` file contains various scripts for common tasks: 103 | 104 | - `yarn`: setup project by installing dependencies and pods - run with `POD_INSTALL=0` to skip installing pods. 105 | - `yarn typecheck`: type-check files with TypeScript. 106 | - `yarn lint`: lint files with ESLint. 107 | - `yarn test`: run unit tests with Jest. 108 | - `yarn example start`: start the Metro server for the example app. 109 | - `yarn example android`: run the example app on Android. 110 | - `yarn example ios`: run the example app on iOS. 111 | 112 | ### Sending a pull request 113 | 114 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github). 115 | 116 | When you're sending a pull request: 117 | 118 | - Prefer small pull requests focused on one change. 119 | - Verify that linters and tests are passing. 120 | - Review the documentation to make sure it looks good. 121 | - Follow the pull request template when opening a pull request. 122 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 123 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 kusstar 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-fast-trie 2 | 3 | A fast, memory-efficient Trie implementation for React Native. Uses Tessel's [HAT-trie](https://github.com/Tessil/hat-trie). 4 | 5 | - 💾 Low memory footprint 6 | - ⚡️ Extremely fast for contructing large tries 7 | - 🧪 Well tested in JS and C++ 8 | 9 | ## Installation 10 | 11 | ```sh 12 | npm install react-native-fast-trie 13 | yarn add react-native-fast-trie 14 | ``` 15 | 16 | ## Benchmarks 17 | 18 | Benchmarks are taken compared to a commonly-used JS implementation (trie-typed) on real devices built in release mode. You can build the example project on your device to reproduce these results. 19 | 20 | Tests are as follows: 21 | 22 | - **Single Wordlist**: Insert all the words in the english bip39 dictionary into a Trie 23 | - **Batch Insert**: Use the batchInsert method with the entire english bip39 array for FastTrie 24 | - **All Wordlists**: Create a separate trie for each bip39 wordlist by locale and insert into each 25 | - **Contains**: Access 1,000,000 random words from the english bip39 wordlist 26 | - **Find**: Find 1,000,000 substrings of random words from the english bip39 wordlist 27 | 28 | | Device | Single Wordlist | Batch Insert | All Wordlists | Contains | Find | 29 | | ----------------- | --------------- | ------------- | ------------- | ------------ | ------------- | 30 | | Pixel 5 | 4.64x faster | 16.86x faster | 7.76x faster | 2.94x faster | 24.63x faster | 31 | | Pixel 3a | 3.26x faster | 14.67x faster | 5.54x faster | 3.06x faster | 26.23x faster | 32 | | Galaxy A10e | 2.94x faster | 9.83x faster | 4.84x faster | 3.95x faster | 11.47x faster | 33 | | iPhone 15 Pro Max | 3.78x faster | 10.33x faster | 5.13x faster | 3.43x faster | 23.83x faster | 34 | | iPhone 11 Pro Max | 4.65x faster | 13.12x faster | 5.21x faster | 3.35x faster | 23.79x faster | 35 | | iPhone 7 | 3.58x faster | 12.03x faster | 5.65x faster | 3.46x faster | 26.86x faster | 36 | 37 | Screenshots of these benchmarks can be found in the [benchmarks folder](./benchmarks/). 38 | 39 | ## Usage 40 | 41 | ```js 42 | // index.js 43 | import { FastTrie } from 'react-native-fast-trie'; 44 | 45 | const trie = new FastTrie(); 46 | console.log(trie.contains('test')); // false 47 | 48 | trie.insert('test'); 49 | console.log(trie.contains('test')); // true 50 | console.log(trie.find('te')); // ['test'] 51 | 52 | trie.batchInsert(['test2', 'test3']); 53 | 54 | // Limit to only 2 results 55 | console.log(trie.find('te', 2)); // ['test2', 'test3'] 56 | 57 | trie.delete('test2'); 58 | 59 | console.log(trie.contains('test2')); // false 60 | ``` 61 | 62 | ## API 63 | 64 | ### Overview 65 | 66 | FastTrie is a high-performance trie implementation designed for React Native applications. It offers efficient operations for inserting elements, checking for their existence, and finding elements with a specific prefix. The implementation provides customization options to balance between speed and memory usage. 67 | 68 | ### `FastTrieOptions` Type 69 | 70 | This type allows configuration of the FastTrie instance. 71 | 72 | - `burstThreshold?: number` 73 | Specifies the maximum size of an array hash node before a burst occurs. A higher value (e.g., 16,384) is recommended for exact searches, while the default value of 1024 is optimized for prefix searches. 74 | 75 | - `maxLoadFactor?: number` 76 | Determines the load factor of the trie. A lower value increases speed, while a higher value decreases memory usage. The default value is 8.0. 77 | 78 | ### `FastTrie` Class 79 | 80 | #### Constructor 81 | 82 | Creates a new instance of FastTrie. 83 | 84 | - **Parameters:** 85 | 86 | - `options: FastTrieOptions` (optional) 87 | Configuration options for the trie. Includes `burstThreshold` and `maxLoadFactor`. 88 | 89 | - **Example:** 90 | ```javascript 91 | const trie = new FastTrie({ burstThreshold: 2048, maxLoadFactor: 10.0 }); 92 | ``` 93 | 94 | #### Methods 95 | 96 | `insert(item: string): void` 97 | 98 | > Inserts a string into the trie. 99 | 100 | ```javascript 101 | trie.insert('example'); 102 | ``` 103 | 104 | `batchInsert(items: string[]): void` 105 | 106 | > Inserts multiple strings into the trie in a single operation. This method is optimized for bulk insertions and is more efficient than inserting items individually. 107 | 108 | ```javascript 109 | trie.batchInsert(['apple', 'apricot', 'banana']); 110 | ``` 111 | 112 | `contains(item: string): boolean` 113 | 114 | > Checks if a string is present in the trie. 115 | 116 | ```javascript 117 | const isPresent = trie.contains('example'); 118 | ``` 119 | 120 | `find(prefix: string, maxResults?: number): boolean` 121 | 122 | > Finds all strings in the trie that start with the given prefix. 123 | 124 | ```javascript 125 | const results = trie.find('ex', 10); 126 | ``` 127 | 128 | `delete(item: string): void` 129 | 130 | > Deletes a string if it exists in the trie 131 | 132 | ```javascript 133 | trie.delete('apple'); 134 | ``` 135 | 136 | ## Contributing 137 | 138 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 139 | 140 | ## License 141 | 142 | MIT 143 | 144 | --- 145 | 146 | Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob) 147 | -------------------------------------------------------------------------------- /android/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(FastTrie) 2 | cmake_minimum_required(VERSION 3.9.0) 3 | 4 | set(PACKAGE_NAME "fast-trie") 5 | set(CMAKE_VERBOSE_MAKEFILE ON) 6 | set(CMAKE_CXX_STANDARD 17) 7 | set(BUILD_DIR ${CMAKE_SOURCE_DIR}/build) 8 | 9 | # Specifies a path to native header files. 10 | include_directories( 11 | ../cpp 12 | ) 13 | 14 | add_library( 15 | ${PACKAGE_NAME} 16 | SHARED 17 | ../cpp/fast-trie.cpp 18 | ../cpp/TrieHostObject.cpp 19 | cpp-adapter.cpp 20 | ) 21 | 22 | set_target_properties( 23 | ${PACKAGE_NAME} 24 | PROPERTIES CXX_STANDARD 17 25 | CXX_EXTENSIONS OFF 26 | POSITION_INDEPENDENT_CODE ON) 27 | 28 | find_package(ReactAndroid REQUIRED CONFIG) 29 | find_package(fbjni REQUIRED CONFIG) 30 | 31 | target_link_libraries(${PACKAGE_NAME} fbjni::fbjni ReactAndroid::jsi android) 32 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:7.2.1" 9 | } 10 | } 11 | 12 | def resolveBuildType() { 13 | Gradle gradle = getGradle() 14 | String tskReqStr = gradle.getStartParameter().getTaskRequests()['args'].toString() 15 | 16 | return tskReqStr.contains('Release') ? 'release' : 'debug' 17 | } 18 | 19 | def reactNativeArchitectures() { 20 | def value = project.getProperties().get("reactNativeArchitectures") 21 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"] 22 | } 23 | 24 | def isNewArchitectureEnabled() { 25 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true" 26 | } 27 | 28 | apply plugin: "com.android.library" 29 | 30 | if (isNewArchitectureEnabled()) { 31 | apply plugin: "com.facebook.react" 32 | } 33 | 34 | def getExtOrDefault(name) { 35 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["FastTrie_" + name] 36 | } 37 | 38 | def getExtOrIntegerDefault(name) { 39 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["FastTrie_" + name]).toInteger() 40 | } 41 | 42 | def supportsNamespace() { 43 | def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.') 44 | def major = parsed[0].toInteger() 45 | def minor = parsed[1].toInteger() 46 | 47 | // Namespace support was added in 7.3.0 48 | return (major == 7 && minor >= 3) || major >= 8 49 | } 50 | 51 | android { 52 | if (supportsNamespace()) { 53 | namespace "com.fasttrie" 54 | 55 | sourceSets { 56 | main { 57 | manifest.srcFile "src/main/AndroidManifestNew.xml" 58 | } 59 | } 60 | } 61 | 62 | ndkVersion getExtOrDefault("ndkVersion") 63 | compileSdkVersion getExtOrIntegerDefault("compileSdkVersion") 64 | 65 | defaultConfig { 66 | minSdkVersion getExtOrIntegerDefault("minSdkVersion") 67 | targetSdkVersion getExtOrIntegerDefault("targetSdkVersion") 68 | 69 | externalNativeBuild { 70 | cmake { 71 | cppFlags "-O2 -frtti -fexceptions -Wall -fstack-protector-all -DONANDROID -std=c++1y" 72 | arguments '-DANDROID_STL=c++_shared' 73 | abiFilters (*reactNativeArchitectures()) 74 | } 75 | } 76 | 77 | packagingOptions { 78 | doNotStrip resolveBuildType() == 'debug' ? "**/**/*.so" : '' 79 | excludes = [ 80 | "META-INF", 81 | "META-INF/**", 82 | "**/libjsi.so", 83 | "**/libc++_shared.so", 84 | "**/libfbjni.so" 85 | ] 86 | } 87 | } 88 | 89 | externalNativeBuild { 90 | cmake { 91 | path "CMakeLists.txt" 92 | } 93 | } 94 | 95 | buildFeatures { 96 | buildConfig true 97 | prefab true 98 | } 99 | 100 | buildTypes { 101 | release { 102 | minifyEnabled false 103 | } 104 | } 105 | 106 | lintOptions { 107 | disable "GradleCompatible" 108 | } 109 | 110 | compileOptions { 111 | sourceCompatibility JavaVersion.VERSION_1_8 112 | targetCompatibility JavaVersion.VERSION_1_8 113 | } 114 | } 115 | 116 | repositories { 117 | mavenCentral() 118 | google() 119 | } 120 | 121 | 122 | dependencies { 123 | // For < 0.71, this will be from the local maven repo 124 | // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin 125 | //noinspection GradleDynamicVersion 126 | implementation "com.facebook.react:react-native:+" 127 | } 128 | 129 | -------------------------------------------------------------------------------- /android/cpp-adapter.cpp: -------------------------------------------------------------------------------- 1 | #include "fast-trie.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace facebook; 8 | 9 | struct FastTrieBridge : jni::JavaClass { 10 | static constexpr auto kJavaDescriptor = 11 | "Lcom/fasttrie/FastTrieBridge;"; 12 | 13 | static void registerNatives() { 14 | javaClassStatic()->registerNatives( 15 | {// initialization for JSI 16 | makeNativeMethod("installNativeJsi", 17 | FastTrieBridge::installNativeJsi) 18 | }); 19 | } 20 | 21 | private: 22 | static void installNativeJsi( 23 | jni::alias_ref thiz, jlong jsiRuntimePtr) { 24 | auto jsiRuntime = reinterpret_cast(jsiRuntimePtr); 25 | 26 | fasttrie::install(*jsiRuntime); 27 | } 28 | }; 29 | 30 | JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *) { 31 | return jni::initialize(vm, [] { FastTrieBridge::registerNatives(); }); 32 | } 33 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | FastTrie_kotlinVersion=1.7.0 2 | FastTrie_minSdkVersion=21 3 | FastTrie_targetSdkVersion=31 4 | FastTrie_compileSdkVersion=31 5 | FastTrie_ndkversion=21.4.7075529 6 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifestNew.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /android/src/main/java/com/fasturl/FastTrieBridge.java: -------------------------------------------------------------------------------- 1 | package com.fasttrie; 2 | 3 | import android.util.Log; 4 | 5 | import com.facebook.react.bridge.ReactApplicationContext; 6 | import com.facebook.react.bridge.ReactContext; 7 | import com.facebook.react.turbomodule.core.CallInvokerHolderImpl; 8 | 9 | public class FastTrieBridge { 10 | private native void installNativeJsi(long jsContextNativePointer); 11 | 12 | public static final FastTrieBridge instance = new FastTrieBridge(); 13 | 14 | public void install(ReactContext context) { 15 | long jsContextPointer = context.getJavaScriptContextHolder().get(); 16 | installNativeJsi(jsContextPointer); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /android/src/main/java/com/fasturl/FastTrieModule.java: -------------------------------------------------------------------------------- 1 | package com.fasttrie; 2 | 3 | import androidx.annotation.NonNull; 4 | import android.util.Log; 5 | 6 | import com.facebook.react.bridge.Promise; 7 | import com.facebook.react.bridge.ReactApplicationContext; 8 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 9 | import com.facebook.react.bridge.ReactMethod; 10 | import com.facebook.react.module.annotations.ReactModule; 11 | 12 | @ReactModule(name = FastTrieModule.NAME) 13 | public class FastTrieModule extends ReactContextBaseJavaModule { 14 | public static final String NAME = "FastTrie"; 15 | 16 | public FastTrieModule(ReactApplicationContext reactContext) { 17 | super(reactContext); 18 | } 19 | 20 | @Override 21 | @NonNull 22 | public String getName() { 23 | return NAME; 24 | } 25 | 26 | @ReactMethod(isBlockingSynchronousMethod = true) 27 | public boolean install() { 28 | try { 29 | System.loadLibrary("fast-trie"); 30 | FastTrieBridge.instance.install(getReactApplicationContext()); 31 | return true; 32 | } catch (Exception exception) { 33 | Log.e(NAME, "Failed to install JSI Bindings!", exception); 34 | return false; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /android/src/main/java/com/fasturl/FastTriePackage.java: -------------------------------------------------------------------------------- 1 | package com.fasttrie; 2 | 3 | import androidx.annotation.NonNull; 4 | 5 | import com.facebook.react.ReactPackage; 6 | import com.facebook.react.bridge.NativeModule; 7 | import com.facebook.react.bridge.ReactApplicationContext; 8 | import com.facebook.react.uimanager.ViewManager; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Collections; 12 | import java.util.List; 13 | 14 | public class FastTriePackage implements ReactPackage { 15 | @NonNull 16 | @Override 17 | public List createNativeModules(@NonNull ReactApplicationContext reactContext) { 18 | List modules = new ArrayList<>(); 19 | modules.add(new FastTrieModule(reactContext)); 20 | return modules; 21 | } 22 | 23 | @NonNull 24 | @Override 25 | public List createViewManagers(@NonNull ReactApplicationContext reactContext) { 26 | return Collections.emptyList(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /benchmarks/galaxy_a10e.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/benchmarks/galaxy_a10e.jpeg -------------------------------------------------------------------------------- /benchmarks/iphone_11_pro_max.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/benchmarks/iphone_11_pro_max.jpeg -------------------------------------------------------------------------------- /benchmarks/iphone_15_pro_max.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/benchmarks/iphone_15_pro_max.jpeg -------------------------------------------------------------------------------- /benchmarks/iphone_7.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/benchmarks/iphone_7.jpeg -------------------------------------------------------------------------------- /benchmarks/pixel_3a.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/benchmarks/pixel_3a.jpeg -------------------------------------------------------------------------------- /benchmarks/pixel_5.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/benchmarks/pixel_5.jpeg -------------------------------------------------------------------------------- /cpp/TrieHostObject.cpp: -------------------------------------------------------------------------------- 1 | #include "TrieHostObject.h" 2 | 3 | namespace fasttrie 4 | { 5 | 6 | // From docs: https://github.com/Tessil/hat-trie 7 | // The balance between speed and memory usage can be modified through the max_load_factor method. 8 | // A lower max load factor will increase the speed, a higher one will reduce the memory usage. 9 | // Its default value is set to 8.0. 10 | // The default burst threshold, which is the maximum size of an array hash node before a burst occurs, 11 | // is set to 16 384 which provides good performances for exact searches. If you mainly use prefix searches, 12 | // you may want to reduce it to something like 1024 or lower for faster iteration on the results through 13 | // the burst_threshold method. 14 | TrieHostObject::TrieHostObject(size_t burst_threshold, size_t max_load_factor) : _trie(burst_threshold) 15 | { 16 | _trie.max_load_factor(max_load_factor); 17 | } 18 | 19 | std::vector TrieHostObject::getPropertyNames( 20 | jsi::Runtime &rt) 21 | { 22 | std::vector keys; 23 | const char *names[] = {"insert", "batchInsert", "contains", "find", "delete"}; 24 | for (const auto &name : names) 25 | { 26 | keys.push_back(jsi::PropNameID::forAscii(rt, name)); 27 | } 28 | return keys; 29 | }; 30 | 31 | jsi::Value TrieHostObject::get(jsi::Runtime &rt, const jsi::PropNameID &propNameID) 32 | { 33 | std::string propName = propNameID.utf8(rt); 34 | 35 | if (propName == "insert") 36 | { 37 | // Return a JavaScript function that inserts a string into the trie. 38 | return HOST_FN(rt, "insert", 1, { 39 | if (count != 1 || !arguments[0].isString()) 40 | { 41 | throw jsi::JSError(rt, "insert expects a single string argument"); 42 | } 43 | std::string key = arguments[0].asString(rt).utf8(rt); 44 | _trie.insert(key); 45 | return jsi::Value::undefined(); 46 | }); 47 | } 48 | if (propName == "delete") 49 | { 50 | // Return a JavaScript function that inserts a string into the trie. 51 | return HOST_FN(rt, "delete", 1, { 52 | if (count != 1 || !arguments[0].isString()) 53 | { 54 | throw jsi::JSError(rt, "insert expects a single string argument"); 55 | } 56 | std::string key = arguments[0].asString(rt).utf8(rt); 57 | _trie.erase(key); 58 | return jsi::Value::undefined(); 59 | }); 60 | } 61 | if (propName == "batchInsert") 62 | { 63 | // Return a JavaScript function that inserts an array of strings into the trie. 64 | return HOST_FN(rt, "batchInsert", 1, { 65 | if (count != 1 || !arguments[0].isObject() || !arguments[0].asObject(rt).isArray(rt)) 66 | { 67 | throw jsi::JSError(rt, "batchInsert expects an array of strings"); 68 | } 69 | 70 | jsi::Array values = arguments[0].asObject(rt).getArray(rt); 71 | size_t length = values.length(rt); 72 | for (size_t i = 0; i < length; ++i) 73 | { 74 | jsi::Value val = values.getValueAtIndex(rt, i); 75 | if (val.isString()) 76 | { 77 | std::string key = val.asString(rt).utf8(rt); 78 | _trie.insert(key); 79 | } 80 | else 81 | { 82 | // Handle non-string values appropriately, e.g., throw an error 83 | throw jsi::JSError(rt, "All elements of the array must be strings"); 84 | } 85 | } 86 | return jsi::Value::undefined(); 87 | }); 88 | } 89 | 90 | else if (propName == "contains") 91 | { 92 | // Return a JavaScript function that checks if a string is in the trie. 93 | return HOST_FN(rt, "contains", 1, { 94 | if (count != 1 || !arguments[0].isString()) 95 | { 96 | throw jsi::JSError(rt, "contains expects a single string argument"); 97 | } 98 | std::string key = arguments[0].asString(rt).utf8(rt); 99 | auto it = _trie.find(key); 100 | bool found = (it != _trie.end()); 101 | return jsi::Value(found); 102 | }); 103 | } 104 | else if (propName == "find") 105 | { 106 | return HOST_FN(rt, "find", 2, { 107 | if (count < 1 || !arguments[0].isString()) 108 | { 109 | throw jsi::JSError(rt, "find expects at least one argument, a string"); 110 | } 111 | if (count > 1 && !arguments[1].isUndefined() && !arguments[1].isNumber()) 112 | { 113 | throw jsi::JSError(rt, "Second argument to find must be a number or undefined"); 114 | } 115 | 116 | std::string prefix = arguments[0].asString(rt).utf8(rt); 117 | size_t maxResults = std::numeric_limits::max(); 118 | if (count > 1 && arguments[1].isNumber()) 119 | { 120 | maxResults = arguments[1].asNumber(); 121 | } 122 | 123 | auto range = _trie.equal_prefix_range(prefix); 124 | 125 | // First iteration to determine the size 126 | size_t determinedSize = 0; 127 | for (auto it = range.first; it != range.second && determinedSize < maxResults; ++it) 128 | { 129 | ++determinedSize; 130 | } 131 | 132 | // Create the jsi::Array with the determined size 133 | jsi::Array resultArray = jsi::Array(rt, determinedSize); 134 | 135 | // Second iteration to populate the jsi::Array 136 | size_t index = 0; 137 | for (auto it = range.first; it != range.second && index < maxResults; ++it, ++index) 138 | { 139 | resultArray.setValueAtIndex(rt, index, jsi::String::createFromUtf8(rt, it.key())); 140 | } 141 | 142 | return resultArray; 143 | }); 144 | } 145 | 146 | return jsi::Value::undefined(); 147 | } 148 | 149 | } // namespace fasttrie 150 | -------------------------------------------------------------------------------- /cpp/TrieHostObject.h: -------------------------------------------------------------------------------- 1 | #ifndef FASTTRIE_HOSTOBJECT_H 2 | #define FASTTRIE_HOSTOBJECT_H 3 | 4 | #include "utils.h" 5 | #include "tsl/htrie_set.h" 6 | 7 | namespace fasttrie { 8 | namespace jsi = facebook::jsi; 9 | 10 | class JSI_EXPORT TrieHostObject : public jsi::HostObject { 11 | public: 12 | TrieHostObject(size_t burst_threshold, size_t max_load_factor); 13 | 14 | std::vector getPropertyNames(jsi::Runtime &rt); 15 | jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propNameID); 16 | 17 | private: 18 | tsl::htrie_set _trie; 19 | }; 20 | 21 | } // namespace fasttrie 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /cpp/fast-trie.cpp: -------------------------------------------------------------------------------- 1 | #include "fast-trie.h" 2 | 3 | #include "TrieHostObject.h" 4 | 5 | namespace fasttrie { 6 | namespace jsi = facebook::jsi; 7 | 8 | void install(jsi::Runtime &rt) { 9 | auto FastTrie = HOST_FN(rt, "FastTrie", 2, { 10 | if (count != 2 || !arguments[0].isNumber() || !arguments[1].isNumber()) { 11 | throw jsi::JSError(rt, "FastTrie expects two number arguments"); 12 | } 13 | size_t burst_threshold = arguments[0].asNumber(); 14 | size_t max_load_factor = arguments[1].asNumber(); 15 | 16 | return jsi::Object::createFromHostObject( 17 | rt, std::make_shared( 18 | TrieHostObject(burst_threshold, max_load_factor))); 19 | }); 20 | 21 | rt.global().setProperty(rt, "__FastTrie", std::move(FastTrie)); 22 | } 23 | } // namespace fasttrie 24 | -------------------------------------------------------------------------------- /cpp/fast-trie.h: -------------------------------------------------------------------------------- 1 | #ifndef FASTTRIE_H 2 | #define FASTTRIE_H 3 | 4 | #include "utils.h" 5 | 6 | namespace fasttrie { 7 | void install(facebook::jsi::Runtime &runtime); 8 | } 9 | 10 | #endif /* FASTTRIE_H */ 11 | -------------------------------------------------------------------------------- /cpp/tsl/array-hash/array_growth_policy.h: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright (c) 2017 Thibaut Goetghebuer-Planchon 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | #ifndef TSL_ARRAY_GROWTH_POLICY_H 25 | #define TSL_ARRAY_GROWTH_POLICY_H 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | namespace tsl { 39 | namespace ah { 40 | 41 | /** 42 | * Grow the hash table by a factor of GrowthFactor keeping the bucket count to a 43 | * power of two. It allows the table to use a mask operation instead of a modulo 44 | * operation to map a hash to a bucket. 45 | * 46 | * GrowthFactor must be a power of two >= 2. 47 | */ 48 | template 49 | class power_of_two_growth_policy { 50 | public: 51 | /** 52 | * Called on the hash table creation and on rehash. The number of buckets for 53 | * the table is passed in parameter. This number is a minimum, the policy may 54 | * update this value with a higher value if needed (but not lower). 55 | * 56 | * If 0 is given, min_bucket_count_in_out must still be 0 after the policy 57 | * creation and bucket_for_hash must always return 0 in this case. 58 | */ 59 | explicit power_of_two_growth_policy(std::size_t& min_bucket_count_in_out) { 60 | if (min_bucket_count_in_out > max_bucket_count()) { 61 | throw std::length_error("The hash table exceeds its maximum size."); 62 | } 63 | 64 | if (min_bucket_count_in_out > 0) { 65 | min_bucket_count_in_out = 66 | round_up_to_power_of_two(min_bucket_count_in_out); 67 | m_mask = min_bucket_count_in_out - 1; 68 | } else { 69 | m_mask = 0; 70 | } 71 | } 72 | 73 | /** 74 | * Return the bucket [0, bucket_count()) to which the hash belongs. 75 | * If bucket_count() is 0, it must always return 0. 76 | */ 77 | std::size_t bucket_for_hash(std::size_t hash) const noexcept { 78 | return hash & m_mask; 79 | } 80 | 81 | /** 82 | * Return the number of buckets that should be used on next growth. 83 | */ 84 | std::size_t next_bucket_count() const { 85 | if ((m_mask + 1) > max_bucket_count() / GrowthFactor) { 86 | throw std::length_error("The hash table exceeds its maximum size."); 87 | } 88 | 89 | return (m_mask + 1) * GrowthFactor; 90 | } 91 | 92 | /** 93 | * Return the maximum number of buckets supported by the policy. 94 | */ 95 | std::size_t max_bucket_count() const { 96 | // Largest power of two. 97 | return (std::numeric_limits::max() / 2) + 1; 98 | } 99 | 100 | /** 101 | * Reset the growth policy as if it was created with a bucket count of 0. 102 | * After a clear, the policy must always return 0 when bucket_for_hash is 103 | * called. 104 | */ 105 | void clear() noexcept { m_mask = 0; } 106 | 107 | private: 108 | static std::size_t round_up_to_power_of_two(std::size_t value) { 109 | if (is_power_of_two(value)) { 110 | return value; 111 | } 112 | 113 | if (value == 0) { 114 | return 1; 115 | } 116 | 117 | --value; 118 | for (std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) { 119 | value |= value >> i; 120 | } 121 | 122 | return value + 1; 123 | } 124 | 125 | static constexpr bool is_power_of_two(std::size_t value) { 126 | return value != 0 && (value & (value - 1)) == 0; 127 | } 128 | 129 | protected: 130 | static_assert(is_power_of_two(GrowthFactor) && GrowthFactor >= 2, 131 | "GrowthFactor must be a power of two >= 2."); 132 | 133 | std::size_t m_mask; 134 | }; 135 | 136 | /** 137 | * Grow the hash table by GrowthFactor::num / GrowthFactor::den and use a modulo 138 | * to map a hash to a bucket. Slower but it can be useful if you want a slower 139 | * growth. 140 | */ 141 | template > 142 | class mod_growth_policy { 143 | public: 144 | explicit mod_growth_policy(std::size_t& min_bucket_count_in_out) { 145 | if (min_bucket_count_in_out > max_bucket_count()) { 146 | throw std::length_error("The hash table exceeds its maximum size."); 147 | } 148 | 149 | if (min_bucket_count_in_out > 0) { 150 | m_mod = min_bucket_count_in_out; 151 | } else { 152 | m_mod = 1; 153 | } 154 | } 155 | 156 | std::size_t bucket_for_hash(std::size_t hash) const noexcept { 157 | return hash % m_mod; 158 | } 159 | 160 | std::size_t next_bucket_count() const { 161 | if (m_mod == max_bucket_count()) { 162 | throw std::length_error("The hash table exceeds its maximum size."); 163 | } 164 | 165 | const double next_bucket_count = 166 | std::ceil(double(m_mod) * REHASH_SIZE_MULTIPLICATION_FACTOR); 167 | if (!std::isnormal(next_bucket_count)) { 168 | throw std::length_error("The hash table exceeds its maximum size."); 169 | } 170 | 171 | if (next_bucket_count > double(max_bucket_count())) { 172 | return max_bucket_count(); 173 | } else { 174 | return std::size_t(next_bucket_count); 175 | } 176 | } 177 | 178 | std::size_t max_bucket_count() const { return MAX_BUCKET_COUNT; } 179 | 180 | void clear() noexcept { m_mod = 1; } 181 | 182 | private: 183 | static constexpr double REHASH_SIZE_MULTIPLICATION_FACTOR = 184 | 1.0 * GrowthFactor::num / GrowthFactor::den; 185 | static const std::size_t MAX_BUCKET_COUNT = 186 | std::size_t(double(std::numeric_limits::max() / 187 | REHASH_SIZE_MULTIPLICATION_FACTOR)); 188 | 189 | static_assert(REHASH_SIZE_MULTIPLICATION_FACTOR >= 1.1, 190 | "Growth factor should be >= 1.1."); 191 | 192 | std::size_t m_mod; 193 | }; 194 | 195 | namespace detail { 196 | 197 | #if SIZE_MAX >= ULLONG_MAX 198 | #define TSL_AH_NB_PRIMES 51 199 | #elif SIZE_MAX >= ULONG_MAX 200 | #define TSL_AH_NB_PRIMES 40 201 | #else 202 | #define TSL_AH_NB_PRIMES 23 203 | #endif 204 | 205 | static constexpr const std::array PRIMES = {{ 206 | 1u, 207 | 5u, 208 | 17u, 209 | 29u, 210 | 37u, 211 | 53u, 212 | 67u, 213 | 79u, 214 | 97u, 215 | 131u, 216 | 193u, 217 | 257u, 218 | 389u, 219 | 521u, 220 | 769u, 221 | 1031u, 222 | 1543u, 223 | 2053u, 224 | 3079u, 225 | 6151u, 226 | 12289u, 227 | 24593u, 228 | 49157u, 229 | #if SIZE_MAX >= ULONG_MAX 230 | 98317ul, 231 | 196613ul, 232 | 393241ul, 233 | 786433ul, 234 | 1572869ul, 235 | 3145739ul, 236 | 6291469ul, 237 | 12582917ul, 238 | 25165843ul, 239 | 50331653ul, 240 | 100663319ul, 241 | 201326611ul, 242 | 402653189ul, 243 | 805306457ul, 244 | 1610612741ul, 245 | 3221225473ul, 246 | 4294967291ul, 247 | #endif 248 | #if SIZE_MAX >= ULLONG_MAX 249 | 6442450939ull, 250 | 12884901893ull, 251 | 25769803751ull, 252 | 51539607551ull, 253 | 103079215111ull, 254 | 206158430209ull, 255 | 412316860441ull, 256 | 824633720831ull, 257 | 1649267441651ull, 258 | 3298534883309ull, 259 | 6597069766657ull, 260 | #endif 261 | }}; 262 | 263 | template 264 | static constexpr std::size_t mod(std::size_t hash) { 265 | return hash % PRIMES[IPrime]; 266 | } 267 | 268 | // MOD_PRIME[iprime](hash) returns hash % PRIMES[iprime]. This table allows for 269 | // faster modulo as the compiler can optimize the modulo code better with a 270 | // constant known at the compilation. 271 | static constexpr const std::array 273 | MOD_PRIME = {{ 274 | &mod<0>, &mod<1>, &mod<2>, &mod<3>, &mod<4>, &mod<5>, 275 | &mod<6>, &mod<7>, &mod<8>, &mod<9>, &mod<10>, &mod<11>, 276 | &mod<12>, &mod<13>, &mod<14>, &mod<15>, &mod<16>, &mod<17>, 277 | &mod<18>, &mod<19>, &mod<20>, &mod<21>, &mod<22>, 278 | #if SIZE_MAX >= ULONG_MAX 279 | &mod<23>, &mod<24>, &mod<25>, &mod<26>, &mod<27>, &mod<28>, 280 | &mod<29>, &mod<30>, &mod<31>, &mod<32>, &mod<33>, &mod<34>, 281 | &mod<35>, &mod<36>, &mod<37>, &mod<38>, &mod<39>, 282 | #endif 283 | #if SIZE_MAX >= ULLONG_MAX 284 | &mod<40>, &mod<41>, &mod<42>, &mod<43>, &mod<44>, &mod<45>, 285 | &mod<46>, &mod<47>, &mod<48>, &mod<49>, &mod<50>, 286 | #endif 287 | }}; 288 | 289 | } // namespace detail 290 | 291 | /** 292 | * Grow the hash table by using prime numbers as bucket count. Slower than 293 | * tsl::ah::power_of_two_growth_policy in general but will probably distribute 294 | * the values around better in the buckets with a poor hash function. 295 | * 296 | * To allow the compiler to optimize the modulo operation, a lookup table is 297 | * used with constant primes numbers. 298 | * 299 | * With a switch the code would look like: 300 | * \code 301 | * switch(iprime) { // iprime is the current prime of the hash table 302 | * case 0: hash % 5ul; 303 | * break; 304 | * case 1: hash % 17ul; 305 | * break; 306 | * case 2: hash % 29ul; 307 | * break; 308 | * ... 309 | * } 310 | * \endcode 311 | * 312 | * Due to the constant variable in the modulo the compiler is able to optimize 313 | * the operation by a series of multiplications, substractions and shifts. 314 | * 315 | * The 'hash % 5' could become something like 'hash - (hash * 0xCCCCCCCD) >> 34) 316 | * * 5' in a 64 bits environment. 317 | */ 318 | class prime_growth_policy { 319 | public: 320 | explicit prime_growth_policy(std::size_t& min_bucket_count_in_out) { 321 | auto it_prime = std::lower_bound( 322 | detail::PRIMES.begin(), detail::PRIMES.end(), min_bucket_count_in_out); 323 | if (it_prime == detail::PRIMES.end()) { 324 | throw std::length_error("The hash table exceeds its maximum size."); 325 | } 326 | 327 | m_iprime = static_cast( 328 | std::distance(detail::PRIMES.begin(), it_prime)); 329 | if (min_bucket_count_in_out > 0) { 330 | min_bucket_count_in_out = *it_prime; 331 | } else { 332 | min_bucket_count_in_out = 0; 333 | } 334 | } 335 | 336 | std::size_t bucket_for_hash(std::size_t hash) const noexcept { 337 | return detail::MOD_PRIME[m_iprime](hash); 338 | } 339 | 340 | std::size_t next_bucket_count() const { 341 | if (m_iprime + 1 >= detail::PRIMES.size()) { 342 | throw std::length_error("The hash table exceeds its maximum size."); 343 | } 344 | 345 | return detail::PRIMES[m_iprime + 1]; 346 | } 347 | 348 | std::size_t max_bucket_count() const { return detail::PRIMES.back(); } 349 | 350 | void clear() noexcept { m_iprime = 0; } 351 | 352 | private: 353 | unsigned int m_iprime; 354 | 355 | static_assert(std::numeric_limits::max() >= 356 | detail::PRIMES.size(), 357 | "The type of m_iprime is not big enough."); 358 | }; 359 | 360 | } // namespace ah 361 | } // namespace tsl 362 | 363 | #endif 364 | -------------------------------------------------------------------------------- /cpp/tsl/htrie_set.h: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright (c) 2017 Thibaut Goetghebuer-Planchon 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in 14 | * all copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | #ifndef TSL_HTRIE_SET_H 25 | #define TSL_HTRIE_SET_H 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "htrie_hash.h" 34 | 35 | namespace tsl { 36 | 37 | /** 38 | * Implementation of a hat-trie set. 39 | * 40 | * The size of a key string is limited to std::numeric_limits::max() 41 | * - 1. That is 65 535 characters by default, but can be raised with the 42 | * KeySizeT template parameter. See max_key_size() for an easy access to this 43 | * limit. 44 | * 45 | * Iterators invalidation: 46 | * - clear, operator=: always invalidate the iterators. 47 | * - insert: always invalidate the iterators. 48 | * - erase: always invalidate the iterators. 49 | */ 50 | template , 51 | class KeySizeT = std::uint16_t> 52 | class htrie_set { 53 | private: 54 | template 55 | using is_iterator = tsl::detail_array_hash::is_iterator; 56 | 57 | using ht = tsl::detail_htrie_hash::htrie_hash; 58 | 59 | public: 60 | using char_type = typename ht::char_type; 61 | using key_size_type = typename ht::key_size_type; 62 | using size_type = typename ht::size_type; 63 | using hasher = typename ht::hasher; 64 | using iterator = typename ht::iterator; 65 | using const_iterator = typename ht::const_iterator; 66 | using prefix_iterator = typename ht::prefix_iterator; 67 | using const_prefix_iterator = typename ht::const_prefix_iterator; 68 | 69 | public: 70 | explicit htrie_set(const Hash& hash = Hash()) 71 | : m_ht(hash, ht::HASH_NODE_DEFAULT_MAX_LOAD_FACTOR, 72 | ht::DEFAULT_BURST_THRESHOLD) {} 73 | 74 | explicit htrie_set(size_type burst_threshold, const Hash& hash = Hash()) 75 | : m_ht(hash, ht::HASH_NODE_DEFAULT_MAX_LOAD_FACTOR, burst_threshold) {} 76 | 77 | template ::value>::type* = nullptr> 79 | htrie_set(InputIt first, InputIt last, const Hash& hash = Hash()) 80 | : htrie_set(hash) { 81 | insert(first, last); 82 | } 83 | 84 | #ifdef TSL_HT_HAS_STRING_VIEW 85 | htrie_set(std::initializer_list> init, 86 | const Hash& hash = Hash()) 87 | : htrie_set(hash) { 88 | insert(init); 89 | } 90 | #else 91 | htrie_set(std::initializer_list init, const Hash& hash = Hash()) 92 | : htrie_set(hash) { 93 | insert(init); 94 | } 95 | #endif 96 | 97 | #ifdef TSL_HT_HAS_STRING_VIEW 98 | htrie_set& operator=( 99 | std::initializer_list> ilist) { 100 | clear(); 101 | insert(ilist); 102 | 103 | return *this; 104 | } 105 | #else 106 | htrie_set& operator=(std::initializer_list ilist) { 107 | clear(); 108 | insert(ilist); 109 | 110 | return *this; 111 | } 112 | #endif 113 | 114 | /* 115 | * Iterators 116 | */ 117 | iterator begin() noexcept { return m_ht.begin(); } 118 | const_iterator begin() const noexcept { return m_ht.begin(); } 119 | const_iterator cbegin() const noexcept { return m_ht.cbegin(); } 120 | 121 | iterator end() noexcept { return m_ht.end(); } 122 | const_iterator end() const noexcept { return m_ht.end(); } 123 | const_iterator cend() const noexcept { return m_ht.cend(); } 124 | 125 | /* 126 | * Capacity 127 | */ 128 | bool empty() const noexcept { return m_ht.empty(); } 129 | size_type size() const noexcept { return m_ht.size(); } 130 | size_type max_size() const noexcept { return m_ht.max_size(); } 131 | size_type max_key_size() const noexcept { return m_ht.max_key_size(); } 132 | 133 | /** 134 | * Call shrink_to_fit() on each hash node of the hat-trie to reduce its size. 135 | */ 136 | void shrink_to_fit() { m_ht.shrink_to_fit(); } 137 | 138 | /* 139 | * Modifiers 140 | */ 141 | void clear() noexcept { m_ht.clear(); } 142 | 143 | std::pair insert_ks(const CharT* key, size_type key_size) { 144 | return m_ht.insert(key, key_size); 145 | } 146 | #ifdef TSL_HT_HAS_STRING_VIEW 147 | std::pair insert(const std::basic_string_view& key) { 148 | return m_ht.insert(key.data(), key.size()); 149 | } 150 | #else 151 | std::pair insert(const CharT* key) { 152 | return m_ht.insert(key, std::strlen(key)); 153 | } 154 | 155 | std::pair insert(const std::basic_string& key) { 156 | return m_ht.insert(key.data(), key.size()); 157 | } 158 | #endif 159 | 160 | template ::value>::type* = nullptr> 162 | void insert(InputIt first, InputIt last) { 163 | for (auto it = first; it != last; ++it) { 164 | insert(*it); 165 | } 166 | } 167 | 168 | #ifdef TSL_HT_HAS_STRING_VIEW 169 | void insert(std::initializer_list> ilist) { 170 | insert(ilist.begin(), ilist.end()); 171 | } 172 | #else 173 | void insert(std::initializer_list ilist) { 174 | insert(ilist.begin(), ilist.end()); 175 | } 176 | #endif 177 | 178 | std::pair emplace_ks(const CharT* key, size_type key_size) { 179 | return m_ht.insert(key, key_size); 180 | } 181 | #ifdef TSL_HT_HAS_STRING_VIEW 182 | std::pair emplace(const std::basic_string_view& key) { 183 | return m_ht.insert(key.data(), key.size()); 184 | } 185 | #else 186 | std::pair emplace(const CharT* key) { 187 | return m_ht.insert(key, std::strlen(key)); 188 | } 189 | 190 | std::pair emplace(const std::basic_string& key) { 191 | return m_ht.insert(key.data(), key.size()); 192 | } 193 | #endif 194 | 195 | iterator erase(const_iterator pos) { return m_ht.erase(pos); } 196 | iterator erase(const_iterator first, const_iterator last) { 197 | return m_ht.erase(first, last); 198 | } 199 | 200 | size_type erase_ks(const CharT* key, size_type key_size) { 201 | return m_ht.erase(key, key_size); 202 | } 203 | #ifdef TSL_HT_HAS_STRING_VIEW 204 | size_type erase(const std::basic_string_view& key) { 205 | return m_ht.erase(key.data(), key.size()); 206 | } 207 | #else 208 | size_type erase(const CharT* key) { 209 | return m_ht.erase(key, std::strlen(key)); 210 | } 211 | 212 | size_type erase(const std::basic_string& key) { 213 | return m_ht.erase(key.data(), key.size()); 214 | } 215 | #endif 216 | 217 | /** 218 | * Erase all the elements which have 'prefix' as prefix. Return the number of 219 | * erase elements. 220 | */ 221 | size_type erase_prefix_ks(const CharT* prefix, size_type prefix_size) { 222 | return m_ht.erase_prefix(prefix, prefix_size); 223 | } 224 | #ifdef TSL_HT_HAS_STRING_VIEW 225 | /** 226 | * @copydoc erase_prefix_ks(const CharT* prefix, size_type prefix_size) 227 | */ 228 | size_type erase_prefix(const std::basic_string_view& prefix) { 229 | return m_ht.erase_prefix(prefix.data(), prefix.size()); 230 | } 231 | #else 232 | /** 233 | * @copydoc erase_prefix_ks(const CharT* prefix, size_type prefix_size) 234 | */ 235 | size_type erase_prefix(const CharT* prefix) { 236 | return m_ht.erase_prefix(prefix, std::strlen(prefix)); 237 | } 238 | 239 | /** 240 | * @copydoc erase_prefix_ks(const CharT* prefix, size_type prefix_size) 241 | */ 242 | size_type erase_prefix(const std::basic_string& prefix) { 243 | return m_ht.erase_prefix(prefix.data(), prefix.size()); 244 | } 245 | #endif 246 | 247 | void swap(htrie_set& other) { other.m_ht.swap(m_ht); } 248 | 249 | /* 250 | * Lookup 251 | */ 252 | size_type count_ks(const CharT* key, size_type key_size) const { 253 | return m_ht.count(key, key_size); 254 | } 255 | #ifdef TSL_HT_HAS_STRING_VIEW 256 | size_type count(const std::basic_string_view& key) const { 257 | return m_ht.count(key.data(), key.size()); 258 | } 259 | #else 260 | size_type count(const CharT* key) const { 261 | return m_ht.count(key, std::strlen(key)); 262 | } 263 | size_type count(const std::basic_string& key) const { 264 | return m_ht.count(key.data(), key.size()); 265 | } 266 | #endif 267 | 268 | iterator find_ks(const CharT* key, size_type key_size) { 269 | return m_ht.find(key, key_size); 270 | } 271 | 272 | const_iterator find_ks(const CharT* key, size_type key_size) const { 273 | return m_ht.find(key, key_size); 274 | } 275 | #ifdef TSL_HT_HAS_STRING_VIEW 276 | iterator find(const std::basic_string_view& key) { 277 | return m_ht.find(key.data(), key.size()); 278 | } 279 | 280 | const_iterator find(const std::basic_string_view& key) const { 281 | return m_ht.find(key.data(), key.size()); 282 | } 283 | #else 284 | iterator find(const CharT* key) { return m_ht.find(key, std::strlen(key)); } 285 | 286 | const_iterator find(const CharT* key) const { 287 | return m_ht.find(key, std::strlen(key)); 288 | } 289 | 290 | iterator find(const std::basic_string& key) { 291 | return m_ht.find(key.data(), key.size()); 292 | } 293 | 294 | const_iterator find(const std::basic_string& key) const { 295 | return m_ht.find(key.data(), key.size()); 296 | } 297 | #endif 298 | 299 | std::pair equal_range_ks(const CharT* key, 300 | size_type key_size) { 301 | return m_ht.equal_range(key, key_size); 302 | } 303 | 304 | std::pair equal_range_ks( 305 | const CharT* key, size_type key_size) const { 306 | return m_ht.equal_range(key, key_size); 307 | } 308 | #ifdef TSL_HT_HAS_STRING_VIEW 309 | std::pair equal_range( 310 | const std::basic_string_view& key) { 311 | return m_ht.equal_range(key.data(), key.size()); 312 | } 313 | 314 | std::pair equal_range( 315 | const std::basic_string_view& key) const { 316 | return m_ht.equal_range(key.data(), key.size()); 317 | } 318 | #else 319 | std::pair equal_range(const CharT* key) { 320 | return m_ht.equal_range(key, std::strlen(key)); 321 | } 322 | 323 | std::pair equal_range( 324 | const CharT* key) const { 325 | return m_ht.equal_range(key, std::strlen(key)); 326 | } 327 | 328 | std::pair equal_range( 329 | const std::basic_string& key) { 330 | return m_ht.equal_range(key.data(), key.size()); 331 | } 332 | 333 | std::pair equal_range( 334 | const std::basic_string& key) const { 335 | return m_ht.equal_range(key.data(), key.size()); 336 | } 337 | #endif 338 | 339 | /** 340 | * Return a range containing all the elements which have 'prefix' as prefix. 341 | * The range is defined by a pair of iterator, the first being the begin 342 | * iterator and the second being the end iterator. 343 | */ 344 | std::pair equal_prefix_range_ks( 345 | const CharT* prefix, size_type prefix_size) { 346 | return m_ht.equal_prefix_range(prefix, prefix_size); 347 | } 348 | 349 | /** 350 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 351 | */ 352 | std::pair equal_prefix_range_ks( 353 | const CharT* prefix, size_type prefix_size) const { 354 | return m_ht.equal_prefix_range(prefix, prefix_size); 355 | } 356 | #ifdef TSL_HT_HAS_STRING_VIEW 357 | /** 358 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 359 | */ 360 | std::pair equal_prefix_range( 361 | const std::basic_string_view& prefix) { 362 | return m_ht.equal_prefix_range(prefix.data(), prefix.size()); 363 | } 364 | 365 | /** 366 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 367 | */ 368 | std::pair equal_prefix_range( 369 | const std::basic_string_view& prefix) const { 370 | return m_ht.equal_prefix_range(prefix.data(), prefix.size()); 371 | } 372 | #else 373 | /** 374 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 375 | */ 376 | std::pair equal_prefix_range( 377 | const CharT* prefix) { 378 | return m_ht.equal_prefix_range(prefix, std::strlen(prefix)); 379 | } 380 | 381 | /** 382 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 383 | */ 384 | std::pair equal_prefix_range( 385 | const CharT* prefix) const { 386 | return m_ht.equal_prefix_range(prefix, std::strlen(prefix)); 387 | } 388 | 389 | /** 390 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 391 | */ 392 | std::pair equal_prefix_range( 393 | const std::basic_string& prefix) { 394 | return m_ht.equal_prefix_range(prefix.data(), prefix.size()); 395 | } 396 | 397 | /** 398 | * @copydoc equal_prefix_range_ks(const CharT* prefix, size_type prefix_size) 399 | */ 400 | std::pair equal_prefix_range( 401 | const std::basic_string& prefix) const { 402 | return m_ht.equal_prefix_range(prefix.data(), prefix.size()); 403 | } 404 | #endif 405 | 406 | /** 407 | * Return the element in the trie which is the longest prefix of `key`. If no 408 | * element in the trie is a prefix of `key`, the end iterator is returned. 409 | * 410 | * Example: 411 | * 412 | * tsl::htrie_set set = {"/foo", "/foo/bar"}; 413 | * 414 | * set.longest_prefix("/foo"); // returns "/foo" 415 | * set.longest_prefix("/foo/baz"); // returns "/foo" 416 | * set.longest_prefix("/foo/bar/baz"); // returns "/foo/bar" 417 | * set.longest_prefix("/foo/bar/"); // returns "/foo/bar" 418 | * set.longest_prefix("/bar"); // returns end() 419 | * set.longest_prefix(""); // returns end() 420 | */ 421 | iterator longest_prefix_ks(const CharT* key, size_type key_size) { 422 | return m_ht.longest_prefix(key, key_size); 423 | } 424 | 425 | /** 426 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 427 | */ 428 | const_iterator longest_prefix_ks(const CharT* key, size_type key_size) const { 429 | return m_ht.longest_prefix(key, key_size); 430 | } 431 | #ifdef TSL_HT_HAS_STRING_VIEW 432 | /** 433 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 434 | */ 435 | iterator longest_prefix(const std::basic_string_view& key) { 436 | return m_ht.longest_prefix(key.data(), key.size()); 437 | } 438 | 439 | /** 440 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 441 | */ 442 | const_iterator longest_prefix( 443 | const std::basic_string_view& key) const { 444 | return m_ht.longest_prefix(key.data(), key.size()); 445 | } 446 | #else 447 | /** 448 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 449 | */ 450 | iterator longest_prefix(const CharT* key) { 451 | return m_ht.longest_prefix(key, std::strlen(key)); 452 | } 453 | 454 | /** 455 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 456 | */ 457 | const_iterator longest_prefix(const CharT* key) const { 458 | return m_ht.longest_prefix(key, std::strlen(key)); 459 | } 460 | 461 | /** 462 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 463 | */ 464 | iterator longest_prefix(const std::basic_string& key) { 465 | return m_ht.longest_prefix(key.data(), key.size()); 466 | } 467 | 468 | /** 469 | * @copydoc longest_prefix_ks(const CharT* key, size_type key_size) 470 | */ 471 | const_iterator longest_prefix(const std::basic_string& key) const { 472 | return m_ht.longest_prefix(key.data(), key.size()); 473 | } 474 | #endif 475 | 476 | /** 477 | * Invoke the given `visitor` function for each element in the trie which is 478 | * a prefix of `key`. 479 | * 480 | * @tparam F Callable target taking a single `iterator` or `const_iterator` 481 | * argument. 482 | * 483 | * Example: 484 | * 485 | * tsl::htrie_set set = {"/foo", "/foo/bar"}; 486 | * auto print = [](tsl::htrie_set::iterator it) { 487 | * std::cout << it.key() << "\n"; 488 | * }; 489 | * 490 | * set.for_each_prefix_of("/foo", print); // prints "/foo" 491 | * set.for_each_prefix_of("/foo/baz"); // prints nothing 492 | * set.for_each_prefix_of("/foo/bar/baz"); // prints nothing 493 | * set.for_each_prefix_of("/foo/bar/"); // prints "/foo" and "/foo/bar" 494 | * set.for_each_prefix_of("/bar"); // prints nothing 495 | * set.for_each_prefix_of(""); // prints nothing 496 | */ 497 | template 498 | void for_each_prefix_of_ks(const CharT* key, size_type key_size, 499 | F&& visitor) { 500 | return m_ht.for_each_prefix_of(key, key_size, std::forward(visitor)); 501 | } 502 | 503 | /** 504 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 505 | */ 506 | template 507 | void for_each_prefix_of_ks(const CharT* key, size_type key_size, 508 | F&& visitor) const { 509 | return m_ht.for_each_prefix_of(key, key_size, std::forward(visitor)); 510 | } 511 | #ifdef TSL_HT_HAS_STRING_VIEW 512 | /** 513 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 514 | */ 515 | template 516 | void for_each_prefix_of(const std::basic_string_view& key, 517 | F&& visitor) { 518 | return m_ht.for_each_prefix_of(key.data(), key.size(), 519 | std::forward(visitor)); 520 | } 521 | 522 | /** 523 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 524 | */ 525 | template 526 | void for_each_prefix_of( 527 | const std::basic_string_view& key, F&& visitor) const { 528 | return m_ht.for_each_prefix_of(key.data(), key.size(), 529 | std::forward(visitor)); 530 | } 531 | #else 532 | /** 533 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 534 | */ 535 | template 536 | void for_each_prefix_of(const CharT* key, F&& visitor) { 537 | return m_ht.for_each_prefix_of(key, std::strlen(key), 538 | std::forward(visitor)); 539 | } 540 | 541 | /** 542 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 543 | */ 544 | template 545 | void for_each_prefix_of(const CharT* key, F&& visitor) const { 546 | return m_ht.for_each_prefix_of(key, std::strlen(key), 547 | std::forward(visitor)); 548 | } 549 | 550 | /** 551 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 552 | */ 553 | template 554 | void for_each_prefix_of(const std::basic_string& key, F&& visitor) { 555 | return m_ht.for_each_prefix_of(key.data(), key.size(), 556 | std::forward(visitor)); 557 | } 558 | 559 | /** 560 | * @copydoc for_each_prefix_of_ks(const CharT*, size_type, F&&) 561 | */ 562 | template 563 | void for_each_prefix_of(const std::basic_string& key, 564 | F&& visitor) const { 565 | return m_ht.for_each_prefix_of(key.data(), key.size(), 566 | std::forward(visitor)); 567 | } 568 | #endif 569 | 570 | /* 571 | * Hash policy 572 | */ 573 | float max_load_factor() const { return m_ht.max_load_factor(); } 574 | void max_load_factor(float ml) { m_ht.max_load_factor(ml); } 575 | 576 | /* 577 | * Burst policy 578 | */ 579 | size_type burst_threshold() const { return m_ht.burst_threshold(); } 580 | void burst_threshold(size_type threshold) { m_ht.burst_threshold(threshold); } 581 | 582 | /* 583 | * Observers 584 | */ 585 | hasher hash_function() const { return m_ht.hash_function(); } 586 | 587 | /* 588 | * Other 589 | */ 590 | 591 | /** 592 | * Serialize the set through the `serializer` parameter. 593 | * 594 | * The `serializer` parameter must be a function object that supports the 595 | * following calls: 596 | * - `void operator()(const U& value);` where the types `std::uint64_t` and 597 | * `float` must be supported for U. 598 | * - `void operator()(const CharT* value, std::size_t value_size);` 599 | * 600 | * The implementation leaves binary compatibility (endianness, IEEE 754 for 601 | * floats, ...) of the types it serializes in the hands of the `Serializer` 602 | * function object if compatibility is required. 603 | */ 604 | template 605 | void serialize(Serializer& serializer) const { 606 | m_ht.serialize(serializer); 607 | } 608 | 609 | /** 610 | * Deserialize a previously serialized set through the `deserializer` 611 | * parameter. 612 | * 613 | * The `deserializer` parameter must be a function object that supports the 614 | * following calls: 615 | * - `template U operator()();` where the types `std::uint64_t` 616 | * and `float` must be supported for U. 617 | * - `void operator()(CharT* value_out, std::size_t value_size);` 618 | * 619 | * If the deserialized hash set part of the hat-trie is hash compatible with 620 | * the serialized set, the deserialization process can be sped up by setting 621 | * `hash_compatible` to true. To be hash compatible, the Hash (take care of 622 | * the 32-bits vs 64 bits), and KeySizeT must behave the same than the ones 623 | * used in the serialized set. Otherwise the behaviour is undefined with 624 | * `hash_compatible` sets to true. 625 | * 626 | * The behaviour is undefined if the type `CharT` of the `htrie_set` is not 627 | * the same as the type used during serialization. 628 | * 629 | * The implementation leaves binary compatibility (endianness, IEEE 754 for 630 | * floats, size of int, ...) of the types it deserializes in the hands of the 631 | * `Deserializer` function object if compatibility is required. 632 | */ 633 | template 634 | static htrie_set deserialize(Deserializer& deserializer, 635 | bool hash_compatible = false) { 636 | htrie_set set; 637 | set.m_ht.deserialize(deserializer, hash_compatible); 638 | 639 | return set; 640 | } 641 | 642 | friend bool operator==(const htrie_set& lhs, const htrie_set& rhs) { 643 | if (lhs.size() != rhs.size()) { 644 | return false; 645 | } 646 | 647 | std::string key_buffer; 648 | for (auto it = lhs.cbegin(); it != lhs.cend(); ++it) { 649 | it.key(key_buffer); 650 | 651 | const auto it_element_rhs = rhs.find(key_buffer); 652 | if (it_element_rhs == rhs.cend()) { 653 | return false; 654 | } 655 | } 656 | 657 | return true; 658 | } 659 | 660 | friend bool operator!=(const htrie_set& lhs, const htrie_set& rhs) { 661 | return !operator==(lhs, rhs); 662 | } 663 | 664 | friend void swap(htrie_set& lhs, htrie_set& rhs) { lhs.swap(rhs); } 665 | 666 | private: 667 | ht m_ht; 668 | }; 669 | 670 | } // end namespace tsl 671 | 672 | #endif 673 | -------------------------------------------------------------------------------- /cpp/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef FASTTRIE_UTILS_H 2 | #define FASTTRIE_UTILS_H 3 | 4 | #include 5 | 6 | #define HOST_FN(rt, name, functionArgCount, hostFunctionBody) \ 7 | jsi::Function::createFromHostFunction( \ 8 | rt, jsi::PropNameID::forAscii(rt, name), (functionArgCount), \ 9 | [=](jsi::Runtime & rt, const jsi::Value &thisValue, \ 10 | const jsi::Value *arguments, \ 11 | size_t count) -> jsi::Value hostFunctionBody) 12 | 13 | #define HOST_STR(str) jsi::String::createFromAscii(rt, str) 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /example/.bundle/config: -------------------------------------------------------------------------------- 1 | BUNDLE_PATH: "vendor/bundle" 2 | BUNDLE_FORCE_RUBY_PLATFORM: 1 3 | -------------------------------------------------------------------------------- /example/.watchmanconfig: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /example/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version 4 | ruby ">= 2.6.10" 5 | 6 | gem 'cocoapods', '~> 1.13' 7 | gem 'activesupport', '>= 6.1.7.3', '< 7.1.0' 8 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli). 2 | 3 | # Getting Started 4 | 5 | >**Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till "Creating a new application" step, before proceeding. 6 | 7 | ## Step 1: Start the Metro Server 8 | 9 | First, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native. 10 | 11 | To start Metro, run the following command from the _root_ of your React Native project: 12 | 13 | ```bash 14 | # using npm 15 | npm start 16 | 17 | # OR using Yarn 18 | yarn start 19 | ``` 20 | 21 | ## Step 2: Start your Application 22 | 23 | Let Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app: 24 | 25 | ### For Android 26 | 27 | ```bash 28 | # using npm 29 | npm run android 30 | 31 | # OR using Yarn 32 | yarn android 33 | ``` 34 | 35 | ### For iOS 36 | 37 | ```bash 38 | # using npm 39 | npm run ios 40 | 41 | # OR using Yarn 42 | yarn ios 43 | ``` 44 | 45 | If everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly. 46 | 47 | This is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively. 48 | 49 | ## Step 3: Modifying your App 50 | 51 | Now that you have successfully run the app, let's modify it. 52 | 53 | 1. Open `App.tsx` in your text editor of choice and edit some lines. 54 | 2. For **Android**: Press the R key twice or select **"Reload"** from the **Developer Menu** (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes! 55 | 56 | For **iOS**: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes! 57 | 58 | ## Congratulations! :tada: 59 | 60 | You've successfully run and modified your React Native App. :partying_face: 61 | 62 | ### Now what? 63 | 64 | - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps). 65 | - If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started). 66 | 67 | # Troubleshooting 68 | 69 | If you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page. 70 | 71 | # Learn More 72 | 73 | To learn more about React Native, take a look at the following resources: 74 | 75 | - [React Native Website](https://reactnative.dev) - learn more about React Native. 76 | - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment. 77 | - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**. 78 | - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts. 79 | - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native. 80 | -------------------------------------------------------------------------------- /example/android/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.application" 2 | apply plugin: "com.facebook.react" 3 | 4 | /** 5 | * This is the configuration block to customize your React Native Android app. 6 | * By default you don't need to apply any configuration, just uncomment the lines you need. 7 | */ 8 | react { 9 | /* Folders */ 10 | // The root of your project, i.e. where "package.json" lives. Default is '..' 11 | // root = file("../") 12 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native 13 | // reactNativeDir = file("../node_modules/react-native") 14 | // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen 15 | // codegenDir = file("../node_modules/@react-native/codegen") 16 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js 17 | // cliFile = file("../node_modules/react-native/cli.js") 18 | 19 | /* Variants */ 20 | // The list of variants to that are debuggable. For those we're going to 21 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'. 22 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. 23 | // debuggableVariants = ["liteDebug", "prodDebug"] 24 | 25 | /* Bundling */ 26 | // A list containing the node command and its flags. Default is just 'node'. 27 | // nodeExecutableAndArgs = ["node"] 28 | // 29 | // The command to run when bundling. By default is 'bundle' 30 | // bundleCommand = "ram-bundle" 31 | // 32 | // The path to the CLI configuration file. Default is empty. 33 | // bundleConfig = file(../rn-cli.config.js) 34 | // 35 | // The name of the generated asset file containing your JS bundle 36 | // bundleAssetName = "MyApplication.android.bundle" 37 | // 38 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' 39 | // entryFile = file("../js/MyApplication.android.js") 40 | // 41 | // A list of extra flags to pass to the 'bundle' commands. 42 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle 43 | // extraPackagerArgs = [] 44 | 45 | /* Hermes Commands */ 46 | // The hermes compiler command to run. By default it is 'hermesc' 47 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" 48 | // 49 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" 50 | // hermesFlags = ["-O", "-output-source-map"] 51 | } 52 | 53 | /** 54 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode. 55 | */ 56 | def enableProguardInReleaseBuilds = false 57 | 58 | /** 59 | * The preferred build flavor of JavaScriptCore (JSC) 60 | * 61 | * For example, to use the international variant, you can use: 62 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` 63 | * 64 | * The international variant includes ICU i18n library and necessary data 65 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that 66 | * give correct results when using with locales other than en-US. Note that 67 | * this variant is about 6MiB larger per architecture than default. 68 | */ 69 | def jscFlavor = 'org.webkit:android-jsc:+' 70 | 71 | android { 72 | ndkVersion rootProject.ext.ndkVersion 73 | 74 | compileSdkVersion rootProject.ext.compileSdkVersion 75 | 76 | namespace "com.fasttrieexample" 77 | defaultConfig { 78 | applicationId "com.fasttrieexample" 79 | minSdkVersion rootProject.ext.minSdkVersion 80 | targetSdkVersion rootProject.ext.targetSdkVersion 81 | versionCode 1 82 | versionName "1.0" 83 | } 84 | signingConfigs { 85 | debug { 86 | storeFile file('debug.keystore') 87 | storePassword 'android' 88 | keyAlias 'androiddebugkey' 89 | keyPassword 'android' 90 | } 91 | release { 92 | storeFile file('debug.keystore') 93 | storePassword 'android' 94 | keyAlias 'androiddebugkey' 95 | keyPassword 'android' 96 | } 97 | } 98 | buildTypes { 99 | debug { 100 | signingConfig signingConfigs.debug 101 | } 102 | release { 103 | // Caution! In production, you need to generate your own keystore file. 104 | // see https://reactnative.dev/docs/signed-apk-android. 105 | signingConfig signingConfigs.debug 106 | minifyEnabled enableProguardInReleaseBuilds 107 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" 108 | } 109 | } 110 | } 111 | 112 | dependencies { 113 | // The version of react-native is set by the React Native Gradle Plugin 114 | implementation("com.facebook.react:react-android") 115 | 116 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") 117 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { 118 | exclude group:'com.squareup.okhttp3', module:'okhttp' 119 | } 120 | 121 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") 122 | if (hermesEnabled.toBoolean()) { 123 | implementation("com.facebook.react:hermes-android") 124 | } else { 125 | implementation jscFlavor 126 | } 127 | } 128 | 129 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) 130 | -------------------------------------------------------------------------------- /example/android/app/debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/debug.keystore -------------------------------------------------------------------------------- /example/android/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /example/android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /example/android/app/src/debug/java/com/fasttrieexample/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.fasttrieexample; 8 | 9 | import android.content.Context; 10 | import com.facebook.flipper.android.AndroidFlipperClient; 11 | import com.facebook.flipper.android.utils.FlipperUtils; 12 | import com.facebook.flipper.core.FlipperClient; 13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; 14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; 15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; 16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping; 17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; 18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; 19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; 20 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; 21 | import com.facebook.react.ReactInstanceEventListener; 22 | import com.facebook.react.ReactInstanceManager; 23 | import com.facebook.react.bridge.ReactContext; 24 | import com.facebook.react.modules.network.NetworkingModule; 25 | import okhttp3.OkHttpClient; 26 | 27 | /** 28 | * Class responsible of loading Flipper inside your React Native application. This is the debug 29 | * flavor of it. Here you can add your own plugins and customize the Flipper setup. 30 | */ 31 | public class ReactNativeFlipper { 32 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 33 | if (FlipperUtils.shouldEnableFlipper(context)) { 34 | final FlipperClient client = AndroidFlipperClient.getInstance(context); 35 | 36 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); 37 | client.addPlugin(new DatabasesFlipperPlugin(context)); 38 | client.addPlugin(new SharedPreferencesFlipperPlugin(context)); 39 | client.addPlugin(CrashReporterPlugin.getInstance()); 40 | 41 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); 42 | NetworkingModule.setCustomClientBuilder( 43 | new NetworkingModule.CustomClientBuilder() { 44 | @Override 45 | public void apply(OkHttpClient.Builder builder) { 46 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); 47 | } 48 | }); 49 | client.addPlugin(networkFlipperPlugin); 50 | client.start(); 51 | 52 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized 53 | // Hence we run if after all native modules have been initialized 54 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); 55 | if (reactContext == null) { 56 | reactInstanceManager.addReactInstanceEventListener( 57 | new ReactInstanceEventListener() { 58 | @Override 59 | public void onReactContextInitialized(ReactContext reactContext) { 60 | reactInstanceManager.removeReactInstanceEventListener(this); 61 | reactContext.runOnNativeModulesQueueThread( 62 | new Runnable() { 63 | @Override 64 | public void run() { 65 | client.addPlugin(new FrescoFlipperPlugin()); 66 | } 67 | }); 68 | } 69 | }); 70 | } else { 71 | client.addPlugin(new FrescoFlipperPlugin()); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /example/android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 12 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/fasttrieexample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.fasttrieexample; 2 | 3 | import com.facebook.react.ReactActivity; 4 | import com.facebook.react.ReactActivityDelegate; 5 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; 6 | import com.facebook.react.defaults.DefaultReactActivityDelegate; 7 | import android.os.Bundle; 8 | 9 | public class MainActivity extends ReactActivity { 10 | 11 | /** 12 | * Returns the name of the main component registered from JavaScript. This is used to schedule 13 | * rendering of the component. 14 | */ 15 | @Override 16 | protected String getMainComponentName() { 17 | return "FastTrieExample"; 18 | } 19 | 20 | // https://reactnavigation.org/docs/getting-started/ 21 | @Override 22 | protected void onCreate(Bundle savedInstanceState) { 23 | super.onCreate(null); 24 | } 25 | 26 | /** 27 | * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link 28 | * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React 29 | * (aka React 18) with two boolean flags. 30 | */ 31 | @Override 32 | protected ReactActivityDelegate createReactActivityDelegate() { 33 | return new DefaultReactActivityDelegate( 34 | this, 35 | getMainComponentName(), 36 | // If you opted-in for the New Architecture, we enable the Fabric Renderer. 37 | DefaultNewArchitectureEntryPoint.getFabricEnabled()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /example/android/app/src/main/java/com/fasttrieexample/MainApplication.java: -------------------------------------------------------------------------------- 1 | package com.fasttrieexample; 2 | 3 | import android.app.Application; 4 | import com.facebook.react.PackageList; 5 | import com.facebook.react.ReactApplication; 6 | import com.facebook.react.ReactNativeHost; 7 | import com.facebook.react.ReactPackage; 8 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; 9 | import com.facebook.react.defaults.DefaultReactNativeHost; 10 | import com.facebook.soloader.SoLoader; 11 | import java.util.List; 12 | 13 | public class MainApplication extends Application implements ReactApplication { 14 | 15 | private final ReactNativeHost mReactNativeHost = 16 | new DefaultReactNativeHost(this) { 17 | @Override 18 | public boolean getUseDeveloperSupport() { 19 | return BuildConfig.DEBUG; 20 | } 21 | 22 | @Override 23 | protected List getPackages() { 24 | @SuppressWarnings("UnnecessaryLocalVariable") 25 | List packages = new PackageList(this).getPackages(); 26 | // Packages that cannot be autolinked yet can be added manually here, for example: 27 | // packages.add(new MyReactNativePackage()); 28 | return packages; 29 | } 30 | 31 | @Override 32 | protected String getJSMainModuleName() { 33 | return "index"; 34 | } 35 | 36 | @Override 37 | protected boolean isNewArchEnabled() { 38 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; 39 | } 40 | 41 | @Override 42 | protected Boolean isHermesEnabled() { 43 | return BuildConfig.IS_HERMES_ENABLED; 44 | } 45 | }; 46 | 47 | @Override 48 | public ReactNativeHost getReactNativeHost() { 49 | return mReactNativeHost; 50 | } 51 | 52 | @Override 53 | public void onCreate() { 54 | super.onCreate(); 55 | SoLoader.init(this, /* native exopackage */ false); 56 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { 57 | // If you opted-in for the New Architecture, we load the native entry point for this app. 58 | DefaultNewArchitectureEntryPoint.load(); 59 | } 60 | ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/drawable/rn_edit_text_material.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 21 | 22 | 23 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | FastTrieExample 3 | 4 | -------------------------------------------------------------------------------- /example/android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /example/android/app/src/release/java/com/fasttrieexample/ReactNativeFlipper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. 3 | * 4 | *

This source code is licensed under the MIT license found in the LICENSE file in the root 5 | * directory of this source tree. 6 | */ 7 | package com.fasttrieexample; 8 | 9 | import android.content.Context; 10 | import com.facebook.react.ReactInstanceManager; 11 | 12 | /** 13 | * Class responsible of loading Flipper inside your React Native application. This is the release 14 | * flavor of it so it's empty as we don't want to load Flipper. 15 | */ 16 | public class ReactNativeFlipper { 17 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { 18 | // Do nothing as we don't want to initialize Flipper on Release. 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /example/android/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext { 5 | buildToolsVersion = "33.0.0" 6 | minSdkVersion = 21 7 | compileSdkVersion = 33 8 | targetSdkVersion = 33 9 | 10 | // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP. 11 | ndkVersion = "23.1.7779620" 12 | } 13 | repositories { 14 | google() 15 | mavenCentral() 16 | } 17 | dependencies { 18 | classpath("com.android.tools.build:gradle") 19 | classpath("com.facebook.react:react-native-gradle-plugin") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /example/android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | # AndroidX package structure to make it clearer which packages are bundled with the 21 | # Android operating system, and which are packaged with your app's APK 22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 23 | android.useAndroidX=true 24 | # Automatically convert third-party libraries to use AndroidX 25 | android.enableJetifier=true 26 | 27 | # Version of flipper SDK to use with React Native 28 | FLIPPER_VERSION=0.182.0 29 | 30 | # Use this property to specify which architecture you want to build. 31 | # You can also override it from the CLI using 32 | # ./gradlew -PreactNativeArchitectures=x86_64 33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 34 | 35 | # Use this property to enable support to the new architecture. 36 | # This will allow you to use TurboModules and the Fabric render in 37 | # your application. You should enable this flag either if you want 38 | # to write custom TurboModules/Fabric components OR use libraries that 39 | # are providing them. 40 | newArchEnabled=false 41 | 42 | # Use this property to enable or disable the Hermes JS engine. 43 | # If set to false, you will be using JSC instead. 44 | hermesEnabled=true 45 | -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zacharyfmarion/react-native-fast-trie/c8eb790375ae6ec49008795276cfdf6cff62efe5/example/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /example/android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-all.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /example/android/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /example/android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /example/android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'FastTrieExample' 2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) 3 | include ':app' 4 | includeBuild('../node_modules/@react-native/gradle-plugin') 5 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "FastTrieExample", 3 | "displayName": "FastTrieExample" 4 | } 5 | -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | presets: ['module:metro-react-native-babel-preset'], 6 | plugins: [ 7 | [ 8 | 'module-resolver', 9 | { 10 | extensions: ['.tsx', '.ts', '.js', '.json'], 11 | alias: { 12 | [pak.name]: path.join(__dirname, '..', pak.source), 13 | }, 14 | }, 15 | ], 16 | ], 17 | }; 18 | -------------------------------------------------------------------------------- /example/index.js: -------------------------------------------------------------------------------- 1 | import { AppRegistry } from 'react-native'; 2 | import App from './src/App'; 3 | import { name as appName } from './app.json'; 4 | import { Buffer } from '@craftzdog/react-native-buffer'; 5 | 6 | global.process = { 7 | cwd: () => 'sxsx', 8 | env: { NODE_ENV: 'production' }, 9 | }; 10 | global.location = {}; 11 | global.Buffer = Buffer; 12 | 13 | AppRegistry.registerComponent(appName, () => App); 14 | -------------------------------------------------------------------------------- /example/ios/.xcode.env: -------------------------------------------------------------------------------- 1 | # This `.xcode.env` file is versioned and is used to source the environment 2 | # used when running script phases inside Xcode. 3 | # To customize your local environment, you can create an `.xcode.env.local` 4 | # file that is not versioned. 5 | 6 | # NODE_BINARY variable contains the PATH to the node executable. 7 | # 8 | # Customize the NODE_BINARY variable here. 9 | # For example, to use nvm with brew, add the following line 10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use 11 | export NODE_BINARY=$(command -v node) 12 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | // 2 | // Use this file to import your target's public headers that you would like to expose to Swift. 3 | // 4 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample.xcodeproj/xcshareddata/xcschemes/FastTrieExample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 31 | 32 | 42 | 44 | 50 | 51 | 52 | 53 | 59 | 61 | 67 | 68 | 69 | 70 | 72 | 73 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample.xcodeproj/xcshareddata/xcschemes/FastTrieExampleTests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 16 | 18 | 24 | 25 | 26 | 27 | 28 | 38 | 39 | 45 | 46 | 48 | 49 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample.xcodeproj/xcshareddata/xcschemes/FastUrlExample.xcscheme.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 53 | 55 | 61 | 62 | 63 | 64 | 70 | 72 | 78 | 79 | 80 | 81 | 83 | 84 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample.xcworkspace/contents.xcworkspacedata.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /example/ios/FastTrieExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /example/ios/FastTrieExampleTests/FastUrlExampleTests.m: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import 5 | #import 6 | 7 | #define TIMEOUT_SECONDS 600 8 | #define TEXT_TO_LOOK_FOR @"Welcome to React" 9 | 10 | @interface FastTrieExampleTests : XCTestCase 11 | 12 | @end 13 | 14 | @implementation FastTrieExampleTests 15 | 16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test 17 | { 18 | if (test(view)) { 19 | return YES; 20 | } 21 | for (UIView *subview in [view subviews]) { 22 | if ([self findSubviewInView:subview matching:test]) { 23 | return YES; 24 | } 25 | } 26 | return NO; 27 | } 28 | 29 | - (void)testRendersWelcomeScreen 30 | { 31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController]; 32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; 33 | BOOL foundElement = NO; 34 | 35 | __block NSString *redboxError = nil; 36 | #ifdef DEBUG 37 | RCTSetLogFunction( 38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { 39 | if (level >= RCTLogLevelError) { 40 | redboxError = message; 41 | } 42 | }); 43 | #endif 44 | 45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { 46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; 48 | 49 | foundElement = [self findSubviewInView:vc.view 50 | matching:^BOOL(UIView *view) { 51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { 52 | return YES; 53 | } 54 | return NO; 55 | }]; 56 | } 57 | 58 | #ifdef DEBUG 59 | RCTSetLogFunction(RCTDefaultLogFunction); 60 | #endif 61 | 62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); 63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /example/ios/FastTrieExampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | @interface AppDelegate : RCTAppDelegate 5 | 6 | @end 7 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/AppDelegate.mm: -------------------------------------------------------------------------------- 1 | #import "AppDelegate.h" 2 | 3 | #import 4 | 5 | @implementation AppDelegate 6 | 7 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 8 | { 9 | self.moduleName = @"FastTrieExample"; 10 | // You can add your custom initial props in the dictionary below. 11 | // They will be passed down to the ViewController used by React Native. 12 | self.initialProps = @{}; 13 | 14 | return [super application:application didFinishLaunchingWithOptions:launchOptions]; 15 | } 16 | 17 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge 18 | { 19 | #if DEBUG 20 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; 21 | #else 22 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; 23 | #endif 24 | } 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/Images.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "scale" : "2x", 6 | "size" : "20x20" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "scale" : "3x", 11 | "size" : "20x20" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "scale" : "2x", 16 | "size" : "29x29" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "scale" : "3x", 21 | "size" : "29x29" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "scale" : "2x", 26 | "size" : "40x40" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "scale" : "3x", 31 | "size" : "40x40" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "scale" : "2x", 36 | "size" : "60x60" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "scale" : "3x", 41 | "size" : "60x60" 42 | }, 43 | { 44 | "idiom" : "ios-marketing", 45 | "scale" : "1x", 46 | "size" : "1024x1024" 47 | } 48 | ], 49 | "info" : { 50 | "author" : "xcode", 51 | "version" : 1 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/Images.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | FastTrieExample 9 | CFBundleExecutable 10 | $(EXECUTABLE_NAME) 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(MARKETING_VERSION) 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | $(CURRENT_PROJECT_VERSION) 25 | LSRequiresIPhoneOS 26 | 27 | NSAppTransportSecurity 28 | 29 | NSExceptionDomains 30 | 31 | localhost 32 | 33 | NSExceptionAllowsInsecureHTTPLoads 34 | 35 | 36 | 37 | 38 | NSLocationWhenInUseUsageDescription 39 | 40 | UILaunchStoryboardName 41 | LaunchScreen 42 | UIRequiredDeviceCapabilities 43 | 44 | armv7 45 | 46 | UISupportedInterfaceOrientations 47 | 48 | UIInterfaceOrientationPortrait 49 | UIInterfaceOrientationLandscapeLeft 50 | UIInterfaceOrientationLandscapeRight 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/LaunchScreen.storyboard.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 23 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /example/ios/FastUrlExample/main.m: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "AppDelegate.h" 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | @autoreleasepool { 8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /example/ios/File.swift: -------------------------------------------------------------------------------- 1 | // 2 | // File.swift 3 | // FastTrieExample 4 | // 5 | 6 | import Foundation 7 | -------------------------------------------------------------------------------- /example/ios/Podfile: -------------------------------------------------------------------------------- 1 | # Resolve react_native_pods.rb with node to allow for hoisting 2 | require Pod::Executable.execute_command('node', ['-p', 3 | 'require.resolve( 4 | "react-native/scripts/react_native_pods.rb", 5 | {paths: [process.argv[1]]}, 6 | )', __dir__]).strip 7 | 8 | platform :ios, min_ios_version_supported 9 | prepare_react_native_project! 10 | 11 | # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set. 12 | # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded 13 | # 14 | # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js` 15 | # ```js 16 | # module.exports = { 17 | # dependencies: { 18 | # ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}), 19 | # ``` 20 | flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled 21 | 22 | linkage = ENV['USE_FRAMEWORKS'] 23 | if linkage != nil 24 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green 25 | use_frameworks! :linkage => linkage.to_sym 26 | end 27 | 28 | target 'FastTrieExample' do 29 | config = use_native_modules! 30 | 31 | # Flags change depending on the env values. 32 | flags = get_default_flags() 33 | 34 | use_react_native!( 35 | :path => config[:reactNativePath], 36 | # Hermes is now enabled by default. Disable by setting this flag to false. 37 | :hermes_enabled => flags[:hermes_enabled], 38 | :fabric_enabled => flags[:fabric_enabled], 39 | # Enables Flipper. 40 | # 41 | # Note that if you have use_frameworks! enabled, Flipper will not work and 42 | # you should disable the next line. 43 | :flipper_configuration => flipper_config, 44 | # An absolute path to your application root. 45 | :app_path => "#{Pod::Config.instance.installation_root}/.." 46 | ) 47 | 48 | target 'FastTrieExampleTests' do 49 | inherit! :complete 50 | # Pods for testing 51 | end 52 | 53 | post_install do |installer| 54 | # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 55 | react_native_post_install( 56 | installer, 57 | config[:reactNativePath], 58 | :mac_catalyst_enabled => false 59 | ) 60 | __apply_Xcode_12_5_M1_post_install_workaround(installer) 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /example/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'react-native', 3 | }; 4 | -------------------------------------------------------------------------------- /example/metro.config.js: -------------------------------------------------------------------------------- 1 | const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); 2 | const path = require('path'); 3 | const escape = require('escape-string-regexp'); 4 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 5 | const pak = require('../package.json'); 6 | 7 | const root = path.resolve(__dirname, '..'); 8 | const modules = Object.keys({ ...pak.peerDependencies }); 9 | 10 | /** 11 | * Metro configuration 12 | * https://facebook.github.io/metro/docs/configuration 13 | * 14 | * @type {import('metro-config').MetroConfig} 15 | */ 16 | const config = { 17 | watchFolders: [root], 18 | 19 | // We need to make sure that only one version is loaded for peerDependencies 20 | // So we block them at the root, and alias them to the versions in example's node_modules 21 | resolver: { 22 | blacklistRE: exclusionList( 23 | modules.map( 24 | (m) => 25 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 26 | ) 27 | ), 28 | 29 | extraNodeModules: modules.reduce((acc, name) => { 30 | acc[name] = path.join(__dirname, 'node_modules', name); 31 | acc.stream = path.join(__dirname, 'node_modules', 'stream-browserify'); 32 | acc.buffer = path.join( 33 | __dirname, 34 | 'node_modules', 35 | '@craftzdog', 36 | 'react-native-buffer' 37 | ); 38 | return acc; 39 | }, {}), 40 | }, 41 | 42 | transformer: { 43 | getTransformOptions: async () => ({ 44 | transform: { 45 | experimentalImportSupport: false, 46 | inlineRequires: true, 47 | }, 48 | }), 49 | }, 50 | }; 51 | 52 | module.exports = mergeConfig(getDefaultConfig(__dirname), config); 53 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-fast-trie-example", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "typecheck": "tsc --noEmit", 7 | "android": "react-native run-android", 8 | "ios": "react-native run-ios", 9 | "start": "react-native start", 10 | "build:android": "cd android && ./gradlew assembleDebug --no-daemon --console=plain -PreactNativeArchitectures=arm64-v8a", 11 | "build:ios": "cd ios && xcodebuild -workspace FastTrieExample.xcworkspace -scheme FastTrieExample -allowProvisioningUpdates -configuration Debug -sdk iphonesimulator CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ GCC_OPTIMIZATION_LEVEL=0 GCC_PRECOMPILE_PREFIX_HEADER=YES ASSETCATALOG_COMPILER_OPTIMIZATION=time DEBUG_INFORMATION_FORMAT=dwarf COMPILER_INDEX_STORE_ENABLE=NO" 12 | }, 13 | "dependencies": { 14 | "@craftzdog/react-native-buffer": "^6.0.5", 15 | "@react-native-community/checkbox": "^0.5.17", 16 | "@react-navigation/native": "^6.1.9", 17 | "@react-navigation/native-stack": "^6.9.17", 18 | "binary-search-bounds": "^2.0.5", 19 | "chai": "^5.0.0", 20 | "events": "^3.3.0", 21 | "long": "^5.2.3", 22 | "mocha": "^10.2.0", 23 | "react": "18.2.0", 24 | "react-native": "0.72.7", 25 | "react-native-heap-profiler": "^0.2.0", 26 | "react-native-performance": "^5.1.0", 27 | "react-native-safe-area-context": "^4.8.2", 28 | "react-native-screens": "^3.29.0", 29 | "react-native-url-polyfill": "^2.0.0", 30 | "stream-browserify": "^3.0.0", 31 | "trie-typed": "^1.51.7", 32 | "util": "^0.12.5" 33 | }, 34 | "devDependencies": { 35 | "@babel/core": "^7.20.0", 36 | "@babel/preset-env": "^7.20.0", 37 | "@babel/runtime": "^7.20.0", 38 | "@react-native/metro-config": "^0.72.11", 39 | "@types/chai": "^4.3.11", 40 | "@types/mocha": "^10.0.6", 41 | "babel-plugin-module-resolver": "^5.0.0", 42 | "metro-react-native-babel-preset": "0.76.8", 43 | "pod-install": "^0.1.0" 44 | }, 45 | "engines": { 46 | "node": ">=16" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /example/react-native.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = { 5 | dependencies: { 6 | [pak.name]: { 7 | root: path.join(__dirname, '..'), 8 | }, 9 | }, 10 | }; 11 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { NavigationContainer } from '@react-navigation/native'; 3 | import { createNativeStackNavigator } from '@react-navigation/native-stack'; 4 | 5 | import { Home } from './screens/Home'; 6 | import { Benchmarks } from './screens/Benchmarks/Benchmarks'; 7 | import { Tests } from './screens/Tests/Tests'; 8 | import type { RootStackParamList } from './screens/params'; 9 | import { SpeedBenchmarks } from './screens/Benchmarks/SpeedBenchmarks'; 10 | import { MemoryBenchmarks } from './screens/Benchmarks/MemoryBenchmarks'; 11 | 12 | const Stack = createNativeStackNavigator(); 13 | 14 | export default function App() { 15 | return ( 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | ); 26 | } 27 | -------------------------------------------------------------------------------- /example/src/JsTrie.ts: -------------------------------------------------------------------------------- 1 | import { Trie } from 'trie-typed'; 2 | 3 | /** 4 | * Wrapper class for Trie to provide a unified interface 5 | */ 6 | export class JsTrie { 7 | _trie: Trie; 8 | 9 | constructor() { 10 | this._trie = new Trie(); 11 | } 12 | 13 | insert(item: string) { 14 | this._trie.add(item); 15 | } 16 | 17 | contains(item: string) { 18 | return this._trie.has(item); 19 | } 20 | 21 | find(search: string, max: number | undefined = undefined) { 22 | return this._trie.getWords(search, max); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /example/src/Trie.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Naive pure js implementation of a Trie. 3 | */ 4 | export class Trie { 5 | root: TrieNode; 6 | 7 | constructor() { 8 | this.root = new TrieNode(null); 9 | } 10 | 11 | insert(word: string) { 12 | let node = this.root; 13 | 14 | for (let i = 0; i < word.length; i++) { 15 | // check to see if character node exists in children. 16 | const wordChar = word[i] as string; 17 | if (!node.children[wordChar]) { 18 | node.children[wordChar] = new TrieNode(wordChar); 19 | // @ts-expect-error 20 | node.children[wordChar].parent = node; 21 | } 22 | 23 | // proceed to the next depth in the trie. 24 | node = node.children[wordChar] as TrieNode; 25 | 26 | // check if it's the last word. 27 | if (i === word.length - 1) { 28 | node.leafNode = true; 29 | } 30 | } 31 | } 32 | 33 | /** check if it contains a whole word */ 34 | contains(word: string) { 35 | let node = this.root; 36 | 37 | for (const char of word) { 38 | if (node.children[char]) { 39 | node = node.children[char] as TrieNode; 40 | } else { 41 | return false; 42 | } 43 | } 44 | 45 | // we finished going through all the words, is it a whole word? 46 | return node.leafNode; 47 | } 48 | 49 | /** Returns every word with given prefix */ 50 | find(prefix: string, maxResults?: number) { 51 | let node = this.root; 52 | const output: string[] = []; 53 | 54 | for (const char of prefix) { 55 | // make sure prefix actually has words 56 | if (node.children[char]) { 57 | node = node.children[char] as TrieNode; 58 | } else { 59 | // there's none. just return it. 60 | return output; 61 | } 62 | } 63 | 64 | findAllWords(node, output, maxResults); 65 | return output; 66 | } 67 | } 68 | 69 | // recursive function to find all words in the given node. 70 | function findAllWords(node: TrieNode, arr: string[], maxResults?: number) { 71 | // base case, if node is at a word, push to output 72 | if (node.leafNode) { 73 | arr.push(node.getWord()); 74 | } 75 | 76 | // iterate through each children, call recursive findAllWords 77 | for (const child of Object.values(node.children)) { 78 | if (maxResults && maxResults <= arr.length) { 79 | return; 80 | } 81 | 82 | findAllWords(child, arr, maxResults); 83 | } 84 | } 85 | 86 | class TrieNode { 87 | readonly key: string | null; 88 | parent: TrieNode | null; 89 | children: Record; 90 | leafNode: boolean; 91 | 92 | constructor(key: string | null) { 93 | this.key = key; 94 | this.parent = null; 95 | this.children = {}; 96 | this.leafNode = false; 97 | } 98 | 99 | /** 100 | * iterates through the parents to get the word. 101 | * time complexity: O(k), k = word length 102 | */ 103 | getWord() { 104 | const output = []; 105 | let node = this as TrieNode | null; 106 | 107 | while (node !== null) { 108 | output.unshift(node.key); 109 | node = node.parent; 110 | } 111 | 112 | return output.join(''); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /example/src/components/Button.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, TouchableOpacity, StyleSheet } from 'react-native'; 3 | import { Text } from './Text'; 4 | 5 | type ButtonProps = { 6 | title: string; 7 | onPress: () => void; 8 | }; 9 | 10 | export const Button: React.FC = ({ 11 | title, 12 | onPress, 13 | }: ButtonProps) => { 14 | return ( 15 | 16 | 17 | {title} 18 | 19 | 20 | ); 21 | }; 22 | 23 | const styles = StyleSheet.create({ 24 | container: { 25 | backgroundColor: '#99FFFF', 26 | padding: 10, 27 | borderRadius: 5, 28 | alignContent: 'center', 29 | justifyContent: 'center', 30 | borderWidth: 1, 31 | borderColor: 'black', 32 | }, 33 | }); 34 | -------------------------------------------------------------------------------- /example/src/components/CorrectResultItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, StyleSheet } from 'react-native'; 3 | import { Text } from './Text'; 4 | 5 | type CorrectResultItemProps = { 6 | description: string; 7 | }; 8 | 9 | export const CorrectResultItem: React.FC = ({ 10 | description, 11 | }: CorrectResultItemProps) => { 12 | const emoji = '✅'; 13 | const fullText = emoji + ' [' + description + ']'; 14 | 15 | return ( 16 | 17 | {fullText} 18 | 19 | ); 20 | }; 21 | 22 | const styles = StyleSheet.create({ 23 | scroll: { 24 | flex: 1, 25 | }, 26 | itemContainer: { 27 | borderWidth: 1, 28 | margin: 10, 29 | marginBottom: 5, 30 | flexDirection: 'column', 31 | borderRadius: 5, 32 | padding: 5, 33 | }, 34 | text: { 35 | flexShrink: 1, 36 | }, 37 | }); 38 | -------------------------------------------------------------------------------- /example/src/components/IncorrectResultItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, StyleSheet } from 'react-native'; 3 | import { Text } from './Text'; 4 | 5 | type IncorrectResultItemProps = { 6 | description: string; 7 | errorMsg: string; 8 | }; 9 | 10 | export const IncorrectResultItem: React.FC = ({ 11 | description, 12 | errorMsg, 13 | }: IncorrectResultItemProps) => { 14 | const emoji = '❌'; 15 | const fullText = emoji + ' [' + description + '] ---> ' + errorMsg; 16 | 17 | return ( 18 | 19 | {fullText} 20 | 21 | ); 22 | }; 23 | 24 | const styles = StyleSheet.create({ 25 | scroll: { 26 | flex: 1, 27 | }, 28 | itemContainer: { 29 | borderWidth: 1, 30 | margin: 10, 31 | marginBottom: 5, 32 | flexDirection: 'column', 33 | borderRadius: 5, 34 | padding: 5, 35 | }, 36 | text: { 37 | flexShrink: 1, 38 | }, 39 | }); 40 | -------------------------------------------------------------------------------- /example/src/components/Indentator.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, StyleSheet } from 'react-native'; 3 | 4 | type IndentatorProps = { 5 | indentation: number; 6 | children: React.ReactChild; 7 | }; 8 | 9 | export const Indentator: React.FC = ({ 10 | indentation, 11 | children, 12 | }: IndentatorProps) => { 13 | return ( 14 | 15 | 16 | {children} 17 | 18 | ); 19 | }; 20 | 21 | const styles = StyleSheet.create({ 22 | container: { 23 | width: '100%', 24 | padding: 5, 25 | flexDirection: 'row', 26 | alignContent: 'center', 27 | }, 28 | }); 29 | -------------------------------------------------------------------------------- /example/src/components/NavigationButton.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { Pressable, StyleSheet, Text } from 'react-native'; 3 | 4 | type Props = { 5 | onPress: () => void; 6 | title: string; 7 | }; 8 | 9 | export function NavigationButton({ onPress, title }: Props) { 10 | return ( 11 | [ 14 | { 15 | backgroundColor: pressed ? 'rgb(210, 230, 255)' : 'white', 16 | }, 17 | styles.wrapperCustom, 18 | ]} 19 | > 20 | {title} 21 | 22 | ); 23 | } 24 | 25 | const styles = StyleSheet.create({ 26 | container: { 27 | flex: 1, 28 | justifyContent: 'center', 29 | }, 30 | text: { 31 | minWidth: 150, 32 | textAlign: 'center', 33 | fontSize: 18, 34 | color: 'black', 35 | }, 36 | wrapperCustom: { 37 | borderWidth: 1, 38 | borderColor: 'black', 39 | borderRadius: 8, 40 | padding: 8, 41 | marginBottom: 12, 42 | }, 43 | }); 44 | -------------------------------------------------------------------------------- /example/src/components/Suite.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, StyleSheet } from 'react-native'; 3 | import { Text } from './Text'; 4 | 5 | type SuiteProps = { 6 | description: string; 7 | }; 8 | 9 | export const Suite: React.FC = ({ description }: SuiteProps) => { 10 | const emoji = '↘️ '; 11 | const fullText = emoji + description; 12 | 13 | return ( 14 | 15 | {fullText} 16 | 17 | ); 18 | }; 19 | 20 | const styles = StyleSheet.create({ 21 | scroll: { 22 | flex: 1, 23 | }, 24 | itemContainer: { 25 | borderWidth: 1, 26 | margin: 10, 27 | marginBottom: 0, 28 | flexDirection: 'column', 29 | borderRadius: 5, 30 | padding: 5, 31 | }, 32 | text: { 33 | flexShrink: 1, 34 | }, 35 | }); 36 | -------------------------------------------------------------------------------- /example/src/components/TestItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { View, StyleSheet } from 'react-native'; 3 | import Checkbox from '@react-native-community/checkbox'; 4 | import { Text } from './Text'; 5 | 6 | type TestItemProps = { 7 | description: string; 8 | value: boolean; 9 | index: number; 10 | onToggle: (index: number) => void; 11 | }; 12 | 13 | export const TestItem: React.FC = ({ 14 | description, 15 | value, 16 | index, 17 | onToggle, 18 | }: TestItemProps) => { 19 | return ( 20 | 21 | {description} 22 | { 25 | onToggle(index); 26 | }} 27 | /> 28 | 29 | ); 30 | }; 31 | 32 | const styles = StyleSheet.create({ 33 | container: { 34 | borderRadius: 6, 35 | width: '100%', 36 | padding: 10, 37 | paddingHorizontal: 25, 38 | flexDirection: 'row', 39 | alignContent: 'center', 40 | alignItems: 'center', 41 | justifyContent: 'space-between', 42 | backgroundColor: '#d1e8ff', 43 | marginTop: 10, 44 | }, 45 | }); 46 | -------------------------------------------------------------------------------- /example/src/components/Text.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StyleSheet, Text as TextNative } from 'react-native'; 3 | 4 | type Props = { 5 | children: React.ReactNode; 6 | style?: any[]; 7 | }; 8 | 9 | export function Text({ children, style }: Props) { 10 | const styles = React.useMemo(() => { 11 | const res = [textStyles.text]; 12 | if (style) { 13 | res.concat(style); 14 | } 15 | return res; 16 | }, [style]); 17 | 18 | return {children}; 19 | } 20 | 21 | const textStyles = StyleSheet.create({ 22 | text: { 23 | color: 'black', 24 | }, 25 | }); 26 | -------------------------------------------------------------------------------- /example/src/screens/Benchmarks/Benchmarks.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { StyleSheet, View } from 'react-native'; 4 | import { Button } from '../../components/Button'; 5 | import { useNavigation } from '@react-navigation/native'; 6 | import type { NativeStackNavigationProp } from '@react-navigation/native-stack'; 7 | import type { RootStackParamList } from '../params'; 8 | 9 | export function Benchmarks() { 10 | const navigation = 11 | useNavigation>(); 12 | 13 | return ( 14 | 15 |