├── .github └── buildomat │ ├── config.toml │ └── jobs │ └── build-and-test.sh ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── rustfmt.toml └── src └── lib.rs /.github/buildomat/config.toml: -------------------------------------------------------------------------------- 1 | enable = true 2 | -------------------------------------------------------------------------------- /.github/buildomat/jobs/build-and-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #: 3 | #: name = "build-and-test" 4 | #: variety = "basic" 5 | #: target = "helios-2.0" 6 | #: rust_toolchain = "stable" 7 | #: output_rules = [ ] 8 | #: 9 | 10 | set -o errexit 11 | set -o pipefail 12 | set -o xtrace 13 | 14 | cargo --version 15 | rustc --version 16 | 17 | banner build 18 | cargo build 19 | 20 | cargo fmt -- --check 21 | cargo clippy -- --deny warnings 22 | 23 | banner test 24 | cargo test 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | *.sw* 3 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "poptrie" 7 | version = "0.1.0" 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "poptrie" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Poptrie 2 | 3 | A poptrie is a data structure and set of algorithms for performing longest 4 | prefix match of an IP address over a set of IP prefixes. Its primary use is 5 | implementing routing tables. 6 | 7 | Poptrie was created by Asai and Ohara in: 8 | 9 | > Asai, Hirochika, and Yasuhiro Ohara. "Poptrie: A compressed trie with 10 | > population count for fast and scalable software IP routing table lookup." 11 | > ACM SIGCOMM Computer Communication Review 45.4 (2015): 57-70. 12 | 13 | This is a dependency free `no_std` implementation to facilitate use in OS 14 | kernels. 15 | 16 | **This is a work in progress implementation.** 17 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | max_width = 80 3 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // This Source Code Form is subject to the terms of the Mozilla Public 2 | // License, v. 2.0. If a copy of the MPL was not distributed with this 3 | // file, You can obtain one at https://mozilla.org/MPL/2.0/. 4 | 5 | // Copyright 2023 Oxide Computer Company 6 | 7 | #![no_std] 8 | 9 | //! A poptrie implementation. 10 | //! 11 | //! A poptrie is a data structure and set of algorithms for performing longest 12 | //! prefix match of an IP address over a set of IP prefixes. Its primary use is 13 | //! implementing routing tables. 14 | //! 15 | //! Poptrie was created by Asai and Ohara in: 16 | //! 17 | //! > Asai, Hirochika, and Yasuhiro Ohara. "Poptrie: A compressed trie with 18 | //! > population count for fast and scalable software IP routing table lookup." 19 | //! > ACM SIGCOMM Computer Communication Review 45.4 (2015): 57-70. 20 | //! 21 | //! This is a dependency free `no_std` implementation to facilitate use in OS 22 | //! kernels. 23 | //! 24 | //! ## By Example 25 | //! 26 | //! This section describes describes a poptrie by building and querying one. 27 | //! Consider a routing table with the following entries. 28 | //! 29 | //! ```text 30 | //! Destination Nexthop 31 | //! ----------- ------- 32 | //! 1.0.0.0/8 1.254.254.254 33 | //! 247.33.0.0/16 247.33.0.1 34 | //! 247.33.12.0/24 247.33.12.1 35 | //! 51.12.109.0/24 51.12.109.10 36 | //! 77.18.0.0/16 77.18.10.1 37 | //! 170.1.14.3/32 1.7.0.1 38 | //! 0.0.0.0.0/0 1.2.3.4 39 | //! ``` 40 | //! We are going to build a poptrie based on 64-bit bitmaps. The way that 41 | //! poptrie works is by breaking up the IP address we need a nexthop for into 42 | //! prefix chunks. The nodes of a poptrie contain bitmaps. Each one in the 43 | //! bitmap is a pointer to a child node. This means there up to 64 child nodes 44 | //! for any given poptrie node. Therefore if a prefix chunk needs to map onto 45 | //! one of 64 values, the prefix may only contain up to 64 values. This means 46 | //! the prefixes must have a numeric value no larger than 64 which is another 47 | //! way of saying they can be no larger than 6 bits. 48 | //! 49 | //! Let's start to construct a poptrie for the routing table described above. 50 | //! 51 | //! ```text 52 | //! Destination Numeric value of fist 6 bits 53 | //! ----------- ---------------------------- 54 | //! 1.0.0.0/8 0 55 | //! 247.33.0.0/16 61 56 | //! 247.33.12.0/24 61 57 | //! 51.12.109.0/24 12 58 | //! 77.18.0.0/16 19 59 | //! 170.1.14.3/32 42 60 | //! 0.0.0.0.0/0 . 61 | //! ``` 62 | //! 63 | //! This gives us a root poptrie node that looks like this. 64 | //! 65 | //! ```text 66 | //! 6 4 1 1 67 | //! 1 2 9 2 0 68 | //! +-------------------------+ 69 | //! |..|1|..|1|..|1|..|1|..|1|| 70 | //! +-------------------------+ 71 | //! ``` 72 | //! 73 | //! The first five destinations in the routing table have prefix lengths that 74 | //! are greater than 6. Therefore, a `1` is placed at the bitmap location 75 | //! corresponding to the numeric value of the first 6 bits of the prefix, 76 | //! indicating that further tree traversal is required in order to match those 77 | //! prefixes. The last entry in the routing table, the default route, has a 78 | //! prefix length less than 6. This means the first 6 bits of any query is 79 | //! sufficient to match against this prefix and a `0` is placed at the 80 | //! corresponding bitmap location. 81 | //! 82 | //! We'll refer to this bitmap as `v`. 83 | //! 84 | //! For any IP address, if we call the numeric value of the first 6 bits `n`, we 85 | //! have a selector `sel` as follows. 86 | //! 87 | //! ```text 88 | //! sel = 1 << n 89 | //! ``` 90 | //! 91 | //! The bitwise intersection of `sel` and `v` tells us what kind of node is next 92 | //! in the trie. If `sel & v` is zero, then we have reached a leaf node. 93 | //! Otherwise we have reached an interior node. The root of the tree is always 94 | //! an interior node. The poptrie data structure keeps interior and leaf nodes 95 | //! in two distinct arrays. 96 | //! 97 | //! ``` 98 | //! use poptrie::*; 99 | //! pub struct Poptrie { 100 | //! pub interior: Vec, 101 | //! pub leaf: Vec>, 102 | //! pub default: Option>, 103 | //! } 104 | //! ``` 105 | //! 106 | //! Once we have determined if a selector leads us to an interior or leaf node, 107 | //! we need to combine `sel` and `v` to form an index into the corresponding 108 | //! array. In the case of an interior node, this selector is formed as follows. 109 | //! 110 | //! ```text 111 | //! i = popcnt(v & ((2 << n) - 1)) 112 | //! ``` 113 | //! 114 | //! This turns all the zeros to the right of the selector (or put differently, 115 | //! in positions of lesser significance) into ones. The population count 116 | //! (`popcnt`) instruction then counts those ones. This gives us a partial index 117 | //! into the interior nodes array. Because the index has a maximum value of 64, 118 | //! this can only be a relative index as there will be many more than 64 119 | //! interior and leaf nodes in a real tree. To overcome this, interior nodes 120 | //! contain an offset to combine with the index to find the correct position in 121 | //! the corresponding array. 122 | //! 123 | //! ``` 124 | //! pub struct Interior { 125 | //! pub iv: u64, 126 | //! pub interior_offset: u64, 127 | //! pub leaf_offset: u64, 128 | //! } 129 | //! ``` 130 | //! 131 | //! The complete index is then 132 | //! 133 | //! ```text 134 | //! i += interior_offset 135 | //! ``` 136 | //! 137 | //! In the leaf-node case where the bitwise intersection of `sel` and `v` is 138 | //! zero we need to form the index a bit differently as the above `popcnt` will 139 | //! just equal zero. This is easily done by flipping the bits in `v` and then 140 | //! applying the same logic. This has the effect of counting the zeros to the 141 | //! right of the one in `sel`. 142 | //! 143 | //! ```text 144 | //! i = popcnt(!v & ((2 << n) - 1)) 145 | //! ``` 146 | //! 147 | //! **TODO(ry):** is the bitwise and really necessary in the `popcnt` 148 | //! calculation. We already know from the selector test whether or not there is 149 | //! an intersection so should we be able to just do `popcnt((2 << n) - 1)`? in 150 | //! either the interior or leaf case? 151 | //! 152 | //! To complete our root poptrie node above, we need to add offsets. In this 153 | //! case, since it's the root node and there are no other nodes yet we can set 154 | //! the `interior_offset` to `1` (accounting for the root node itself) and the 155 | //! `leaf_offset` to `0`. 156 | //! 157 | //! ```text 158 | //! 6 4 1 1 159 | //! 1 2 9 2 0 160 | //! +-------------------------+ 161 | //! |..|1|..|1|..|1|..|1|..|1|| interior_offset=1 leaf_offset=0 162 | //! +-------------------------+ 163 | //! ``` 164 | //! 165 | //! We need a leaf node for the default route. In this example we'll have leaf 166 | //! nodes contain nexthops directly. Therefore the single leaf node contained by 167 | //! the root node is the following (the default route). This route is not 168 | //! pointed to by any particular child index, as the prefix length is zero, so 169 | //! this is a bit of a special case. 170 | //! 171 | //! ```text 172 | //! +---------+ 173 | //! null -> | 1.2.3.4 | 174 | //! +---------+ 175 | //! ``` 176 | //! 177 | //! In order to determine the rest of the nodes, it will be useful to break out 178 | //! the prefixes in the routing table into 6-bit segments. 179 | //! 180 | //! ```text 181 | //! Destination Segments 6-bit values 182 | //! ----------- -------- ------------ 183 | //! 1.0.0.0/8 000000_010000_000000_000000_000000_00 |0 16 | 184 | //! 247.33.0.0/16 111101_110010_000100_000000_000000_00 |61 50 4 | 185 | //! 247.33.12.0/24 111101_110010_000100_001100_000000_00 |61 50 4 12 | 186 | //! 51.12.109.0/24 001100_110000_110001_101101_000000_00 |12 48 49 45 | 187 | //! 77.18.0.0/16 010011_010001_001000_000000_000000_00 |19 17 8 | 188 | //! 170.1.14.3/32 101010_100000_000100_001110_000000_11 |42 32 4 14 0 3| 189 | //! 0.0.0.0.0/0 000000_000000_000000_000000_000000_00 | | 190 | //! ``` 191 | //! 192 | //! From this table we can see that the first column corresponds directly to the 193 | //! bitvec structure of the root node. We've already covered the single leaf 194 | //! child node for the root. What remains are 5 child internal nodes stemming 195 | //! from bitvec positions 0, 61, 12, 19 and 42. These yield the following 196 | //! internal child nodes. 197 | //! 198 | //! ```text 199 | //! 1 5 4 1 3 200 | //! 6 0 8 7 2 201 | //! +-------+ +-------+ +-------+ +-------+ +-------+ 202 | //! 0: |..|1|..| 61: |..|1|..| 12: |..|1|..| 19: |..|1|..| 42: |..|1|..| 203 | //! +-------+ +-------+ +-------+ +-------+ +-------+ 204 | //! ``` 205 | //! 206 | //! Taking these internal child nodes in turn. The following is for the first 207 | //! routing table entry. 208 | //! 209 | //! ```text 210 | //! 1 211 | //! 6 212 | //! +-------+ +---------------+ 213 | //! 0: |..|0|..| ,--> | 1.254.254.254 | 214 | //! +-------+ | +---------------+ 215 | //! `-------' 216 | //! ``` 217 | //! 218 | //! At this point we have consumed 12 bits of the input IP address. This is 219 | //! beyond the 8 bit prefix so we need a leaf entry for that prefix. That leaf 220 | //! node is shown to the right of the internal node in the depiction above. 221 | //! 222 | //! The next internal node represents a pair of prefixes in the routing table, 223 | //! `247.33.0.0/16` and `247.33.12.0/24`. We do not have enough bits for a leaf 224 | //! node on either, so we have another internal node 225 | //! 226 | //! ```text 227 | //! 5 228 | //! 0 4 229 | //! +-------+ +-------+ 230 | //! 61: |..|1|..| ,-->|..|1|..| 231 | //! +-------+ | +-------+ 232 | //! `-------' 233 | //!``` 234 | //! At the next internal node 235 | //! 236 | //!```text 237 | //! 1 238 | //! 2 +-------------+ 239 | //! ,---------->| 247.33.12.1 | 240 | //! +-------+ +-------------+ 241 | //! 4: |..|0|..| 242 | //! +-------+ +------------+ 243 | //! `----`------->| 247.33.0.1 | 244 | //! +------------+ 245 | //! ``` 246 | //! 247 | //! For the entry `51.12.109.0/24` we have: 248 | //! 249 | //! ```text 250 | //! 4 4 251 | //! 8 9 252 | //! +-------+ +-------+ 253 | //! 12: |..|1|..| ,-->|..|1|..| 254 | //! +-------+ | +-------+ 255 | //! `-------' 256 | //! ``` 257 | //! 258 | //! For the entry `77.18.0.0/16` we have: 259 | //! 260 | //! ```text 261 | //! 1 262 | //! 7 8 263 | //! +-------+ +-------+ 264 | //! 19: |..|1|..| ,-->|..|1|..| 265 | //! +-------+ | +-------+ 266 | //! `-------' 267 | //! ``` 268 | //! 269 | //! For the entry `170.1.14.3/32` we have: 270 | //! 271 | //! ```text 272 | //! 3 273 | //! 2 4 274 | //! +-------+ +-------+ 275 | //! 42: |..|1|..| ,-->|..|1|..| 276 | //! +-------+ | +-------+ 277 | //! `-------' 278 | //! ``` 279 | //! 280 | 281 | extern crate alloc; 282 | use alloc::collections::BTreeMap; 283 | use alloc::vec; 284 | use alloc::vec::Vec; 285 | 286 | /// The poptrie data structure. 287 | #[derive(Debug)] 288 | pub struct Poptrie { 289 | /// An array of interior nodes. 290 | pub interior: Vec, 291 | 292 | /// An array of leaf nodes. 293 | pub leaf: Vec>, 294 | 295 | /// A default route if any. 296 | pub default: Option>, 297 | } 298 | 299 | // NOTE #[derive(Default)] see: 300 | // broken https://github.com/rust-lang/rust/issues/26925 301 | impl Default for Poptrie { 302 | fn default() -> Self { 303 | Self { 304 | interior: Vec::new(), 305 | leaf: Vec::new(), 306 | default: None, 307 | } 308 | } 309 | } 310 | 311 | /// An interior poptrie node. 312 | pub struct Interior { 313 | /// The bit vector that describes child internal nodes. 314 | pub iv: u64, 315 | 316 | /// The bit vector that describes child leaf nodes. 317 | pub lv: u64, 318 | 319 | /// An offset into Poptrie::interior where the child interior nodes of this 320 | /// node begin. 321 | pub interior_offset: u64, 322 | 323 | /// An offset into Poptrie::interior where the child leaf nodes of this node 324 | /// begin. 325 | pub leaf_offset: u64, 326 | } 327 | 328 | impl core::fmt::Debug for Interior { 329 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 330 | let mut islots = Vec::new(); 331 | let mut lslots = Vec::new(); 332 | for i in 0..63 { 333 | if (self.iv & (1 << i)) != 0 { 334 | islots.push(i); 335 | } 336 | } 337 | for i in 0..63 { 338 | if (self.lv & (1 << i)) != 0 { 339 | lslots.push(i); 340 | } 341 | } 342 | f.debug_struct("Interior") 343 | .field("iv", &islots) 344 | .field("lv", &lslots) 345 | .field("interior_offset", &self.interior_offset) 346 | .field("leaf_offset", &self.leaf_offset) 347 | .finish() 348 | } 349 | } 350 | 351 | /// A leaf poptrie node. 352 | #[derive(Debug)] 353 | pub struct Leaf { 354 | /// The data associated with this node. 355 | pub data: T, 356 | } 357 | 358 | #[derive(Clone)] 359 | pub struct Ipv4RoutingTable(pub BTreeMap<(u32, u8), T>); 360 | 361 | // NOTE #[derive(Default)] see: 362 | // broken https://github.com/rust-lang/rust/issues/26925 363 | impl Default for Ipv4RoutingTable { 364 | fn default() -> Self { 365 | Self(BTreeMap::new()) 366 | } 367 | } 368 | 369 | impl core::ops::Deref for Ipv4RoutingTable { 370 | type Target = BTreeMap<(u32, u8), T>; 371 | 372 | fn deref(&self) -> &Self::Target { 373 | &self.0 374 | } 375 | } 376 | 377 | impl core::ops::DerefMut for Ipv4RoutingTable { 378 | fn deref_mut(&mut self) -> &mut Self::Target { 379 | &mut self.0 380 | } 381 | } 382 | 383 | impl Ipv4RoutingTable { 384 | pub fn add(&mut self, dst: [u8; 4], len: u8, nexthop: T) { 385 | self.0.insert((u32::from_be_bytes(dst), len), nexthop); 386 | } 387 | } 388 | 389 | impl From> for Poptrie { 390 | fn from(tree: Ipv4RoutingTable) -> Self { 391 | let mut s = Self::default(); 392 | s.construct4(tree); 393 | s 394 | } 395 | } 396 | 397 | #[derive(Clone)] 398 | pub struct Ipv6RoutingTable(pub BTreeMap<(u128, u8), T>); 399 | 400 | // NOTE #[derive(Default)] see: 401 | // broken https://github.com/rust-lang/rust/issues/26925 402 | impl Default for Ipv6RoutingTable { 403 | fn default() -> Self { 404 | Self(BTreeMap::new()) 405 | } 406 | } 407 | 408 | impl core::ops::Deref for Ipv6RoutingTable { 409 | type Target = BTreeMap<(u128, u8), T>; 410 | 411 | fn deref(&self) -> &Self::Target { 412 | &self.0 413 | } 414 | } 415 | 416 | impl core::ops::DerefMut for Ipv6RoutingTable { 417 | fn deref_mut(&mut self) -> &mut Self::Target { 418 | &mut self.0 419 | } 420 | } 421 | 422 | impl Ipv6RoutingTable { 423 | pub fn add(&mut self, dst: [u8; 16], len: u8, nexthop: T) { 424 | self.0.insert((u128::from_be_bytes(dst), len), nexthop); 425 | } 426 | } 427 | 428 | impl From> for Poptrie { 429 | fn from(tree: Ipv6RoutingTable) -> Self { 430 | let mut s = Self::default(); 431 | s.construct6(tree); 432 | s 433 | } 434 | } 435 | 436 | macro_rules! extract { 437 | ($width:expr, $offset:expr, $v:expr, $bits:expr) => {{ 438 | let shift = $bits.saturating_sub($width * ($offset + 1)); 439 | let mask = 0b111111 << shift; 440 | let res = ($v & mask) >> shift; 441 | res as u8 442 | }}; 443 | } 444 | 445 | pub fn extract_32(width: u8, offset: u8, v: u32) -> u8 { 446 | extract!(width, offset, v, 32u8) 447 | } 448 | 449 | pub fn extract_128(width: u8, offset: u8, v: u32) -> u8 { 450 | extract!(width, offset, v, 128u8) 451 | } 452 | 453 | //TODO having this as a macro is terrible for debugging as we get no backtrace 454 | macro_rules! matcher { 455 | ($self:ident, $addr:tt, $bits:expr) => {{ 456 | let mut i = 0u64; 457 | let mut v = $self.interior.get(i as usize)?.iv; 458 | let mut offset = 0; 459 | let mut n = extract!(6, offset, $addr, $bits); 460 | 461 | let mut result = None; 462 | 463 | #[cfg(test)] 464 | println!("n={n}"); 465 | 466 | #[cfg(test)] 467 | println!("{:#?}", $self.interior.get(i as usize)?); 468 | 469 | while (v & (1 << n)) != 0 { 470 | let base = $self.interior.get(i as usize)?.interior_offset; 471 | let arg = v & ((2 << n) - 1); 472 | let bc = arg.count_ones() as u64; 473 | i = base + bc - 1; 474 | v = $self.interior.get(i as usize)?.iv; 475 | 476 | offset += 1; 477 | n = extract!(6, offset, $addr, $bits); 478 | 479 | #[cfg(test)] 480 | println!("n={n}"); 481 | 482 | #[cfg(test)] 483 | println!("{:#?}", $self.interior.get(i as usize)?); 484 | 485 | // check for stash any potentially suboptimal matches, longer 486 | // prefix matches will overwrite these 487 | let base = $self.interior.get(i as usize)?.leaf_offset; 488 | let v = $self.interior.get(i as usize)?.lv; 489 | if (v & (1 << n)) != 0 { 490 | let i = base - 1; 491 | result = Some($self.leaf.get(i as usize)?.data) 492 | } 493 | } 494 | 495 | let base = $self.interior.get(i as usize)?.leaf_offset; 496 | let v = $self.interior.get(i as usize)?.lv; 497 | if (v & (1 << n)) != 0 { 498 | i = base - 1; 499 | result = Some($self.leaf.get(i as usize)?.data) 500 | } 501 | 502 | result 503 | }}; 504 | } 505 | 506 | //TODO having this as a macro is terrible for debugging as we get no backtrace 507 | macro_rules! construct { 508 | ($self:ident, $tree:ident, $bits:expr, $depth:expr, $rt:ident<$t:tt>) => {{ 509 | let mut forest = vec![(0, $tree)]; 510 | 511 | let mut ioff = 1; 512 | for depth in 0..$depth { 513 | let mut subforest = Vec::<(u8, $rt<$t>)>::new(); 514 | let mut children = 0; 515 | let mut siblings = 0; 516 | for (_, $tree) in &forest { 517 | let mut iv = 0u64; 518 | let mut lv = 0u64; 519 | 520 | let mut subsubforest = Vec::<(u8, $rt<$t>)>::new(); 521 | for (r, e) in &$tree.0 { 522 | // default route case 523 | if r.1 == 0 { 524 | $self.default = Some(Leaf { data: *e }); 525 | continue; 526 | } 527 | let k = extract!(6, depth, r.0, $bits); 528 | let consumed = core::cmp::min((depth + 1) * 6, $bits); 529 | if r.1 <= consumed { 530 | if ((1 << k) & iv) == 0 { 531 | lv |= 1 << k; 532 | $self.leaf.push(Leaf { data: *e }); 533 | } 534 | 535 | // If the prefix of the router entry is less than but not equal 536 | // to the consumed number of bits, we need to add those bits to 537 | // the bitvec. 538 | if r.1 != consumed { 539 | // Shift by the extra bits and add to the bitvec for this 540 | // internal node. 541 | let extra = 1 << (consumed - r.1); 542 | for i in 1..(extra) { 543 | lv |= 1 << (k + i); 544 | $self.leaf.push(Leaf { data: *e }); 545 | } 546 | } 547 | continue; 548 | } 549 | iv |= 1 << k; 550 | match subsubforest.iter_mut().find(|x| x.0 == k) { 551 | Some(ref mut entry) => { 552 | entry.1.insert(*r, *e); 553 | } 554 | None => { 555 | let mut tbl = $rt::<$t>::default(); 556 | tbl.insert(*r, *e); 557 | subsubforest.push((k, tbl)); 558 | if iv > 0 { 559 | children += 1; 560 | } 561 | } 562 | } 563 | } 564 | 565 | if iv > 0 || lv > 0 { 566 | $self.interior.push(Interior { 567 | iv, 568 | lv, 569 | interior_offset: if iv > 0 { 570 | ioff + siblings 571 | } else { 572 | 0 573 | }, 574 | leaf_offset: $self.leaf.len() as u64, 575 | }); 576 | if iv > 0 { 577 | siblings += 1; 578 | } 579 | } 580 | subforest.extend_from_slice(&subsubforest); 581 | } 582 | ioff += children; 583 | forest = subforest; 584 | } 585 | }} 586 | } 587 | 588 | impl Poptrie { 589 | pub fn construct4(&mut self, tree: Ipv4RoutingTable) { 590 | construct!(self, tree, 32u8, 6, Ipv4RoutingTable); 591 | } 592 | 593 | pub fn construct6(&mut self, tree: Ipv6RoutingTable) { 594 | construct!(self, tree, 128u8, 22, Ipv6RoutingTable); 595 | } 596 | 597 | pub fn match_v4(&self, addr: u32) -> Option { 598 | self.do_match_v4(addr) 599 | .or(self.default.as_ref().map(|x| x.data)) 600 | } 601 | 602 | pub fn match_v6(&self, addr: u128) -> Option { 603 | self.do_match_v6(addr) 604 | .or(self.default.as_ref().map(|x| x.data)) 605 | } 606 | 607 | pub fn do_match_v4(&self, addr: u32) -> Option { 608 | matcher!(self, addr, 32u8) 609 | } 610 | 611 | pub fn do_match_v6(&self, addr: u128) -> Option { 612 | matcher!(self, addr, 128u8) 613 | } 614 | } 615 | 616 | #[cfg(test)] 617 | #[macro_use] 618 | extern crate std; 619 | 620 | #[cfg(test)] 621 | mod test { 622 | use super::*; 623 | 624 | #[derive(Default, Copy, Clone, PartialEq)] 625 | struct Ipv4(u32); 626 | impl core::fmt::Debug for Ipv4 { 627 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 628 | let b = self.0.to_be_bytes(); 629 | write!(f, "{}.{}.{}.{}", b[0], b[1], b[2], b[3]) 630 | } 631 | } 632 | 633 | impl Ipv4 { 634 | fn new(v: [u8; 4]) -> Self { 635 | Self(u32::from_be_bytes(v)) 636 | } 637 | } 638 | 639 | #[derive(Default, Copy, Clone, PartialEq)] 640 | struct Ipv6(u128); 641 | impl core::fmt::Debug for Ipv6 { 642 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 643 | let b = self.0.to_be_bytes(); 644 | write!( 645 | f, 646 | "{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}", 647 | b[0], b[1], b[2], b[3], 648 | b[4], b[5], b[6], b[7], 649 | b[8], b[9], b[10], b[11], 650 | b[12], b[13], b[14], b[15], 651 | ) 652 | } 653 | } 654 | 655 | impl Ipv6 { 656 | fn new(v: [u8; 16]) -> Self { 657 | Self(u128::from_be_bytes(v)) 658 | } 659 | } 660 | 661 | impl std::str::FromStr for Ipv6 { 662 | type Err = std::net::AddrParseError; 663 | fn from_str(s: &str) -> std::result::Result { 664 | let addr: std::net::Ipv6Addr = s.parse()?; 665 | Ok(Self::new(addr.octets())) 666 | } 667 | } 668 | 669 | #[test] 670 | fn test_extract32() { 671 | // Verify documentation examples 672 | 673 | // 1.0.0.0 674 | let v = u32::from_be_bytes([1, 0, 0, 0]); 675 | let x = extract_32_all(v); 676 | assert_eq!(x, [0, 16, 0, 0, 0, 0]); 677 | 678 | // 247.33.0.0 679 | let v = u32::from_be_bytes([247, 33, 0, 0]); 680 | let x = extract_32_all(v); 681 | assert_eq!(x, [61, 50, 4, 0, 0, 0]); 682 | 683 | // 247.33.12.0 684 | let v = u32::from_be_bytes([247, 33, 12, 0]); 685 | let x = extract_32_all(v); 686 | assert_eq!(x, [61, 50, 4, 12, 0, 0]); 687 | 688 | // 51.12.109.0 689 | let v = u32::from_be_bytes([51, 12, 109, 0]); 690 | let x = extract_32_all(v); 691 | assert_eq!(x, [12, 48, 49, 45, 0, 0]); 692 | 693 | // 77.18.0.0 694 | let v = u32::from_be_bytes([77, 18, 0, 0]); 695 | let x = extract_32_all(v); 696 | assert_eq!(x, [19, 17, 8, 0, 0, 0]); 697 | 698 | // 170.1.14.3 699 | let v = u32::from_be_bytes([170, 1, 14, 3]); 700 | let x = extract_32_all(v); 701 | assert_eq!(x, [42, 32, 4, 14, 0, 3]); 702 | 703 | // 0.0.0.0 704 | let v = u32::from_be_bytes([0, 0, 0, 0]); 705 | let x = extract_32_all(v); 706 | assert_eq!(x, [0, 0, 0, 0, 0, 0]); 707 | } 708 | 709 | #[test] 710 | fn test_construct_rec() { 711 | let tbl = test_routing_table_with_default_route_v4(); 712 | let pt = Poptrie::::from(tbl); 713 | 714 | #[allow(clippy::identity_op)] 715 | let expected_root_bitvec = 716 | 0u64 | 1 << 0 | 1 << 61 | 1 << 61 | 1 << 12 | 1 << 19 | 1 << 42; 717 | 718 | assert_eq!(expected_root_bitvec, pt.interior[0].iv); 719 | assert_eq!(pt.leaf.len(), 27); 720 | 721 | println!("{:#?}", pt); 722 | } 723 | 724 | #[test] 725 | fn test_match_v4() { 726 | let tbl = test_routing_table_v4(); 727 | let pt = Poptrie::::from(tbl); 728 | 729 | // Test hits 730 | let addr = Ipv4::new([1, 7, 0, 1]); 731 | let m = pt.match_v4(addr.0); 732 | assert_eq!(m, Some(Ipv4::new([1, 254, 254, 254]))); 733 | 734 | let addr = Ipv4::new([247, 33, 0, 1]); 735 | let m = pt.match_v4(addr.0); 736 | assert_eq!(m, Some(Ipv4::new([247, 33, 0, 1]))); 737 | 738 | let addr = Ipv4::new([247, 33, 12, 1]); 739 | let m = pt.match_v4(addr.0); 740 | assert_eq!(m, Some(Ipv4::new([247, 33, 12, 1]))); 741 | 742 | let addr = Ipv4::new([51, 12, 109, 1]); 743 | let m = pt.match_v4(addr.0); 744 | assert_eq!(m, Some(Ipv4::new([51, 12, 109, 10]))); 745 | 746 | let addr = Ipv4::new([77, 18, 4, 7]); 747 | let m = pt.match_v4(addr.0); 748 | assert_eq!(m, Some(Ipv4::new([77, 18, 10, 1]))); 749 | 750 | let addr = Ipv4::new([170, 1, 14, 3]); 751 | let m = pt.match_v4(addr.0); 752 | assert_eq!(m, Some(Ipv4::new([1, 7, 0, 1]))); 753 | 754 | // Test default route 755 | let addr = Ipv4::new([4, 7, 0, 1]); 756 | let m = pt.match_v4(addr.0); 757 | assert_eq!(m, None); 758 | 759 | let tbl = test_routing_table_with_default_route_v4(); 760 | let pt = Poptrie::::from(tbl); 761 | 762 | // Test default route 763 | let addr = Ipv4::new([4, 7, 0, 1]); 764 | let m = pt.match_v4(addr.0); 765 | assert_eq!(m, Some(Ipv4::new([1, 2, 3, 4]))); 766 | } 767 | 768 | #[test] 769 | fn test_match_v6() { 770 | let tbl = test_routing_table_v6(); 771 | let pt = Poptrie::::from(tbl); 772 | 773 | // Test hits 774 | let addr: Ipv6 = "1:7:0::1".parse().unwrap(); 775 | let m = pt.match_v6(addr.0); 776 | let gw: Ipv6 = "1::ffff:ffff:ffff".parse().unwrap(); 777 | assert_eq!(m, Some(gw)); 778 | 779 | let addr: Ipv6 = "247:33::1".parse().unwrap(); 780 | let m = pt.match_v6(addr.0); 781 | let gw: Ipv6 = "247:33::1".parse().unwrap(); 782 | assert_eq!(m, Some(gw)); 783 | 784 | let addr: Ipv6 = "247:33:12::1".parse().unwrap(); 785 | let m = pt.match_v6(addr.0); 786 | let gw: Ipv6 = "247:33:12::1".parse().unwrap(); 787 | assert_eq!(m, Some(gw)); 788 | 789 | let addr: Ipv6 = "51:12:109::1".parse().unwrap(); 790 | let m = pt.match_v6(addr.0); 791 | let gw: Ipv6 = "51:12:109::10".parse().unwrap(); 792 | assert_eq!(m, Some(gw)); 793 | 794 | let addr: Ipv6 = "77:18:4::7".parse().unwrap(); 795 | let m = pt.match_v6(addr.0); 796 | let gw: Ipv6 = "77:18:10::1".parse().unwrap(); 797 | assert_eq!(m, Some(gw)); 798 | 799 | let addr: Ipv6 = "170:1:14::3".parse().unwrap(); 800 | let m = pt.match_v6(addr.0); 801 | let gw: Ipv6 = "1:7:0::1".parse().unwrap(); 802 | assert_eq!(m, Some(gw)); 803 | 804 | // Test default route 805 | let addr: Ipv6 = "4:7:0::1".parse().unwrap(); 806 | let m = pt.match_v6(addr.0); 807 | assert_eq!(m, None); 808 | 809 | let tbl = test_routing_table_with_default_route_v6(); 810 | let pt = Poptrie::::from(tbl); 811 | 812 | let addr: Ipv6 = "4:7:0::1".parse().unwrap(); 813 | let m = pt.match_v6(addr.0); 814 | let gw: Ipv6 = "1:2:3::4".parse().unwrap(); 815 | assert_eq!(m, Some(gw)); 816 | } 817 | 818 | fn test_routing_table_v4() -> Ipv4RoutingTable { 819 | let mut tbl = Ipv4RoutingTable::::default(); 820 | tbl.add([1, 0, 0, 0], 8, Ipv4::new([1, 254, 254, 254])); 821 | tbl.add([247, 33, 0, 0], 16, Ipv4::new([247, 33, 0, 1])); 822 | tbl.add([247, 33, 12, 0], 24, Ipv4::new([247, 33, 12, 1])); 823 | tbl.add([51, 12, 109, 0], 24, Ipv4::new([51, 12, 109, 10])); 824 | tbl.add([77, 18, 0, 0], 16, Ipv4::new([77, 18, 10, 1])); 825 | tbl.add([170, 1, 14, 3], 32, Ipv4::new([1, 7, 0, 1])); 826 | tbl 827 | } 828 | 829 | fn test_routing_table_with_default_route_v4() -> Ipv4RoutingTable { 830 | let mut tbl = test_routing_table_v4(); 831 | tbl.add([0, 0, 0, 0], 0, Ipv4::new([1, 2, 3, 4])); 832 | tbl 833 | } 834 | 835 | fn test_routing_table_v6() -> Ipv6RoutingTable { 836 | let mut tbl = Ipv6RoutingTable::::default(); 837 | 838 | let rt: std::net::Ipv6Addr = "1::".parse().unwrap(); 839 | let gw: Ipv6 = "1::ffff:ffff:ffff".parse().unwrap(); 840 | tbl.add(rt.octets(), 16, gw); 841 | 842 | let rt: std::net::Ipv6Addr = "247:33::".parse().unwrap(); 843 | let gw: Ipv6 = "247:33::1".parse().unwrap(); 844 | tbl.add(rt.octets(), 32, gw); 845 | 846 | let rt: std::net::Ipv6Addr = "247:33:12::".parse().unwrap(); 847 | let gw: Ipv6 = "247:33:12::1".parse().unwrap(); 848 | tbl.add(rt.octets(), 48, gw); 849 | 850 | let rt: std::net::Ipv6Addr = "51:12:109::".parse().unwrap(); 851 | let gw: Ipv6 = "51:12:109::10".parse().unwrap(); 852 | tbl.add(rt.octets(), 48, gw); 853 | 854 | let rt: std::net::Ipv6Addr = "77:18::".parse().unwrap(); 855 | let gw: Ipv6 = "77:18:10::1".parse().unwrap(); 856 | tbl.add(rt.octets(), 32, gw); 857 | 858 | let rt: std::net::Ipv6Addr = "170:1:14::3".parse().unwrap(); 859 | let gw: Ipv6 = "1:7:0::1".parse().unwrap(); 860 | tbl.add(rt.octets(), 128, gw); 861 | 862 | tbl 863 | } 864 | 865 | fn test_routing_table_with_default_route_v6() -> Ipv6RoutingTable { 866 | let mut tbl = test_routing_table_v6(); 867 | 868 | let rt: std::net::Ipv6Addr = "::".parse().unwrap(); 869 | let gw: Ipv6 = "1:2:3::4".parse().unwrap(); 870 | tbl.add(rt.octets(), 0, gw); 871 | 872 | tbl 873 | } 874 | 875 | fn extract_32_all(v: u32) -> [u8; 6] { 876 | [ 877 | extract_32(6, 0, v), 878 | extract_32(6, 1, v), 879 | extract_32(6, 2, v), 880 | extract_32(6, 3, v), 881 | extract_32(6, 4, v), 882 | extract_32(6, 5, v), 883 | ] 884 | } 885 | } 886 | --------------------------------------------------------------------------------