= ({
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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/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 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "rootDir": ".",
4 | "paths": {
5 | "react-native-fast-trie": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "jsx": "react",
12 | "lib": ["esnext"],
13 | "module": "esnext",
14 | "moduleResolution": "node",
15 | "noFallthroughCasesInSwitch": true,
16 | "noImplicitReturns": true,
17 | "noImplicitUseStrict": false,
18 | "noStrictGenericChecks": false,
19 | "noUncheckedIndexedAccess": true,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "resolveJsonModule": true,
23 | "skipLibCheck": true,
24 | "strict": true,
25 | "target": "esnext",
26 | "verbatimModuleSyntax": true
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/turbo.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://turbo.build/schema.json",
3 | "pipeline": {
4 | "build:android": {
5 | "inputs": [
6 | "package.json",
7 | "android",
8 | "!android/build",
9 | "src/*.ts",
10 | "src/*.tsx",
11 | "example/package.json",
12 | "example/android",
13 | "!example/android/.gradle",
14 | "!example/android/build",
15 | "!example/android/app/build"
16 | ],
17 | "outputs": []
18 | },
19 | "build:ios": {
20 | "inputs": [
21 | "package.json",
22 | "*.podspec",
23 | "ios",
24 | "src/*.ts",
25 | "src/*.tsx",
26 | "example/package.json",
27 | "example/ios",
28 | "!example/ios/build",
29 | "!example/ios/Pods"
30 | ],
31 | "outputs": []
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/ios/FastTrie.mm:
--------------------------------------------------------------------------------
1 | #import "FastTrie.h"
2 |
3 | #import
4 | #import
5 | #import
6 | #import "../cpp/fast-trie.h"
7 |
8 | @implementation FastTrie
9 | RCT_EXPORT_MODULE(FastTrie)
10 |
11 | RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install) {
12 | NSLog(@"Initializing FastTrie module...");
13 |
14 | RCTBridge *bridge = [RCTBridge currentBridge];
15 | RCTCxxBridge *cxxBridge = (RCTCxxBridge *)bridge;
16 | if (cxxBridge == nil) {
17 | return @false;
18 | }
19 |
20 | using namespace facebook;
21 |
22 | auto jsiRuntime = (jsi::Runtime *)cxxBridge.runtime;
23 | if (jsiRuntime == nil) {
24 | return @false;
25 | }
26 | auto &runtime = *jsiRuntime;
27 |
28 | fasttrie::install(runtime);
29 |
30 | NSLog(@"FastTrie initialized");
31 | return @true;
32 | }
33 |
34 |
35 | @end
36 |
--------------------------------------------------------------------------------
/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/src/screens/Benchmarks/benchmarks/find.ts:
--------------------------------------------------------------------------------
1 | import { wordlistEN } from '../../../wordlists/allWordlists';
2 | import {
3 | type BenchmarkResult,
4 | createTrie,
5 | runBenchmark,
6 | getRandomWordSubstrings,
7 | getFastTrie,
8 | getJsTrie,
9 | } from './utils';
10 |
11 | function findBench(wordlist: string[]): BenchmarkResult {
12 | const words = getRandomWordSubstrings(wordlist, 10000);
13 | const trie = createTrie(getJsTrie, wordlist);
14 | const fastTrie = createTrie(getFastTrie, wordlist);
15 |
16 | return runBenchmark(
17 | 'Find',
18 | () => {
19 | for (const word of words) {
20 | trie.find(word);
21 | }
22 | },
23 | () => {
24 | for (const word of words) {
25 | fastTrie.find(word);
26 | }
27 | }
28 | );
29 | }
30 |
31 | export function registerBenchmarks() {
32 | return [findBench(wordlistEN)];
33 | }
34 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/example/src/screens/Benchmarks/benchmarks/contains.ts:
--------------------------------------------------------------------------------
1 | import { wordlistEN } from '../../../wordlists/allWordlists';
2 | import {
3 | getRandomWords,
4 | type BenchmarkResult,
5 | createTrie,
6 | runBenchmark,
7 | getFastTrie,
8 | getJsTrie,
9 | } from './utils';
10 |
11 | function containsBench(wordlist: string[]): BenchmarkResult {
12 | const words = getRandomWords(wordlist, 1000000);
13 | const trie = createTrie(getJsTrie, wordlist);
14 | const fastTrie = createTrie(getFastTrie, wordlist);
15 |
16 | return runBenchmark(
17 | 'Contains',
18 | () => {
19 | for (const word of words) {
20 | trie.contains(word);
21 | }
22 | },
23 | () => {
24 | for (const word of words) {
25 | fastTrie.contains(word);
26 | }
27 | }
28 | );
29 | }
30 |
31 | export function registerBenchmarks() {
32 | return [containsBench(wordlistEN)];
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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/screens/Tests/testList.tsx:
--------------------------------------------------------------------------------
1 | import { registerConfigurationAndErrorHandlingTests } from './tests/configurationAndErrorHandlingTests';
2 | import { registerDeletionTests } from './tests/deletionTests';
3 | import { registerFindAndContainsTests } from './tests/findAndContainsTests';
4 | import { registerInsertionTests } from './tests/insertionTests';
5 | import { type TestItemType } from './types';
6 |
7 | export const TEST_LIST: Array = [
8 | {
9 | description: 'Insertion tests',
10 | value: true,
11 | registrator: registerInsertionTests,
12 | },
13 | {
14 | description: 'Deletion tests',
15 | value: true,
16 | registrator: registerDeletionTests,
17 | },
18 | {
19 | description: 'Find and Contains tests',
20 | value: true,
21 | registrator: registerFindAndContainsTests,
22 | },
23 | {
24 | description: 'Configuration and Error Handling',
25 | value: true,
26 | registrator: registerConfigurationAndErrorHandlingTests,
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 |
--------------------------------------------------------------------------------
/scripts/pod-install.cjs:
--------------------------------------------------------------------------------
1 | const child_process = require('child_process');
2 |
3 | module.exports = {
4 | name: 'pod-install',
5 | factory() {
6 | return {
7 | hooks: {
8 | afterAllInstalled(project, options) {
9 | if (process.env.POD_INSTALL === '0') {
10 | return;
11 | }
12 |
13 | if (
14 | options &&
15 | (options.mode === 'update-lockfile' ||
16 | options.mode === 'skip-build')
17 | ) {
18 | return;
19 | }
20 |
21 | const result = child_process.spawnSync(
22 | 'yarn',
23 | ['pod-install', 'example/ios'],
24 | {
25 | cwd: project.cwd,
26 | env: process.env,
27 | stdio: 'inherit',
28 | encoding: 'utf-8',
29 | shell: true,
30 | }
31 | );
32 |
33 | if (result.status !== 0) {
34 | throw new Error('Failed to run pod-install');
35 | }
36 | },
37 | },
38 | };
39 | },
40 | };
41 |
--------------------------------------------------------------------------------
/example/src/testing/MochaRnAdapter.ts:
--------------------------------------------------------------------------------
1 | import 'mocha';
2 | import type * as MochaTypes from 'mocha';
3 |
4 | export const rootSuite = new Mocha.Suite('') as MochaTypes.Suite;
5 |
6 | let mochaContext = rootSuite;
7 | let only = false;
8 |
9 | export const clearTests = () => {
10 | rootSuite.suites = [];
11 | rootSuite.tests = [];
12 | mochaContext = rootSuite;
13 | only = false;
14 | };
15 |
16 | export const it = (name: string, f: () => void): void => {
17 | if (!only) {
18 | mochaContext.addTest(new Mocha.Test(name, f) as MochaTypes.Test);
19 | }
20 | };
21 |
22 | export const itOnly = (name: string, f: () => void): void => {
23 | clearTests();
24 | mochaContext.addTest(new Mocha.Test(name, f) as MochaTypes.Test);
25 | only = true;
26 | };
27 |
28 | export const describe = (name: string, f: () => void): void => {
29 | const prevMochaContext = mochaContext;
30 | mochaContext = new Mocha.Suite(
31 | name,
32 | prevMochaContext.ctx
33 | ) as MochaTypes.Suite;
34 | prevMochaContext.addSuite(mochaContext);
35 | f();
36 | mochaContext = prevMochaContext;
37 | };
38 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
12 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/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/screens/Tests/tests/configurationAndErrorHandlingTests.ts:
--------------------------------------------------------------------------------
1 | import { describe, it } from '../../../testing/MochaRnAdapter';
2 | import { expect } from 'chai';
3 | import { FastTrie } from 'react-native-fast-trie';
4 |
5 | export function registerConfigurationAndErrorHandlingTests() {
6 | describe('FastTrie Configuration and Error Handling Tests', () => {
7 | it('should not crash with valid burstThreshold and maxLoadFactor values', () => {
8 | expect(
9 | () => new FastTrie({ burstThreshold: 1024, maxLoadFactor: 8.0 })
10 | ).to.not.throw();
11 | expect(
12 | () => new FastTrie({ burstThreshold: 2048, maxLoadFactor: 10.0 })
13 | ).to.not.throw();
14 | });
15 |
16 | it('should throw an error when instantiated with an invalid type for burstThreshold', () => {
17 | expect(
18 | () => new FastTrie({ burstThreshold: 'invalid' as unknown as number })
19 | ).to.throw();
20 | });
21 |
22 | it('should throw an error when instantiated with an invalid type for maxLoadFactor', () => {
23 | expect(
24 | () => new FastTrie({ maxLoadFactor: 'invalid' as unknown as number })
25 | ).to.throw();
26 | });
27 | });
28 | }
29 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
28 | );
29 | }
30 |
31 | const styles = StyleSheet.create({
32 | container: {
33 | backgroundColor: 'white',
34 | flex: 1,
35 | alignItems: 'center',
36 | justifyContent: 'center',
37 | },
38 | textColor: {
39 | color: 'black',
40 | },
41 | box: {
42 | width: 60,
43 | height: 60,
44 | marginVertical: 20,
45 | },
46 | });
47 |
--------------------------------------------------------------------------------
/example/src/screens/Benchmarks/benchmarks/insert.ts:
--------------------------------------------------------------------------------
1 | import {
2 | createTrie,
3 | type BenchmarkResult,
4 | runBenchmark,
5 | createBip39Dictionaries,
6 | getFastTrie,
7 | getFastJsTrie,
8 | } from './utils';
9 | import { wordlistEN } from '../../../wordlists/allWordlists';
10 |
11 | function singleWordlistBench(wordlist: string[]): BenchmarkResult {
12 | return runBenchmark(
13 | 'Single wordlist',
14 | () => {
15 | createTrie(getFastJsTrie, wordlist);
16 | },
17 | () => {
18 | createTrie(getFastTrie, wordlist);
19 | }
20 | );
21 | }
22 |
23 | function allWordlistsBench(): BenchmarkResult {
24 | return runBenchmark(
25 | 'All wordlists',
26 | () => {
27 | createBip39Dictionaries(getFastJsTrie);
28 | },
29 | () => {
30 | createBip39Dictionaries(getFastTrie);
31 | }
32 | );
33 | }
34 |
35 | function batchInsertBench(wordlist: string[]): BenchmarkResult {
36 | return runBenchmark(
37 | 'Batch insert',
38 | () => {
39 | createTrie(getFastJsTrie, wordlist);
40 | },
41 | () => {
42 | const result = getFastTrie();
43 | result.batchInsert(wordlist);
44 | }
45 | );
46 | }
47 |
48 | export function registerBenchmarks() {
49 | return [
50 | singleWordlistBench(wordlistEN),
51 | batchInsertBench(wordlistEN),
52 | allWordlistsBench(),
53 | ];
54 | }
55 |
--------------------------------------------------------------------------------
/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/src/screens/Tests/tests/deletionTests.ts:
--------------------------------------------------------------------------------
1 | import { describe, it } from '../../../testing/MochaRnAdapter';
2 | import { expect } from 'chai';
3 | import { FastTrie } from 'react-native-fast-trie';
4 |
5 | export function registerDeletionTests() {
6 | describe('FastTrie Deletion Tests', () => {
7 | it('should delete an existing string and verify it no longer exists in the trie', () => {
8 | const trie = new FastTrie();
9 | trie.insert('test');
10 | trie.delete('test');
11 | expect(trie.contains('test')).to.be.false;
12 | });
13 |
14 | it('should not affect the trie when deleting a string that does not exist', () => {
15 | const trie = new FastTrie();
16 | trie.insert('test');
17 | trie.delete('nonexistent');
18 | expect(trie.contains('test')).to.be.true;
19 | });
20 |
21 | it('should respect case sensitivity during deletion', () => {
22 | const trie = new FastTrie();
23 | trie.insert('Test');
24 | trie.delete('test'); // different case
25 | expect(trie.contains('Test')).to.be.true;
26 | });
27 |
28 | it('should throw an error when deleting null', () => {
29 | const trie = new FastTrie();
30 | // @ts-expect-error
31 | expect(() => trie.delete(null)).to.throw();
32 | });
33 |
34 | it('should throw an error when deleting undefined', () => {
35 | const trie = new FastTrie();
36 | // @ts-expect-error
37 | expect(() => trie.delete(undefined)).to.throw();
38 | });
39 |
40 | it('should throw an error when deleting a non-string value', () => {
41 | const trie = new FastTrie();
42 | expect(() => trie.delete(123 as unknown as string)).to.throw();
43 | });
44 | });
45 | }
46 |
--------------------------------------------------------------------------------
/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/src/screens/Benchmarks/SpeedBenchmarks.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import { StyleSheet, View, Text, ActivityIndicator } from 'react-native';
4 | import { startBench } from './benchmarks/bench';
5 | import { type BenchmarkResult } from './benchmarks/utils';
6 |
7 | export function SpeedBenchmarks() {
8 | const [result, setResult] = React.useState();
9 | React.useEffect(() => {
10 | setTimeout(() => {
11 | setResult(startBench());
12 | }, 100);
13 | }, []);
14 |
15 | return (
16 |
17 | {result ? (
18 | result.map((it, index) => (
19 | // eslint-disable-next-line react-native/no-inline-styles
20 |
21 | Test: {it.name}
22 |
23 | JS Trie URL: {it.b1.toFixed(2)}ms
24 |
25 | FastTrie: {it.b2.toFixed(2)}ms
26 |
27 | FastTrie is {(it.b1 / it.b2).toFixed(2)}x faster
28 |
29 |
30 | ))
31 | ) : (
32 |
33 |
34 | Running benchmark...
35 |
36 | )}
37 |
38 | );
39 | }
40 |
41 | const styles = StyleSheet.create({
42 | container: {
43 | backgroundColor: 'white',
44 | flex: 1,
45 | alignItems: 'center',
46 | justifyContent: 'center',
47 | },
48 | textColor: {
49 | color: 'black',
50 | },
51 | box: {
52 | width: 60,
53 | height: 60,
54 | marginVertical: 20,
55 | },
56 | });
57 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/react-native-fast-trie.podspec:
--------------------------------------------------------------------------------
1 | require "json"
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4 | folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
5 |
6 | Pod::Spec.new do |s|
7 | s.name = "react-native-fast-trie"
8 | s.version = package["version"]
9 | s.summary = package["description"]
10 | s.homepage = package["homepage"]
11 | s.license = package["license"]
12 | s.authors = package["author"]
13 |
14 | s.platforms = { :ios => "12.0" }
15 | s.source = { :git => "https://github.com/KusStar/react-native-fast-trie.git", :tag => "#{s.version}" }
16 |
17 | s.source_files = "ios/**/*.{h,m,mm}", "cpp/**/*.{hpp,cpp,c,h}"
18 |
19 | # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
20 | # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
21 | if respond_to?(:install_modules_dependencies, true)
22 | install_modules_dependencies(s)
23 | else
24 | s.dependency "React-Core"
25 |
26 | # Don't install the dependencies when we run `pod install` in the old architecture.
27 | if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
28 | s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
29 | s.pod_target_xcconfig = {
30 | "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\", \"$(PODS_ROOT)/include\"",
31 | "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
32 | "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
33 | }
34 | s.dependency "React-Codegen"
35 | s.dependency "RCT-Folly"
36 | s.dependency "RCTRequired"
37 | s.dependency "RCTTypeSafety"
38 | s.dependency "ReactCommon/turbomodule/core"
39 | end
40 | end
41 | end
42 |
--------------------------------------------------------------------------------
/example/src/screens/Tests/tests/insertionTests.ts:
--------------------------------------------------------------------------------
1 | // insertTests.ts
2 | import { describe, it } from '../../../testing/MochaRnAdapter';
3 | import { expect } from 'chai';
4 | import { FastTrie } from 'react-native-fast-trie';
5 |
6 | export function registerInsertionTests() {
7 | describe('FastTrie Insertion Tests', () => {
8 | it('should insert a single string and find it in the trie', () => {
9 | const trie = new FastTrie();
10 | trie.insert('test');
11 | expect(trie.contains('test')).to.be.true;
12 | });
13 |
14 | it('should treat case-sensitive strings as distinct entries', () => {
15 | const trie = new FastTrie();
16 | trie.insert('apple');
17 | trie.insert('Apple');
18 | expect(trie.contains('apple')).to.be.true;
19 | expect(trie.contains('Apple')).to.be.true;
20 | });
21 |
22 | it('should handle special ASCII characters correctly', () => {
23 | const trie = new FastTrie();
24 | trie.insert('hello@world');
25 | expect(trie.contains('hello@world')).to.be.true;
26 | });
27 |
28 | it('should correctly insert multiple strings using batchInsert', () => {
29 | const trie = new FastTrie();
30 | trie.batchInsert(['one', 'two', 'three']);
31 | expect(trie.contains('one')).to.be.true;
32 | expect(trie.contains('two')).to.be.true;
33 | expect(trie.contains('three')).to.be.true;
34 | });
35 |
36 | it('should throw an error when inserting null', () => {
37 | const trie = new FastTrie();
38 | // @ts-expect-error
39 | expect(() => trie.insert(null)).to.throw();
40 | });
41 |
42 | it('should throw an error when inserting undefined', () => {
43 | const trie = new FastTrie();
44 | // @ts-expect-error
45 | expect(() => trie.insert(undefined)).to.throw();
46 | });
47 |
48 | it('should throw an error when inserting a non-string value', () => {
49 | const trie = new FastTrie();
50 | expect(() => trie.insert(123 as unknown as string)).to.throw();
51 | });
52 | });
53 | }
54 |
--------------------------------------------------------------------------------
/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/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/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/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/src/testing/MochaSetup.ts:
--------------------------------------------------------------------------------
1 | import type { RowItemType } from '../screens/Tests/types';
2 | import { rootSuite, clearTests } from './MochaRnAdapter';
3 | import 'mocha';
4 | import type * as MochaTypes from 'mocha';
5 |
6 | export function testLib(
7 | addTestResult: (testResult: RowItemType) => void,
8 | testRegistrators: Array<() => void> = []
9 | ) {
10 | console.log('setting up mocha');
11 |
12 | const {
13 | EVENT_RUN_BEGIN,
14 | EVENT_RUN_END,
15 | EVENT_TEST_FAIL,
16 | EVENT_TEST_PASS,
17 | EVENT_SUITE_BEGIN,
18 | EVENT_SUITE_END,
19 | } = Mocha.Runner.constants;
20 |
21 | clearTests();
22 | var runner = new Mocha.Runner(rootSuite) as MochaTypes.Runner;
23 |
24 | let indents = -1;
25 | const indent = () => Array(indents).join(' ');
26 | runner
27 | .once(EVENT_RUN_BEGIN, () => {})
28 | .on(EVENT_SUITE_BEGIN, (suite: MochaTypes.Suite) => {
29 | const name = suite.fullTitle();
30 | if (name !== '') {
31 | addTestResult({
32 | indentation: indents,
33 | description: name,
34 | key: Math.random().toString(),
35 | type: 'grouping',
36 | });
37 | }
38 | indents++;
39 | })
40 | .on(EVENT_SUITE_END, () => {
41 | indents--;
42 | })
43 | .on(EVENT_TEST_PASS, (test: MochaTypes.Runnable) => {
44 | addTestResult({
45 | indentation: indents,
46 | description: test.fullTitle(),
47 | key: Math.random().toString(),
48 | type: 'correct',
49 | });
50 | console.log(`${indent()}pass: ${test.fullTitle()}`);
51 | })
52 | .on(EVENT_TEST_FAIL, (test: MochaTypes.Runnable, err: Error) => {
53 | addTestResult({
54 | indentation: indents,
55 | description: test.fullTitle(),
56 | key: Math.random().toString(),
57 | type: 'incorrect',
58 | errorMsg: err.message,
59 | });
60 | console.log(
61 | `${indent()}fail: ${test.fullTitle()} - error: ${err.message}`
62 | );
63 | })
64 | .once(EVENT_RUN_END, () => {});
65 |
66 | testRegistrators.forEach((register) => {
67 | register();
68 | });
69 |
70 | runner.run();
71 |
72 | return () => {
73 | console.log('aborting');
74 | runner.abort();
75 | };
76 | }
77 |
--------------------------------------------------------------------------------
/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/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/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/src/screens/Tests/tests/findAndContainsTests.ts:
--------------------------------------------------------------------------------
1 | import { describe, it } from '../../../testing/MochaRnAdapter';
2 | import { expect } from 'chai';
3 | import { FastTrie } from 'react-native-fast-trie';
4 |
5 | export function registerFindAndContainsTests() {
6 | describe('FastTrie Find and Contains Tests', () => {
7 | it('should return true for contains when the exact string is present in the trie', () => {
8 | const trie = new FastTrie();
9 | trie.insert('hello');
10 | expect(trie.contains('hello')).to.be.true;
11 | });
12 |
13 | it('should return false for contains when the string is not present in the trie', () => {
14 | const trie = new FastTrie();
15 | trie.insert('hello');
16 | expect(trie.contains('world')).to.be.false;
17 | });
18 |
19 | it('should return correct results for find with a given prefix', () => {
20 | const trie = new FastTrie();
21 | trie.insert('hello');
22 | trie.insert('helium');
23 | const results = trie.find('hel');
24 | expect(results).to.include.members(['hello', 'helium']);
25 | });
26 |
27 | it('should respect maxResults in find method', () => {
28 | const trie = new FastTrie();
29 | trie.insert('apple');
30 | trie.insert('applet');
31 | trie.insert('application');
32 | const results = trie.find('app', 2);
33 | expect(results.length).to.equal(2);
34 | });
35 |
36 | it('should respect case sensitivity in find and contains methods', () => {
37 | const trie = new FastTrie();
38 | trie.insert('Test');
39 | trie.insert('test');
40 | expect(trie.contains('Test')).to.be.true;
41 | expect(trie.contains('test')).to.be.true;
42 | expect(trie.find('T')).to.include('Test');
43 | expect(trie.find('t')).to.include('test');
44 | });
45 |
46 | it('should throw an error when find is called with null', () => {
47 | const trie = new FastTrie();
48 | // @ts-expect-error
49 | expect(() => trie.find(null)).to.throw();
50 | });
51 |
52 | it('should throw an error when find is called with undefined', () => {
53 | const trie = new FastTrie();
54 | // @ts-expect-error
55 | expect(() => trie.find(undefined)).to.throw();
56 | });
57 |
58 | it('should throw an error when contains is called with a non-string value', () => {
59 | const trie = new FastTrie();
60 | expect(() => trie.contains(123 as unknown as string)).to.throw();
61 | });
62 | });
63 | }
64 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import { Platform, NativeModules } from 'react-native';
2 |
3 | type FastTrieInstance = {
4 | insert(item: string): void;
5 | delete(item: string): void;
6 | batchInsert(item: string[]): void;
7 | contains(item: string): boolean;
8 | find(prefix: string, maxResults?: number): string[];
9 | };
10 |
11 | type FastTrieModule = (
12 | burstThreshold: number,
13 | maxLoadFactor: number
14 | ) => FastTrieInstance;
15 |
16 | declare global {
17 | var __FastTrie: FastTrieModule;
18 | }
19 |
20 | const LINKING_ERROR =
21 | `The package 'react-native-fast-trie' doesn't seem to be linked. Make sure: \n\n` +
22 | Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
23 | '- You rebuilt the app after installing the package\n' +
24 | '- You are not using Expo Go\n';
25 |
26 | const NativeFastTrie = NativeModules.FastTrie
27 | ? NativeModules.FastTrie
28 | : new Proxy(
29 | {},
30 | {
31 | get() {
32 | throw new Error(LINKING_ERROR);
33 | },
34 | }
35 | );
36 |
37 | if (global.__FastTrie == null) {
38 | const installed = NativeFastTrie.install();
39 |
40 | if (installed) {
41 | } else {
42 | throw new Error(LINKING_ERROR);
43 | }
44 | }
45 |
46 | type FastTrieOptions = {
47 | /**
48 | * The maximum size of an array hash node before a burst occurs. If you are
49 | * mainly dealing with exact searches you should set this value to something larger
50 | * like 16 384. This library defaults the value to 1024 which is better for prefix searches
51 | */
52 | burstThreshold?: number;
53 | /**
54 | * A lower max load factor will increase the speed, a higher one will reduce the memory usage.
55 | * Its default value is set to 8.0.
56 | */
57 | maxLoadFactor?: number;
58 | };
59 |
60 | /**
61 | * A fast trie implementation for React Native.
62 | */
63 | export class FastTrie {
64 | private _trie: ReturnType;
65 |
66 | constructor({
67 | burstThreshold = 1024,
68 | maxLoadFactor = 8.0,
69 | }: FastTrieOptions = {}) {
70 | this._trie = global.__FastTrie(burstThreshold, maxLoadFactor);
71 | }
72 |
73 | insert(item: string): void {
74 | return this._trie.insert(item);
75 | }
76 |
77 | batchInsert(items: string[]): void {
78 | return this._trie.batchInsert(items);
79 | }
80 |
81 | delete(item: string): void {
82 | return this._trie.delete(item);
83 | }
84 |
85 | contains(item: string): boolean {
86 | return this._trie.contains(item);
87 | }
88 |
89 | find(prefix: string, maxResults?: number): string[] {
90 | return this._trie.find(prefix, maxResults);
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/example/src/screens/Tests/Tests.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useCallback, useRef, useEffect } from 'react';
2 | import type { NativeStackScreenProps } from '@react-navigation/native-stack';
3 | import { View, ScrollView, StyleSheet } from 'react-native';
4 | import { testLib } from '../../testing/MochaSetup';
5 | import { CorrectResultItem } from '../../components/CorrectResultItem';
6 | import { IncorrectResultItem } from '../../components/IncorrectResultItem';
7 | import { Suite } from '../../components/Suite';
8 | import { Indentator } from '../../components/Indentator';
9 | import type { RowItemType } from './types';
10 | import type { RootStackParamList } from '../params';
11 |
12 | function useTestRows(): [RowItemType[], (newResult: RowItemType) => void] {
13 | const [rows, setRows] = useState([]);
14 |
15 | let viewIsMounted = useRef(true);
16 |
17 | useEffect(() => {
18 | return () => {
19 | viewIsMounted.current = false;
20 | };
21 | }, []);
22 |
23 | const addResult = useCallback(
24 | (newResult: RowItemType) => {
25 | if (!viewIsMounted.current) {
26 | return;
27 | }
28 | setRows((prevRows) => {
29 | prevRows.push(newResult);
30 | return [...prevRows]; // had to copy to trigger rerender
31 | });
32 | },
33 | [setRows]
34 | );
35 |
36 | return [rows, addResult];
37 | }
38 |
39 | type TestingScreenProps = NativeStackScreenProps;
40 |
41 | export function Tests({ route }: TestingScreenProps) {
42 | const { testRegistrators } = route.params;
43 | const [rows, addRow] = useTestRows();
44 |
45 | useEffect(() => {
46 | const abort = testLib(addRow, testRegistrators);
47 | return () => {
48 | abort();
49 | };
50 | }, [addRow, testRegistrators]);
51 |
52 | return (
53 |
54 |
55 | {rows.map((it) => {
56 | let InnerElement = ;
57 | if (it.type === 'correct') {
58 | InnerElement = ;
59 | }
60 | if (it.type === 'incorrect') {
61 | const errorMsg = it.errorMsg || ''; // Trick TS - How to do it as it should be? :)
62 | InnerElement = (
63 |
67 | );
68 | }
69 | if (it.type === 'grouping') {
70 | InnerElement = ;
71 | }
72 | return (
73 |
74 | {InnerElement}
75 |
76 | );
77 | })}
78 |
79 |
80 | );
81 | }
82 |
83 | const styles = StyleSheet.create({
84 | mainContainer: {
85 | flex: 1,
86 | backgroundColor: 'white',
87 | },
88 | testList: {
89 | flex: 9,
90 | },
91 | menu: {
92 | flex: 1,
93 | alignItems: 'center',
94 | alignContent: 'center',
95 | justifyContent: 'center',
96 | },
97 | scroll: {},
98 | });
99 |
--------------------------------------------------------------------------------
/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/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/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/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/src/screens/Home.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useCallback } from 'react';
2 | import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
3 | import { View, ScrollView, StyleSheet } from 'react-native';
4 | import { useNavigation } from '@react-navigation/native';
5 | import type { TestItemType } from './Tests/types';
6 | import { TEST_LIST } from './Tests/testList';
7 | import { TestItem } from '../components/TestItem';
8 | import { Button } from '../components/Button';
9 | import type { RootStackParamList } from './params';
10 |
11 | const useTests = (): [
12 | Array,
13 | (index: number) => void,
14 | () => void,
15 | () => void
16 | ] => {
17 | const [tests, setTests] = useState>(TEST_LIST);
18 |
19 | const toggle = useCallback(
20 | (index: number) => {
21 | setTests((tests) => {
22 | // @ts-expect-error
23 | tests[index].value = !tests[index].value;
24 | return [...tests];
25 | });
26 | },
27 | [setTests]
28 | );
29 |
30 | const clearAll = useCallback(() => {
31 | setTests((tests) => {
32 | return tests.map((it) => {
33 | it.value = false;
34 | return it;
35 | });
36 | });
37 | }, [setTests]);
38 |
39 | const checkAll = useCallback(() => {
40 | setTests((tests) => {
41 | return tests.map((it) => {
42 | it.value = true;
43 | return it;
44 | });
45 | });
46 | }, [setTests]);
47 |
48 | return [tests, toggle, clearAll, checkAll];
49 | };
50 |
51 | export function Home() {
52 | const [tests, toggle, clearAll, checkAll] = useTests();
53 | const navigation =
54 | useNavigation>();
55 |
56 | return (
57 |
58 |
59 |
60 | {tests.map((test, index: number) => (
61 |
68 | ))}
69 |
70 |
71 |
72 |
73 |
74 | {
77 | navigation.navigate('Tests', {
78 | testRegistrators: tests
79 | .filter((it) => it.value)
80 | .map((it) => it.registrator),
81 | });
82 | }}
83 | />
84 | {
87 | navigation.navigate('Benchmarks');
88 | }}
89 | />
90 |
91 |
92 | );
93 | }
94 |
95 | const styles = StyleSheet.create({
96 | mainContainer: {
97 | flex: 1,
98 | backgroundColor: 'white',
99 | },
100 | testList: {
101 | flex: 9,
102 | },
103 | menu: {
104 | flex: 1,
105 | flexDirection: 'row',
106 | alignItems: 'center',
107 | alignContent: 'space-around',
108 | justifyContent: 'space-around',
109 | },
110 | scrollView: {
111 | paddingHorizontal: 10,
112 | },
113 | });
114 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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/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/src/screens/Benchmarks/MemoryBenchmarks.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import { StyleSheet, View, Text, ActivityIndicator } from 'react-native';
4 | import { measureAllocationSize } from 'react-native-heap-profiler';
5 | import { wordlistEN } from '../../wordlists/allWordlists';
6 | import { FastTrie } from 'react-native-fast-trie';
7 | import { JsTrie } from '../../JsTrie';
8 |
9 | type Result = {
10 | name?: string;
11 | jsTrieAllocation: number;
12 | fastTrieAllocation: number;
13 | diff: number;
14 | percentReduction: number;
15 | };
16 |
17 | function runMemoryBench() {
18 | const results: Result[] = [];
19 |
20 | for (let i = 0; i < 10; i++) {
21 | const jsTrieAllocation = measureAllocationSize(() => {
22 | const trie = new JsTrie();
23 | wordlistEN.forEach((word) => {
24 | trie.insert(word);
25 | });
26 | });
27 |
28 | const jsTrieAllocationInBytes = jsTrieAllocation / 1024 / 1024;
29 |
30 | const fastTrieAllocation = measureAllocationSize(() => {
31 | const trie = new FastTrie();
32 | wordlistEN.forEach((word) => {
33 | trie.insert(word);
34 | });
35 | });
36 |
37 | const fastTrieAllocationInBytes = fastTrieAllocation / 1024 / 1024;
38 |
39 | // Measure in MB
40 | results.push({
41 | jsTrieAllocation: jsTrieAllocationInBytes,
42 | fastTrieAllocation: fastTrieAllocationInBytes,
43 | diff: jsTrieAllocationInBytes - fastTrieAllocationInBytes,
44 | percentReduction:
45 | (1 - fastTrieAllocationInBytes / jsTrieAllocationInBytes) * 100,
46 | });
47 | }
48 |
49 | // Avg the results
50 | return {
51 | name: 'Single trie',
52 | jsTrieAllocation: avgElement(results, 'jsTrieAllocation'),
53 | fastTrieAllocation: avgElement(results, 'fastTrieAllocation'),
54 | diff: avgElement(results, 'diff'),
55 | percentReduction: avgElement(results, 'percentReduction'),
56 | };
57 | }
58 |
59 | function avgElement(results: Record[], key: T) {
60 | return results.reduce((acc, curr) => acc + curr[key], 0) / results.length;
61 | }
62 |
63 | export function MemoryBenchmarks() {
64 | const [results, setResults] = React.useState();
65 | React.useEffect(() => {
66 | setTimeout(() => {
67 | const result = runMemoryBench();
68 | setResults([result]);
69 | }, 100);
70 | }, []);
71 |
72 | return (
73 |
74 | {results ? (
75 | results.map((it, index) => (
76 | // eslint-disable-next-line react-native/no-inline-styles
77 |
78 | Test: {it.name}
79 |
80 | JS Trie URL: {it.jsTrieAllocation.toFixed(2)}MB
81 |
82 |
83 | FastTrie: {it.fastTrieAllocation.toFixed(2)}MB
84 |
85 |
86 | FastTrie uses {it.percentReduction.toFixed(2)}% less memory
87 |
88 |
89 | ))
90 | ) : (
91 |
92 |
93 | Running benchmark...
94 |
95 | )}
96 |
97 | );
98 | }
99 |
100 | const styles = StyleSheet.create({
101 | container: {
102 | backgroundColor: 'white',
103 | flex: 1,
104 | alignItems: 'center',
105 | justifyContent: 'center',
106 | },
107 | textColor: {
108 | color: 'black',
109 | },
110 | box: {
111 | width: 60,
112 | height: 60,
113 | marginVertical: 20,
114 | },
115 | });
116 |
--------------------------------------------------------------------------------
/example/src/screens/Benchmarks/benchmarks/utils.ts:
--------------------------------------------------------------------------------
1 | import performance from 'react-native-performance';
2 | import {
3 | wordlistCZ,
4 | wordlistEN,
5 | wordlistES,
6 | wordlistFR,
7 | wordlistIT,
8 | wordlistJP,
9 | wordlistKR,
10 | wordlistPT,
11 | wordlistZHCN,
12 | wordlistZHTW,
13 | } from '../../../wordlists/allWordlists';
14 | import { Trie } from '../../../Trie';
15 | import { FastTrie } from 'react-native-fast-trie';
16 | import { JsTrie } from '../../../JsTrie';
17 |
18 | export type BenchmarkResult = {
19 | name: string;
20 | b1: number;
21 | b2: number;
22 | };
23 |
24 | export function bench(tag: string, fn: () => void) {
25 | performance.mark('start_' + tag);
26 | fn();
27 | performance.mark('end_' + tag);
28 | performance.measure(tag, 'start_' + tag, 'end_' + tag);
29 | console.log(tag, performance.getEntriesByName(tag));
30 | return performance.getEntriesByName(tag);
31 | }
32 |
33 | export function runBenchmark(
34 | name: string,
35 | f1: () => void,
36 | f2: () => void
37 | ): BenchmarkResult {
38 | global.gc?.();
39 | const b1 = bench(`pure js Trie x - ${name}`, f1);
40 | global.gc?.();
41 | const b2 = bench(`fast Trie x - ${name}`, f2);
42 |
43 | return {
44 | name,
45 | b1: b1[0]?.duration!,
46 | b2: b2[0]?.duration!,
47 | };
48 | }
49 |
50 | export function createTrie(getTrie: () => any, wordlist: string[]) {
51 | const result = getTrie();
52 | for (const word of wordlist) {
53 | result.insert(word);
54 | }
55 | return result;
56 | }
57 |
58 | export function getRandomWords(wordlist: string[], numWords: number) {
59 | const result: string[] = [];
60 | for (let i = 0; i < numWords; i++) {
61 | result.push(
62 | wordlist[Math.floor(Math.random() * wordlist.length)] as string
63 | );
64 | }
65 | return result;
66 | }
67 |
68 | export function getRandomWordSubstrings(wordlist: string[], numWords: number) {
69 | const result: string[] = [];
70 | for (let i = 0; i < numWords; i++) {
71 | const word = wordlist[
72 | Math.floor(Math.random() * wordlist.length)
73 | ] as string;
74 | const start = Math.floor(Math.random() * word.length);
75 | const end = Math.floor(Math.random() * word.length);
76 | result.push(word.substring(start, end));
77 | }
78 | return result;
79 | }
80 |
81 | const wordlists: [string, string[]][] = [
82 | ['en', wordlistEN],
83 | ['es', wordlistES],
84 | ['fr', wordlistFR],
85 | ['it', wordlistIT],
86 | ['pt', wordlistPT],
87 | ['cz', wordlistCZ],
88 | ['jp', wordlistJP],
89 | ['kr', wordlistKR],
90 | ['zhCN', wordlistZHCN],
91 | ['zhTW', wordlistZHTW],
92 | ];
93 |
94 | export function createBip39Dictionaries(getTrie: () => any, batch = false) {
95 | const bip39Dictionaries: Record = {
96 | allLangs: getTrie(),
97 | en: getTrie(),
98 | es: getTrie(),
99 | fr: getTrie(),
100 | it: getTrie(),
101 | pt: getTrie(),
102 | cz: getTrie(),
103 | jp: getTrie(),
104 | kr: getTrie(),
105 | zhCN: getTrie(),
106 | zhTW: getTrie(),
107 | };
108 |
109 | wordlists.forEach(([locale, wordList]) => {
110 | if (batch) {
111 | bip39Dictionaries[locale].batchInsert(wordList);
112 | bip39Dictionaries.allLangs.batchInsert(wordList);
113 | } else {
114 | for (const word of wordList) {
115 | bip39Dictionaries[locale].insert(word);
116 | bip39Dictionaries.allLangs.insert(word);
117 | }
118 | }
119 | });
120 | }
121 |
122 | export const getFastJsTrie = () => new JsTrie();
123 |
124 | export const getJsTrie = () => new Trie();
125 |
126 | export const getFastTrie = () => {
127 | return new FastTrie();
128 | };
129 |
130 | export const getFastTrieWithoutBurst = () => {
131 | return new FastTrie({ burstThreshold: 1 });
132 | };
133 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-fast-trie",
3 | "version": "0.2.1",
4 | "description": "Fast Trie for React Native",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/src/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "*.podspec",
17 | "!ios/build",
18 | "!android/build",
19 | "!android/gradle",
20 | "!android/gradlew",
21 | "!android/gradlew.bat",
22 | "!android/local.properties",
23 | "!**/__tests__",
24 | "!**/__fixtures__",
25 | "!**/__mocks__",
26 | "!**/.*"
27 | ],
28 | "scripts": {
29 | "example": "yarn workspace react-native-fast-trie-example",
30 | "test": "jest",
31 | "typecheck": "tsc --noEmit",
32 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
33 | "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
34 | "prepare": "bob build",
35 | "release": "release-it"
36 | },
37 | "keywords": [
38 | "react-native",
39 | "ios",
40 | "android"
41 | ],
42 | "repository": "https://github.com/zacharyfmarion/react-native-fast-trie",
43 | "author": "zacharyfmarion (https://github.com/zacharyfmarion)",
44 | "license": "MIT",
45 | "bugs": {
46 | "url": "https://github.com/zacharyfmarion/react-native-fast-trie/issues"
47 | },
48 | "homepage": "https://github.com/zacharyfmarion/react-native-fast-trie#readme",
49 | "publishConfig": {
50 | "registry": "https://registry.npmjs.org/"
51 | },
52 | "devDependencies": {
53 | "@commitlint/config-conventional": "^17.0.2",
54 | "@evilmartians/lefthook": "^1.5.0",
55 | "@react-native/eslint-config": "^0.72.2",
56 | "@release-it/conventional-changelog": "^5.0.0",
57 | "@types/jest": "^28.1.2",
58 | "@types/react": "~17.0.21",
59 | "@types/react-native": "0.70.0",
60 | "commitlint": "^17.0.2",
61 | "del-cli": "^5.0.0",
62 | "eslint": "^8.4.1",
63 | "eslint-config-prettier": "^8.5.0",
64 | "eslint-plugin-prettier": "^4.0.0",
65 | "jest": "^28.1.1",
66 | "pod-install": "^0.1.0",
67 | "prettier": "^2.0.5",
68 | "react": "18.2.0",
69 | "react-native": "0.72.7",
70 | "react-native-builder-bob": "^0.20.0",
71 | "release-it": "^15.0.0",
72 | "turbo": "^1.10.7",
73 | "typescript": "^5.0.2"
74 | },
75 | "resolutions": {
76 | "@types/react": "17.0.21"
77 | },
78 | "peerDependencies": {
79 | "react": "*",
80 | "react-native": "*"
81 | },
82 | "workspaces": [
83 | "example"
84 | ],
85 | "packageManager": "yarn@3.6.1",
86 | "engines": {
87 | "node": ">= 18.0.0"
88 | },
89 | "jest": {
90 | "preset": "react-native",
91 | "modulePathIgnorePatterns": [
92 | "/example/node_modules",
93 | "/lib/"
94 | ]
95 | },
96 | "commitlint": {
97 | "extends": [
98 | "@commitlint/config-conventional"
99 | ]
100 | },
101 | "release-it": {
102 | "git": {
103 | "commitMessage": "chore: release ${version}",
104 | "tagName": "v${version}"
105 | },
106 | "npm": {
107 | "publish": true
108 | },
109 | "github": {
110 | "release": true
111 | },
112 | "plugins": {
113 | "@release-it/conventional-changelog": {
114 | "preset": "angular"
115 | }
116 | }
117 | },
118 | "eslintConfig": {
119 | "root": true,
120 | "extends": [
121 | "@react-native",
122 | "prettier"
123 | ],
124 | "rules": {
125 | "prettier/prettier": [
126 | "error",
127 | {
128 | "quoteProps": "consistent",
129 | "singleQuote": true,
130 | "tabWidth": 2,
131 | "trailingComma": "es5",
132 | "useTabs": false
133 | }
134 | ]
135 | }
136 | },
137 | "eslintIgnore": [
138 | "node_modules/",
139 | "lib/"
140 | ],
141 | "prettier": {
142 | "quoteProps": "consistent",
143 | "singleQuote": true,
144 | "tabWidth": 2,
145 | "trailingComma": "es5",
146 | "useTabs": false
147 | },
148 | "react-native-builder-bob": {
149 | "source": "src",
150 | "output": "lib",
151 | "targets": [
152 | "commonjs",
153 | "module",
154 | [
155 | "typescript",
156 | {
157 | "project": "tsconfig.build.json"
158 | }
159 | ]
160 | ]
161 | },
162 | "dependencies": {
163 | "react-native-heap-profiler": "^0.1.0"
164 | }
165 | }
166 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------