├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs └── macros.rs /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | 9 | env: 10 | CARGO_INCREMENTAL: 0 11 | CARGO_NET_RETRY: 10 12 | CARGO_TERM_COLOR: always 13 | RUST_BACKTRACE: 1 14 | RUSTFLAGS: -D warnings 15 | RUSTUP_MAX_RETRIES: 10 16 | 17 | jobs: 18 | test: 19 | name: cargo test (${{ matrix.os }}) 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | os: 24 | - ubuntu-latest 25 | - macos-latest 26 | - windows-latest 27 | runs-on: ${{ matrix.os }} 28 | steps: 29 | - uses: actions/checkout@v3 30 | - uses: dtolnay/rust-toolchain@v1 31 | with: 32 | toolchain: nightly 33 | - name: Cargo Test 34 | run: | 35 | cargo test --all --verbose 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "radix-tree" 3 | version = "0.2.1" 4 | authors = ["Fangdun Tsai "] 5 | edition = "2018" 6 | description = "A radix tree implementation for router, path search" 7 | documentation = "https://docs.rs/radix-tree" 8 | repository = "https://github.com/viz-rs/radix-tree" 9 | readme = "README.md" 10 | keywords = ["radix", "tree", "router", "trek"] 11 | license = "MIT/Apache-2.0" 12 | 13 | [dependencies] 14 | log = "^0.4.17" 15 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Fangdun Cai 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Fangdun Cai 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # radix-tree 2 | 3 | A [radix tree] implementation for router, path search. 4 | 5 | [![Latest version](https://img.shields.io/crates/v/radix-tree.svg)](https://crates.io/crates/radix-tree) 6 | [![Documentation](https://docs.rs/radix-tree/badge.svg)](https://docs.rs/radix-tree) 7 | ![License](https://img.shields.io/crates/l/radix-tree.svg) 8 | 9 | ## Features 10 | 11 | - Supports many types. Like `char`, `u8` `u32` etc. 12 | 13 | ## Usage 14 | 15 | ```rust 16 | use radix_tree::{Node, Vectorable}; 17 | 18 | let mut tree = Node::::new("", Some(false)); 19 | 20 | tree.insert("alligator", true); 21 | tree.insert("alien", true); 22 | tree.insert("baloon", true); 23 | tree.insert("chromodynamic", true); 24 | tree.insert("romane", true); 25 | tree.insert("romanus", true); 26 | tree.insert("romulus", true); 27 | tree.insert("rubens", true); 28 | tree.insert("ruber", true); 29 | tree.insert("rubicon", true); 30 | tree.insert("rubicundus", true); 31 | tree.insert("all", true); 32 | tree.insert("rub", true); 33 | tree.insert("ba", true); 34 | tree.insert("你好,世界", true); 35 | tree.insert("你好", true); 36 | tree.insert("你", true); 37 | 38 | let node = tree.find("all"); 39 | assert_eq!(node.is_some(), true); 40 | assert_eq!(node.unwrap().data.unwrap(), true); 41 | 42 | let node = tree.find("dota2"); 43 | assert_eq!(node.is_none(), true); 44 | ``` 45 | 46 | **Tree**: 47 | 48 | ``` 49 | `-(a) [l] --> [li] []=false 50 | `l-(i) [gator] --> [] []=true 51 | `ien-() [] --> [] []=true 52 | `-(b) [a] --> [l] []=true 53 | `loon-() [] --> [] []=true 54 | `-(c) [hromodynamic] --> [] []=true 55 | `-(r) [] --> [ou] []=false 56 | `om-(a) [n] --> [eu] []=false 57 | `e-() [] --> [] []=true 58 | `us-() [] --> [] []=true 59 | `om-(u) [lus] --> [] []=true 60 | `ub-(e) [] --> [nr] []=false 61 | `ns-() [] --> [] []=true 62 | `r-() [] --> [] []=true 63 | `ub-(i) [c] --> [ou] []=false 64 | `on-() [] --> [] []=true 65 | `undus-() [] --> [] []=true 66 | ``` 67 | 68 | ## Examples 69 | 70 | ```rust 71 | let node = Node::::new("Hello world!", Some("a")); 72 | assert_eq!( 73 | node.path, 74 | vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33] 75 | ); 76 | assert_eq!(node.data.unwrap(), "a"); 77 | 78 | let node = Node::::new("Hello 世界!", Some("a")); 79 | assert_eq!( 80 | node.path, 81 | vec![72, 101, 108, 108, 111, 32, 228, 184, 150, 231, 149, 140, 239, 188, 129] 82 | ); 83 | assert_eq!(node.data.unwrap(), "a"); 84 | 85 | let node = Node::::new("Hello 世界!", Some("a")); 86 | assert_eq!( 87 | node.path, 88 | vec!['H', 'e', 'l', 'l', 'o', ' ', '世', '界', '!'] 89 | ); 90 | assert_eq!(node.data.unwrap(), "a"); 91 | 92 | let node = Node::::new("你好,世界!", Some(0)); 93 | assert_eq!(node.path, vec!['你', '好', ',', '世', '界', '!']); 94 | assert_eq!(node.data.unwrap(), 0); 95 | 96 | let node = Node::::new("abcde", Some(1)); 97 | assert_eq!(node.path, vec![97, 98, 99, 100, 101]); 98 | assert_eq!(node.data.unwrap(), 1); 99 | 100 | let node = Node::new("abcde".as_bytes().to_vec(), Some(97)); 101 | assert_eq!(node.path, vec![97, 98, 99, 100, 101]); 102 | assert_eq!(node.data.unwrap(), 97); 103 | 104 | let node = Node::new("abcde".as_bytes(), Some(97)); 105 | assert_eq!(node.path, vec![97, 98, 99, 100, 101]); 106 | assert_eq!(node.data.unwrap(), 97); 107 | ``` 108 | 109 | ## Acknowledgements 110 | 111 | It is inspired by the: 112 | 113 | - [rax] 114 | - [httprouter] 115 | - [echo] router 116 | - [trekjs] router 117 | 118 | ## License 119 | 120 | This project is licensed under either of 121 | 122 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 123 | http://www.apache.org/licenses/LICENSE-2.0) 124 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or 125 | http://opensource.org/licenses/MIT) 126 | 127 | [radix tree]: https://en.wikipedia.org/wiki/Radix_tree 128 | [rax]: https://github.com/antirez/rax 129 | [httprouter]: https://github.com/julienschmidt/httprouter 130 | [echo]: https://github.com/labstack/echo 131 | [trekjs]: https://github.com/trekjs/router 132 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | extern crate alloc; 3 | 4 | #[allow(unused_imports)] // ambiguity between `vec!` macro and `vec` module doesn't sit well with compiler 5 | use alloc::vec; 6 | use alloc::vec::Vec; 7 | use alloc::borrow::ToOwned; 8 | use core::mem; 9 | 10 | const fn pos(l: &usize, _: &K, _: &Vec) -> usize { 11 | *l 12 | } 13 | 14 | pub trait Vectorable 15 | where 16 | K: Copy + PartialEq + PartialOrd, 17 | { 18 | fn into(&self) -> Vec; 19 | } 20 | 21 | #[macro_use] 22 | pub mod macros; 23 | 24 | pub trait Radix> 25 | where 26 | K: Copy + PartialEq + PartialOrd, 27 | V: Clone, 28 | { 29 | fn remove(&mut self, path: P); 30 | fn insert(&mut self, path: P, data: V) -> &mut Self; 31 | fn find(&self, path: P) -> Option<&Self>; 32 | fn add_node(&mut self, path: P, data: V) -> &mut Self; 33 | fn find_node(&self, path: P) -> Option<&Self>; 34 | } 35 | 36 | #[derive(Debug, Clone, PartialEq)] 37 | pub struct Node { 38 | pub path: Vec, 39 | pub data: Option, 40 | pub indices: Vec, 41 | pub nodes: Vec>, 42 | } 43 | 44 | impl Node 45 | where 46 | K: Copy + PartialEq + PartialOrd, 47 | V: Clone, 48 | { 49 | pub fn new>(path: P, data: Option) -> Self { 50 | Node { 51 | data, 52 | path: (&path).into(), 53 | nodes: Vec::new(), 54 | indices: Vec::new(), 55 | } 56 | } 57 | 58 | pub fn insert_with( 59 | &mut self, 60 | path: &mut Vec, 61 | data: Option, 62 | force_update: bool, 63 | pos: F, 64 | ) -> &mut Self 65 | where 66 | F: Fn(&usize, &K, &Vec) -> usize, 67 | { 68 | let pl = path.len(); 69 | let sl = self.path.len(); 70 | 71 | // empty input path 72 | if 0 == pl { 73 | if force_update { 74 | self.data = data; 75 | } 76 | return self; 77 | } 78 | 79 | // empty node 80 | if 0 == sl && 0 == self.indices.len() { 81 | if force_update { 82 | self.data = data; 83 | } 84 | self.path = path.to_owned(); 85 | return self; 86 | } 87 | 88 | // pl > 0 && sl >= 0 89 | let max = pl.min(sl); 90 | let mut i = 0; 91 | while i < max && path[i] == self.path[i] { 92 | i += 1; 93 | } 94 | 95 | if i < sl { 96 | let child = Node { 97 | data: self.data.take(), 98 | path: self.path.split_off(i), 99 | nodes: mem::replace(&mut self.nodes, Vec::new()), 100 | indices: mem::replace(&mut self.indices, Vec::new()), 101 | }; 102 | let c = child.path[0]; 103 | let index = pos(&self.indices.len(), &c, &self.indices); 104 | self.indices.insert(index, c); 105 | self.nodes.insert(index, child); 106 | 107 | // self.indices.push(child.path[0]); 108 | // self.nodes.push(child); 109 | } 110 | 111 | if i == pl { 112 | if force_update { 113 | self.data = data; 114 | } 115 | return self; 116 | } 117 | 118 | self.add_node_with(path, data, i, force_update, pos) 119 | } 120 | 121 | pub fn add_node_with( 122 | &mut self, 123 | path: &mut Vec, 124 | data: Option, 125 | i: usize, 126 | force_update: bool, 127 | pos: F, 128 | ) -> &mut Self 129 | where 130 | F: Fn(&usize, &K, &Vec) -> usize, 131 | { 132 | let l = self.indices.len(); 133 | let c = path[i]; 134 | let mut j = 0; 135 | while j < l { 136 | if c == self.indices[j] { 137 | return self.nodes[j].insert_with(&mut path.split_off(i), data, force_update, pos); 138 | } 139 | j += 1; 140 | } 141 | 142 | let index = pos(&l, &c, &self.indices); 143 | self.indices.insert(index, c); 144 | self.nodes.insert( 145 | index, 146 | Node { 147 | data, 148 | nodes: Vec::new(), 149 | indices: Vec::new(), 150 | path: path.split_off(i), 151 | }, 152 | ); 153 | 154 | &mut self.nodes[index] 155 | 156 | // self.indices.push(c); 157 | // self.nodes.push(Node { 158 | // data, 159 | // nodes: Vec::new(), 160 | // indices: Vec::new(), 161 | // path: path.split_off(i), 162 | // }); 163 | // &mut self.nodes[l] 164 | } 165 | 166 | pub fn find_with(&self, path: &mut Vec) -> Option<&Self> { 167 | let pl = path.len(); 168 | let sl = self.path.len(); 169 | 170 | // "abc" < "abcde" 171 | // not found 172 | if pl < sl { 173 | return None; 174 | } 175 | 176 | // "abcde" > "abc" or "abc" == "abc" 177 | let mut i = 0; 178 | while i < sl && path[i] == self.path[i] { 179 | i += 1; 180 | } 181 | 182 | // "abc" == "abc" 183 | if pl == sl { 184 | if i == pl { 185 | return Some(self); 186 | } 187 | // not found 188 | return None; 189 | } 190 | 191 | // "abcde" > "abc" 192 | self.find_node_with(path, i) 193 | } 194 | 195 | pub fn find_node_with(&self, path: &mut Vec, i: usize) -> Option<&Self> { 196 | let l = self.indices.len(); 197 | let c = path[i]; 198 | let mut j = 0; 199 | while j < l { 200 | if c == self.indices[j] { 201 | return self.nodes[j].find_with(&mut path.split_off(i)); 202 | } 203 | j += 1; 204 | } 205 | // not found 206 | None 207 | } 208 | } 209 | 210 | impl> Radix for Node 211 | where 212 | K: Copy + PartialEq + PartialOrd, 213 | V: Clone, 214 | { 215 | #[allow(unused_variables)] 216 | fn remove(&mut self, path: P) {} 217 | 218 | fn insert(&mut self, path: P, data: V) -> &mut Self { 219 | self.insert_with(&mut (&path).into(), Some(data), true, pos) 220 | } 221 | 222 | fn find(&self, path: P) -> Option<&Self> { 223 | self.find_with(&mut (&path).into()) 224 | } 225 | 226 | fn add_node(&mut self, path: P, data: V) -> &mut Self { 227 | self.add_node_with(&mut (&path).into(), Some(data), 0, true, pos) 228 | } 229 | 230 | fn find_node(&self, path: P) -> Option<&Self> { 231 | self.find_node_with(&mut (&path).into(), 0) 232 | } 233 | } 234 | 235 | #[cfg(test)] 236 | mod tests { 237 | use super::*; 238 | 239 | macro_rules! find { 240 | ($tree:expr, $($path:expr, $data:expr),*,) => {{ 241 | $( 242 | let node = $tree.find($path); 243 | assert_eq!(node.is_some(), $data); 244 | if node.is_some() { 245 | assert_eq!(node.unwrap().data.unwrap(), $data); 246 | } 247 | )* 248 | }}; 249 | } 250 | 251 | macro_rules! insert_and_find { 252 | ($tree:expr, $($path:expr, $data:expr),*,) => {{ 253 | $( 254 | $tree.insert($path, $data); 255 | find!($tree, $path, $data,); 256 | )* 257 | }}; 258 | } 259 | 260 | #[test] 261 | fn new_any_type_node() { 262 | let node = Node::::new("Hello world!", Some("a")); 263 | assert_eq!( 264 | node.path, 265 | vec![72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33] 266 | ); 267 | assert_eq!(node.data.unwrap(), "a"); 268 | 269 | let node = Node::::new("Hello 世界!", Some("a")); 270 | assert_eq!( 271 | node.path, 272 | vec![72, 101, 108, 108, 111, 32, 228, 184, 150, 231, 149, 140, 239, 188, 129] 273 | ); 274 | assert_eq!(node.data.unwrap(), "a"); 275 | 276 | let node = Node::::new("Hello 世界!", Some("a")); 277 | assert_eq!( 278 | node.path, 279 | vec!['H', 'e', 'l', 'l', 'o', ' ', '世', '界', '!'] 280 | ); 281 | assert_eq!(node.data.unwrap(), "a"); 282 | 283 | let node = Node::::new("你好,世界!", Some(0)); 284 | assert_eq!(node.path, vec!['你', '好', ',', '世', '界', '!']); 285 | assert_eq!(node.data.unwrap(), 0); 286 | 287 | let node = Node::::new("abcde", Some(1)); 288 | assert_eq!(node.path, vec![97, 98, 99, 100, 101]); 289 | assert_eq!(node.data.unwrap(), 1); 290 | 291 | let node = Node::new("abcde".as_bytes().to_vec(), Some(97)); 292 | assert_eq!(node.path, vec![97, 98, 99, 100, 101]); 293 | assert_eq!(node.data.unwrap(), 97); 294 | 295 | let node = Node::new("abcde".as_bytes(), Some(97)); 296 | assert_eq!(node.path, vec![97, 98, 99, 100, 101]); 297 | assert_eq!(node.data.unwrap(), 97); 298 | } 299 | 300 | #[test] 301 | fn node_insert_and_find() { 302 | let mut node = Node::::new("你好,世界!", Some(true)); 303 | node.add_node("Rust", true); 304 | 305 | let n1 = node.find_node("Rust"); 306 | let n2 = node.find("你好,世界!Rust"); 307 | assert_eq!(n1, n2); 308 | } 309 | 310 | #[test] 311 | fn node_insert_then_return_new_node() { 312 | let mut tree = Node::::new("", Some(b' ')); 313 | 314 | let a = tree.insert("a", b'a'); 315 | let b = a.add_node("b", b'b'); 316 | let c = b.add_node("c", b'c'); 317 | let d = c.add_node("d", b'd'); 318 | let _ = d.add_node("e", b'e'); 319 | 320 | // println!("{:#?}", tree); 321 | 322 | let node = tree.find("a"); 323 | assert_eq!(node.is_some(), true); 324 | let a = node.unwrap(); 325 | assert_eq!(a.data.unwrap(), b'a'); 326 | 327 | let node = a.find_node("b"); 328 | assert_eq!(node.is_some(), true); 329 | let b = node.unwrap(); 330 | assert_eq!(b.data.unwrap(), b'b'); 331 | 332 | let node = b.find_node("c"); 333 | assert_eq!(node.is_some(), true); 334 | let c = node.unwrap(); 335 | assert_eq!(c.data.unwrap(), b'c'); 336 | 337 | let node = c.find_node("d"); 338 | assert_eq!(node.is_some(), true); 339 | let d = node.unwrap(); 340 | assert_eq!(d.data.unwrap(), b'd'); 341 | 342 | let node = d.find_node("e"); 343 | assert_eq!(node.is_some(), true); 344 | let e = node.unwrap(); 345 | assert_eq!(e.data.unwrap(), b'e'); 346 | 347 | let node = a.find("abcde"); 348 | assert_eq!(node.is_some(), true); 349 | assert_eq!(node.unwrap().data.unwrap(), b'e'); 350 | 351 | let node = tree.find("abcdef"); 352 | assert_eq!(node.is_some(), false); 353 | 354 | let node = tree.find("b"); 355 | assert_eq!(node.is_some(), false); 356 | } 357 | 358 | #[test] 359 | fn new_tree() { 360 | let mut tree = Node::::new("", Some(false)); 361 | 362 | insert_and_find!( 363 | tree, 364 | "alligator", 365 | true, 366 | "alien", 367 | true, 368 | "baloon", 369 | true, 370 | "chromodynamic", 371 | true, 372 | "romane", 373 | true, 374 | "romanus", 375 | true, 376 | "romulus", 377 | true, 378 | "rubens", 379 | true, 380 | "ruber", 381 | true, 382 | "rubicon", 383 | true, 384 | "rubicundus", 385 | true, 386 | "all", 387 | true, 388 | "rub", 389 | true, 390 | "ba", 391 | true, 392 | "你好,世界", 393 | true, 394 | "你好", 395 | true, 396 | "你", 397 | true, 398 | ); 399 | 400 | find!( 401 | tree, "rpxxx", false, "chro", false, "chromz", false, "zorro", false, "ro", false, 402 | "zo", false, 403 | ); 404 | 405 | let node = tree.find(""); 406 | assert_eq!(node.is_some(), true); 407 | assert_eq!(node.unwrap().data, None); 408 | 409 | tree.insert("", false); 410 | let node = tree.find(""); 411 | assert_eq!(node.is_some(), true); 412 | assert_eq!(node.unwrap().data.unwrap(), false); 413 | 414 | let node = tree.find("all"); 415 | assert_eq!(node.is_some(), true); 416 | assert_eq!(node.unwrap().data.unwrap(), true); 417 | 418 | let node = tree.find("dota2"); 419 | assert_eq!(node.is_none(), true); 420 | 421 | let node = tree.find("你"); 422 | assert_eq!(node.is_some(), true); 423 | assert_eq!(node.unwrap().data.unwrap(), true); 424 | 425 | let node = tree.find("你好"); 426 | assert_eq!(node.is_some(), true); 427 | assert_eq!(node.unwrap().data.unwrap(), true); 428 | 429 | let node = tree.find("语言"); 430 | assert_eq!(node.is_some(), false); 431 | 432 | let node = tree.find("你好,世界"); 433 | assert_eq!(node.is_some(), true); 434 | 435 | let node = tree.find("你好,世界 Rust"); 436 | assert_eq!(node.is_some(), false); 437 | 438 | log::info!("{:#?}", tree); 439 | } 440 | 441 | #[test] 442 | fn clone_node() { 443 | let mut node = Node::::new("", Some(false)); 444 | let mut node2 = node.clone(); 445 | assert_eq!(node, node2); 446 | 447 | node.add_node("/", true); 448 | node2.add_node("/", true); 449 | assert_eq!(node, node2); 450 | 451 | #[derive(Debug, Clone, PartialEq)] 452 | struct NodeMetadata { 453 | is_key: bool, 454 | params: Option>, 455 | } 456 | 457 | let mut node = Node::::new( 458 | "/", 459 | Some(NodeMetadata { 460 | is_key: false, 461 | params: Some(vec![]), 462 | }), 463 | ); 464 | let mut node2 = node.clone(); 465 | assert_eq!(node, node2); 466 | 467 | node.add_node( 468 | "users", 469 | NodeMetadata { 470 | is_key: true, 471 | params: Some(vec!["tree"]), 472 | }, 473 | ); 474 | node2.add_node( 475 | "users", 476 | NodeMetadata { 477 | is_key: true, 478 | params: Some(vec!["tree"]), 479 | }, 480 | ); 481 | assert_eq!(node, node2); 482 | } 483 | } 484 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | use crate::Vectorable; 2 | use alloc::string::String; 3 | use alloc::vec::Vec; 4 | use alloc::borrow::ToOwned; 5 | 6 | #[doc(hidden)] 7 | #[macro_export] 8 | #[allow(unused_macros)] 9 | macro_rules! impl_vec { 10 | ($from: ty, $to: ty, $transform: expr) => { 11 | impl Vectorable<$to> for $from { 12 | #[inline] 13 | fn into(&self) -> Vec<$to> { 14 | $transform(self) 15 | } 16 | } 17 | }; 18 | } 19 | 20 | #[doc(hidden)] 21 | #[macro_export] 22 | #[allow(unused_macros)] 23 | macro_rules! impl_vec_k { 24 | ($from: ty, $transform: expr) => { 25 | impl Vectorable for $from 26 | where 27 | K: Copy + PartialEq + PartialOrd, 28 | { 29 | #[inline] 30 | fn into(&self) -> Vec { 31 | $transform(self) 32 | } 33 | } 34 | }; 35 | } 36 | 37 | impl_vec!(&'static str, u8, |x: &'static str| x.as_bytes().to_owned()); 38 | impl_vec!(String, u8, |x: &String| x.as_bytes().to_owned()); 39 | 40 | impl_vec!(&'static str, u32, |x: &'static str| x 41 | .chars() 42 | .map(|x| x as u32) 43 | .collect()); 44 | impl_vec!(String, u32, |x: &String| x 45 | .chars() 46 | .map(|x| x as u32) 47 | .collect()); 48 | 49 | impl_vec!(&'static str, char, |x: &'static str| x.chars().collect()); 50 | impl_vec!(String, char, |x: &String| x.chars().collect()); 51 | 52 | impl_vec_k!(Vec, |x: &Vec| x.to_owned()); 53 | impl_vec_k!(&[K], |x: &[K]| x.to_owned()); 54 | --------------------------------------------------------------------------------