├── .gitignore ├── Cargo.toml ├── Changelog ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bench-ocaml ├── .merlin ├── build.sh └── test.ml ├── bench ├── Cargo.toml ├── bench.py ├── charts │ ├── ibm_power9_02CY089 │ │ ├── data.json │ │ ├── str_get.png │ │ ├── str_get_parallel.png │ │ ├── str_insert.png │ │ ├── str_insert_many.png │ │ ├── str_insert_many_par.png │ │ ├── str_remove.png │ │ ├── usize_get.png │ │ ├── usize_get_parallel.png │ │ ├── usize_insert.png │ │ ├── usize_insert_many.png │ │ ├── usize_insert_many_par.png │ │ └── usize_remove.png │ ├── intel_corei7-7820X-C128 │ │ └── data.json │ ├── intel_corei7-7820X-C256 │ │ └── data.json │ ├── intel_corei7-7820X-C512 │ │ └── data.json │ ├── intel_corei7-7820X-C64 │ │ └── data.json │ ├── intel_corei7-7820X │ │ ├── data.json │ │ ├── str_get.png │ │ ├── str_get_parallel.png │ │ ├── str_insert.png │ │ ├── str_insert_many.png │ │ ├── str_insert_many_par.png │ │ ├── str_remove.png │ │ ├── usize_get.png │ │ ├── usize_get_parallel.png │ │ ├── usize_insert.png │ │ ├── usize_insert_many.png │ │ ├── usize_insert_many_par.png │ │ └── usize_remove.png │ ├── intel_corei7-8550U │ │ ├── data.json │ │ ├── str_get.png │ │ ├── str_get_parallel.png │ │ ├── str_insert.png │ │ ├── str_insert_many.png │ │ ├── str_insert_many_par.png │ │ ├── str_remove.png │ │ ├── usize_get.png │ │ ├── usize_get_parallel.png │ │ ├── usize_insert.png │ │ ├── usize_insert_many.png │ │ ├── usize_insert_many_par.png │ │ └── usize_remove.png │ ├── intel_corei7-8550U_arrayvec │ │ ├── data.json │ │ ├── str_get.png │ │ ├── str_get_parallel.png │ │ ├── str_insert.png │ │ ├── str_insert_many.png │ │ ├── str_insert_many_par.png │ │ ├── str_remove.png │ │ ├── usize_get.png │ │ ├── usize_get_parallel.png │ │ ├── usize_insert.png │ │ ├── usize_insert_many.png │ │ ├── usize_insert_many_par.png │ │ └── usize_remove.png │ └── intel_corei7-8550U_arrayvec_compact │ │ ├── data.json │ │ ├── str_get.png │ │ ├── str_get_parallel.png │ │ ├── str_insert.png │ │ ├── str_insert_many.png │ │ ├── str_insert_many_par.png │ │ ├── str_remove.png │ │ ├── usize_get.png │ │ ├── usize_get_parallel.png │ │ ├── usize_insert.png │ │ ├── usize_insert_many.png │ │ ├── usize_insert_many_par.png │ │ └── usize_remove.png ├── compare.py └── src │ ├── main.rs │ └── utils.rs ├── rustfmt.toml └── src ├── avl.rs ├── chunk.rs ├── lib.rs ├── map.rs ├── set.rs └── tests.rs /.gitignore: -------------------------------------------------------------------------------- 1 | **/bench-ocaml/test 2 | **/target/ 3 | **/*.rs.bk 4 | Cargo.lock 5 | *.a 6 | *.aux 7 | *.bc 8 | *.boot 9 | *.bz2 10 | *.cmi 11 | *.cmo 12 | *.cmx 13 | *.cp 14 | *.cps 15 | *.d 16 | *.dSYM 17 | *.def 18 | *.diff 19 | *.dll 20 | *.dylib 21 | *.elc 22 | *.epub 23 | *.exe 24 | *.fn 25 | *.kdev4 26 | *.ky 27 | *.ll 28 | *.llvm 29 | *.log 30 | *.o 31 | *.orig 32 | *.out 33 | *.patch 34 | *.pdb 35 | *.pdf 36 | *.pg 37 | *.pot 38 | *.pyc 39 | *.rej 40 | *.rlib 41 | *.rustc 42 | *.so 43 | *.swo 44 | *.swp 45 | *.tmp 46 | *.toc 47 | *.tp 48 | *.vr 49 | *.x86 50 | *~ 51 | .#* 52 | .DS_Store 53 | .cproject 54 | .hg/ 55 | .hgignore 56 | .idea 57 | *.iml 58 | __pycache__/ 59 | *.py[cod] 60 | *$py.class 61 | .project 62 | .settings/ 63 | .valgrindrc 64 | .vscode/ 65 | /*-*-*-*/ 66 | /*-*-*/ 67 | /Makefile 68 | /build 69 | /config.toml 70 | /dist/ 71 | /dl/ 72 | /inst/ 73 | /llvm/ 74 | /mingw-build/ 75 | /nd/ 76 | /obj/ 77 | /rt/ 78 | /rustllvm/ 79 | /src/libstd_unicode/DerivedCoreProperties.txt 80 | /src/libstd_unicode/DerivedNormalizationProps.txt 81 | /src/libstd_unicode/PropList.txt 82 | /src/libstd_unicode/ReadMe.txt 83 | /src/libstd_unicode/Scripts.txt 84 | /src/libstd_unicode/SpecialCasing.txt 85 | /src/libstd_unicode/UnicodeData.txt 86 | /stage[0-9]+/ 87 | /target 88 | /test/ 89 | /tmp/ 90 | TAGS 91 | TAGS.emacs 92 | TAGS.vi 93 | \#* 94 | \#*\# 95 | config.mk 96 | config.stamp 97 | keywords.md 98 | lexer.ml 99 | src/etc/dl 100 | src/librustc_llvm/llvmdeps.rs 101 | tmp.*.rs 102 | version.md 103 | version.ml 104 | version.texi 105 | .cargo 106 | !src/vendor/** 107 | /src/target/ 108 | 109 | no_llvm_build 110 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "immutable-chunkmap" 3 | version = "2.0.6" 4 | authors = ["Eric Stokes "] 5 | publish = true 6 | description = "A fast immutable map and set with batch insert and update methods, COW operations, and big O efficient implementations of set and merge operations" 7 | categories = ["data-structures", "no-std"] 8 | keywords = ["map", "set", "immutable", "persistent", "functional"] 9 | license = "Apache-2.0 OR MIT" 10 | documentation = "https://docs.rs/immutable-chunkmap" 11 | repository = "https://github.com/estokes/immutable-chunkmap" 12 | edition = "2018" 13 | 14 | [features] 15 | default = [] 16 | serde = ["dep:serde"] 17 | rayon = ["dep:rayon"] 18 | 19 | [dependencies] 20 | arrayvec = { version = "0.7", default-features = false } 21 | serde = { version = "1", default-features = false, features = ["alloc"], optional = true } 22 | rayon = { version = "1", optional = true } 23 | 24 | [dev-dependencies] 25 | rayon = "1" 26 | serde = "1" 27 | serde_json = "1" 28 | paste = "1" 29 | rand = "0.8" 30 | hashbrown = "0.15" 31 | -------------------------------------------------------------------------------- /Changelog: -------------------------------------------------------------------------------- 1 | 2.0.6 2 | 3 | * merge #10, no_std support (alloc required) 4 | 5 | 2.0.5 6 | 7 | * merge #8 hand coded packing of height/size to remove the dependency 8 | on packed struct 9 | 10 | * fix a few bugs in the model checking COW tests 11 | 12 | 2.0.4 13 | 14 | * remove redundant type parameter from iter_mut_cow 15 | 16 | 2.0.3 17 | 18 | * implement iter_mut_cow, range_mut_cow, for copy on write iterators 19 | 20 | 2.0.2 21 | 22 | * implement get_or_insert_cow and get_or_default_cow 23 | 24 | 2.0.1 25 | 26 | * implement get_mut_cow to improve the ergonomics of using nested 27 | maps with COW operations 28 | 29 | 2.0.0 30 | 31 | * fix the range api to match the standard library. Sorry about the 32 | previous two releases, it's actually quite a subtle api and I 33 | consistently got it wrong. I also got semantic versioning wrong, and 34 | I'm really sorry about that, I hope nothing broke annoyingly for 35 | anyone (aside from for me :)) 36 | 37 | 1.1.1 38 | * fix ?Sized on range 39 | 40 | 1.1.0 41 | * fix the arguments to range to have the correct borrow type 42 | 43 | 1.0.5 44 | * add remove_many, a small wrapper around update_many 45 | * fix a bug in update_many where trying to remove elements that don't 46 | exist in the map could cause a panic. Add a test for this case. 47 | 48 | 1.0.4 49 | * add optional rayon support for map and set 50 | 51 | 1.0.3 52 | * add optional serde support for map and set 53 | 54 | 1.0.2 55 | * stop depending on serde by default 56 | 57 | 1.0.1 58 | * replace vec chunks with arrayvec chunks to eliminate an indirection 59 | * implement tree compaction to keep inner chunks from getting too sparse 60 | 61 | 1.0.0 "the cake is not a lie" 62 | * Add copy on write mutable operations. They are 10x faster than plain 63 | insert/remove, and bring update performance within an 2-3x of 64 | BTreeMap (with ArcStr keys). 65 | 66 | * Chunk size is now configurable with a const generic parameter. Three 67 | different sizes are exposed as default type aliases. 68 | 69 | * bump dependencies, update readme, and refresh the benchmarks 70 | 71 | * feels like 1.0 to me! 72 | 73 | 0.5.9 74 | * add weak references to maps and sets as well as methods to get the 75 | strong and weak count of map/set references. 76 | 77 | 0.5.8 78 | * further 20% performance improvement on batch update operations. 79 | 80 | 0.5.7 81 | * improve performance of batch update operations on unsorted data by a 82 | large amount (7x on trees of size 10million and chunks of size 100k). 83 | 0.5.6 84 | 85 | * packed the height and length together, which reduced the size of 86 | nodes by 1 word. That reduction gets us a 1-2% improvement in 87 | lookup times (more benefit for larger trees). Tree length is now 88 | limited to 2^56 elements instead of usize::MAX elements. 89 | 90 | * made the tests run faster by wrapping strings in Arcs, which is 91 | closer to how you'd use them in a real program anyway. 92 | 93 | 0.5.5 94 | * small performance optimizations update operations 95 | 96 | 0.5.4 97 | * Edition 2018 98 | 99 | 0.5.3 100 | * implement Set::diff, and Map::diff, O(log(N) + M) where M is the 101 | number of intersecting chunks. Now all the fundamental set 102 | operations are implemented. 103 | * rename Map::merge to Map::union. Sorry for the tiny break in 104 | semantic versioning, but given it was just released I don't 105 | think it's a huge problem to change it now. 106 | 107 | 0.5.2 108 | * implement Set::intersect, and Map::intersect, O(log(N) + M) 109 | where M is the number of intersecting chunks. 110 | 111 | 0.5.1 112 | * implement Set::union, and Map::merge, O(log(N) + M) where M is the 113 | number of intersecting chunks and N is the size of the largest 114 | tree. Should always be as fast as update_many from the other map's 115 | iterator, a lot faster in the case of a small intersection. 116 | * remove my silly &mut F requirement for closure arguments to 117 | functions in the public interface. Sorry I'm still learning rust, I 118 | didn't know FnMut was also implemented by a &mut. 119 | 120 | 0.5.0 121 | * implement map get_key, get_full 122 | * implement set update_many 123 | * fix some incorrect documentation 124 | * BREAKING change map and set update functions so they are able to 125 | work with borrowed forms of the key 126 | 127 | 0.4.1 128 | * implement get in the set module 129 | * properly implement Ord, PartialOrd, Eq, PartialEq, Hash, and Debug 130 | 131 | 0.4.0 132 | * add a set module 133 | * remove the rc and arc modules. There is no observable performance 134 | difference between rc and arc, so just use arc everywhere. This is 135 | especially relevant because all the practical applications of this 136 | library than I know about require using Arc. 137 | * BREAKING: fix return type of insert and remove to match BTreeMap 138 | 139 | 0.3.2 140 | * fix a small performance regression in update_many caused by my last 141 | change 142 | 143 | 0.3.1 144 | * fix a bug in update_many that could rarely cause a removed item not 145 | to be removed 146 | 147 | 0.3.0(yanked) 148 | * BREAKING: change the name of insert_sorted to insert_many 149 | * add update, and update_many 150 | * insert 14% performance improvement 151 | * insert_many 42% performance improvement on unsorted data, now faster 152 | than insert on random data 153 | 154 | 0.2.1 155 | * BREAKING: change signature of insert to match BTreeMap as closely as 156 | possible. Sorry I was new to rust when I first wrote this module :-( 157 | 158 | 0.2.0 159 | * iteration runs in constant space 160 | * Implement collection range api 161 | * Implement DoubleEndedIterator 162 | * insert_sorted performance improved on degenerate cases 163 | * BREAKING: insert_sorted now takes IntoIterator instead of an explicit slice 164 | * BREAKING: change the name of length to len, like BTreeMap 165 | 166 | 0.1.2 167 | * Initial public release 168 | -------------------------------------------------------------------------------- /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 2022 Eric Stokes 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 | Copyright 2022 Eric Stokes 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # immutable chunk map 2 | 3 | A cache efficient immutable map with lookup performance close to 4 | BTreeMap and reasonably good insertion performance. Optional copy on 5 | write mutable operations bring modification performance within 2x of 6 | BTreeMap in the best case while still offering snapshotting, and big O 7 | efficient set operations of a persistant data structure. 8 | 9 | A graph of lookup performance of various data structures using usize 10 | keys. Full test data in the bench/charts directory. Tests performed on 11 | an Intel Core i7 8550U under Linux with a locked frequency of 1.8 GHz. 12 | 13 | * OCaml: core map (from the Jane Street core library), an AVL tree 14 | with distinct leaf nodes and a relaxed balance constraint. 15 | * Chunkmap: this library 16 | * Chunkmap COW: this library using only COW operations 17 | * BTreeMap: from the Rust standard library 18 | * HashMap: from the Rust standard library 19 | 20 | ![alt text](bench/charts/intel_corei7-8550U_arrayvec_compact/usize_get.png "average lookup time") 21 | 22 | Chunkmap is very close to BTreeMap for random accesses using keys 23 | without hashing. Obviously if you don't need ordered data use a 24 | HashMap. 25 | 26 | ![alt text](bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert.png "average insert time") 27 | 28 | Insertion performance, while not as good as most mutable data 29 | structures, is not awful when using COW mode exclusively. In the case 30 | where you have many updates to do at once you can go even faster by 31 | using insert_many. In some cases, e.g. building a map from scratch 32 | using sorted inputs this can be faster than even a HashMap. The below 33 | case is more typical, adding 10% of a data set to the map. 34 | 35 | ![alt text](bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert_many.png "insert many") 36 | 37 | A note about the COW bar on this graph. It represents using only 38 | mutable COW operations on the map, it is perfectly possible to use an 39 | actual insert_many call instead of mutable COW operations if it's 40 | faster in your application, which as you can see, depends on the size 41 | of the map. 42 | 43 | # License 44 | This project is dual licensed under the MIT or the Apache 2 at your discretion. 45 | -------------------------------------------------------------------------------- /bench-ocaml/.merlin: -------------------------------------------------------------------------------- 1 | S . 2 | PKG core 3 | -------------------------------------------------------------------------------- /bench-ocaml/build.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | ocamlfind ocamlopt -package core -linkpkg -thread -o test test.ml 4 | -------------------------------------------------------------------------------- /bench-ocaml/test.ml: -------------------------------------------------------------------------------- 1 | open Core 2 | 3 | let min_iter = 1_000_000 4 | 5 | let random_string () = 6 | let size = 32 in 7 | let s = Bytes.create size in 8 | for i = 0 to size - 1 do 9 | let c = Option.value_exn (Char.of_int (Random.int 254)) in 10 | Bytes.set s i c; 11 | done; 12 | Bytes.to_string s 13 | 14 | let random_array size mk k = 15 | let s = Hash_set.create ~size k () in 16 | while Hash_set.length s < size do 17 | Hash_set.add s (mk ()) 18 | done; 19 | Hash_set.to_array s 20 | 21 | let bench_add cmp k v = 22 | let kv = Option.value_exn (Array.zip k v) in 23 | let st = Time.now () in 24 | let m = 25 | Array.fold kv ~init:(Map.empty cmp) 26 | ~f:(fun m (k, v) -> Map.set m ~key:k ~data:v) 27 | in 28 | let en = Time.now () in 29 | (m, Time.diff en st) 30 | 31 | let bench_find m k = 32 | let st = Time.now () in 33 | let i = ref 0 in 34 | let len = Array.length k in 35 | let iter = Int.max len min_iter in 36 | while !i < iter do 37 | assert (Option.is_some (Map.find m (Array.unsafe_get k (!i mod len)))); 38 | incr i 39 | done; 40 | let en = Time.now () in 41 | Time.diff en st 42 | 43 | let bench_remove m k = 44 | let st = Time.now () in 45 | let m = Array.fold k ~init:m ~f:(fun m k -> Map.remove m k) in 46 | if Map.length m <> 0 then failwith "remove is broken"; 47 | let en = Time.now () in 48 | Time.diff en st 49 | 50 | let () = 51 | let size = 52 | if Array.length Sys.argv = 4 then Int.of_string Sys.argv.(3) 53 | else begin 54 | printf "usage: test \n%!"; 55 | exit 0 56 | end 57 | in 58 | let str t sz = sprintf "%g" (Time.Span.to_ns t /. float sz) in 59 | match Sys.argv.(2) with 60 | "ptr" -> begin 61 | let mk () = Random.int Int.max_value in 62 | let k = random_array size mk (module Int) in 63 | let ks = random_array size mk (module Int) in 64 | let v = random_array size mk (module Int) in 65 | Array.sort ~compare:Int.compare ks; 66 | let (m, add) = bench_add (module Int) k v in 67 | let (_, adds) = bench_add (module Int) ks v in 68 | let find = bench_find m k in 69 | let rm = bench_remove m k in 70 | printf "%d,%s,%s,%s,%s,%s,%s\n%!" 71 | size (str add size) (str adds size) "0." 72 | (str find (Int.max min_iter size)) "0" (str rm size) 73 | end 74 | | "str" -> begin 75 | let k = random_array size random_string (module String) in 76 | let ks = random_array size random_string (module String) in 77 | let v = random_array size random_string (module String) in 78 | Array.sort ~compare:String.compare ks; 79 | let (m, add) = bench_add (module String) k v in 80 | let (_, adds) = bench_add (module String) ks v in 81 | let find = bench_find m k in 82 | let rm = bench_remove m k in 83 | printf "%d,%s,%s,%s,%s,%s,%s\n%!" 84 | size (str add size) (str adds size) "0." 85 | (str find (Int.max min_iter size)) "0" (str rm size) 86 | end 87 | | _ -> failwith "invalid kind. Allowed kinds: [ptr, str]" 88 | -------------------------------------------------------------------------------- /bench/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bench" 3 | version = "0.2.0" 4 | authors = ["Eric Stokes "] 5 | edition = "2018" 6 | 7 | [profile.release] 8 | codegen-units = 1 9 | opt-level = 3 10 | lto = true 11 | 12 | [dependencies] 13 | smallvec = "1.0" 14 | immutable-chunkmap = {path = "../"} 15 | rand = ">= 0.3" 16 | num_cpus = ">= 1.0" 17 | arcstr = "1" 18 | -------------------------------------------------------------------------------- /bench/bench.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import json 4 | import argparse 5 | import subprocess 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | 9 | def run_one(exe, bench, kind, size): 10 | return [ float(x) for x in subprocess.run( 11 | [exe, bench, kind, size], 12 | stdout = subprocess.PIPE, 13 | check = True 14 | ).stdout.strip().split(b',') ] 15 | 16 | def avg3(l): 17 | l.append((l.pop() + l.pop() + l.pop()) / 3.) 18 | 19 | def proto(): 20 | return { 21 | 'insert': [], 22 | 'insert_many': [], 23 | 'insert_many_par': [], 24 | 'get': [], 25 | 'get_parallel': [], 26 | 'remove': [], 27 | } 28 | 29 | def run(exe, bench, kind): 30 | result = proto() 31 | for size in ['1000', '10000', '100000', '1000000', '10000000']: 32 | for j in [1, 2, 3]: 33 | res = run_one(exe, bench, kind, size) 34 | result['insert'].append(res[1]) 35 | result['insert_many'].append(res[2]) 36 | result['insert_many_par'].append(res[3]) 37 | result['get'].append(res[4]) 38 | result['get_parallel'].append(res[5]) 39 | result['remove'].append(res[6]) 40 | avg3(result['insert']) 41 | avg3(result['insert_many']) 42 | avg3(result['insert_many_par']) 43 | avg3(result['get']) 44 | avg3(result['get_parallel']) 45 | avg3(result['remove']) 46 | return result 47 | 48 | def plot(fname, title, xlbl, ylbl, cm, cow, hm, btm, oc): 49 | fig, ax = plt.subplots() 50 | labels = ['1k', '10k', '100k', '1m', '10m'] 51 | x = np.arange(len(labels)) 52 | width = 0.15 53 | rects_hm = ax.bar(x, hm, width, label="HashMap") 54 | rects_cm = ax.bar(x + width, cm, width, label="Chunkmap") 55 | rects_cow = ax.bar(x + width*2, cow, width, label="Chunkmap COW") 56 | rects_bt = ax.bar(x + width*3, btm, width, label="BtreeMap") 57 | rects_oc = ax.bar(x + width*4, oc, width, label="OCaml Map") 58 | ax.set_ylabel(xlbl) 59 | ax.set_xlabel(ylbl) 60 | ax.set_title(title) 61 | ax.set_xticks(x) 62 | ax.set_xticklabels(labels) 63 | ax.legend() 64 | fig.tight_layout() 65 | fig.savefig(fname) 66 | 67 | def load_results(args): 68 | try: 69 | with open(args.data_path + '/data.json', 'r') as f: 70 | return json.load(f) 71 | except: 72 | return { 73 | 'cm': { 74 | 'ptr': proto(), 75 | 'str': proto() 76 | }, 77 | 'cow': { 78 | 'ptr': proto(), 79 | 'str': proto() 80 | }, 81 | 'hm': { 82 | 'ptr': proto(), 83 | 'str': proto() 84 | }, 85 | 'btm': { 86 | 'ptr': proto(), 87 | 'str': proto() 88 | }, 89 | 'oc': { 90 | 'ptr': proto(), 91 | 'str': proto() 92 | }, 93 | } 94 | 95 | def save_results(args, results): 96 | with open(args.data_path + '/data.json', 'w') as f: 97 | json.dump(results, f) 98 | 99 | def chart(args, results): 100 | plt.rcdefaults() 101 | plot( 102 | args.data_path + '/usize_insert.png', 103 | 'insert', "ns / insert", "final size", 104 | results['cm']['ptr']['insert'], 105 | results['cow']['ptr']['insert'], 106 | results['hm']['ptr']['insert'], 107 | results['btm']['ptr']['insert'], 108 | results['oc']['ptr']['insert'] 109 | ) 110 | plot( 111 | args.data_path + '/usize_insert_many.png', 112 | "insert many", "ns / insert", "final size", 113 | results['cm']['ptr']['insert_many'], 114 | results['cow']['ptr']['insert_many'], 115 | results['hm']['ptr']['insert_many'], 116 | results['btm']['ptr']['insert_many'], 117 | results['oc']['ptr']['insert_many'] 118 | ) 119 | plot( 120 | args.data_path + '/usize_insert_many_par.png', 121 | "insert many (all cores)", "ns / insert", "final size", 122 | results['cm']['ptr']['insert_many_par'], 123 | results['cow']['ptr']['insert_many_par'], 124 | results['hm']['ptr']['insert_many_par'], 125 | results['btm']['ptr']['insert_many_par'], 126 | results['oc']['ptr']['insert_many_par'] 127 | ) 128 | plot( 129 | args.data_path + '/usize_remove.png', 130 | "remove", "ns / remove", "initial size", 131 | results['cm']['ptr']['remove'], 132 | results['cow']['ptr']['remove'], 133 | results['hm']['ptr']['remove'], 134 | results['btm']['ptr']['remove'], 135 | results['oc']['ptr']['remove'] 136 | ) 137 | plot( 138 | args.data_path + '/usize_get.png', 139 | "get", "ns / get", "size", 140 | results['cm']['ptr']['get'], 141 | results['cow']['ptr']['get'], 142 | results['hm']['ptr']['get'], 143 | results['btm']['ptr']['get'], 144 | results['oc']['ptr']['get'] 145 | ) 146 | plot( 147 | args.data_path + '/usize_get_parallel.png', 148 | "get (all cores)", "ns / get", "size", 149 | results['cm']['ptr']['get_parallel'], 150 | results['cow']['ptr']['get_parallel'], 151 | results['hm']['ptr']['get_parallel'], 152 | results['btm']['ptr']['get_parallel'], 153 | results['oc']['ptr']['get_parallel'] 154 | ) 155 | plot( 156 | args.data_path + '/str_insert.png', 157 | 'insert', "ns / insert", "final size", 158 | results['cm']['str']['insert'], 159 | results['cow']['str']['insert'], 160 | results['hm']['str']['insert'], 161 | results['btm']['str']['insert'], 162 | results['oc']['str']['insert'] 163 | ) 164 | plot( 165 | args.data_path + '/str_insert_many.png', 166 | "insert many", "ns / insert", "final size", 167 | results['cm']['str']['insert_many'], 168 | results['cow']['str']['insert_many'], 169 | results['hm']['str']['insert_many'], 170 | results['btm']['str']['insert_many'], 171 | results['oc']['str']['insert_many'] 172 | ) 173 | plot( 174 | args.data_path + '/str_insert_many_par.png', 175 | "insert many (all cores)", "ns / insert", "final size", 176 | results['cm']['str']['insert_many_par'], 177 | results['cow']['str']['insert_many_par'], 178 | results['hm']['str']['insert_many_par'], 179 | results['btm']['str']['insert_many_par'], 180 | results['oc']['str']['insert_many_par'] 181 | ) 182 | plot( 183 | args.data_path + '/str_remove.png', 184 | "remove", "ns / remove", "initial size", 185 | results['cm']['str']['remove'], 186 | results['cow']['str']['remove'], 187 | results['hm']['str']['remove'], 188 | results['btm']['str']['remove'], 189 | results['oc']['str']['remove'] 190 | ) 191 | plot( 192 | args.data_path + '/str_get.png', 193 | "get", "ns / get", "size", 194 | results['cm']['str']['get'], 195 | results['cow']['str']['get'], 196 | results['hm']['str']['get'], 197 | results['btm']['str']['get'], 198 | results['oc']['str']['get'] 199 | ) 200 | plot( 201 | args.data_path + '/str_get_parallel.png', 202 | "get (all cores)", "ns / get", "size", 203 | results['cm']['str']['get_parallel'], 204 | results['cow']['str']['get_parallel'], 205 | results['hm']['str']['get_parallel'], 206 | results['btm']['str']['get_parallel'], 207 | results['oc']['str']['get_parallel'] 208 | ) 209 | 210 | parser = argparse.ArgumentParser(description = "run benchmarks") 211 | parser.add_argument( 212 | '--run', 213 | required = False, 214 | choices = ['all', 'cm', 'cow', 'hm', 'btm', 'oc'] 215 | ) 216 | parser.add_argument('--data-path', required = True) 217 | parser.add_argument('--chart', default = False, action = 'store_const', const = True) 218 | args = parser.parse_args() 219 | 220 | results = load_results(args) 221 | 222 | if args.run == 'all' or args.run == 'cm': 223 | results['cm']['ptr'] = run('target/release/bench', 'cm', 'ptr') 224 | results['cm']['str'] = run('target/release/bench', 'cm', 'str') 225 | if args.run == 'all' or args.run == 'cow': 226 | results['cow']['ptr'] = run('target/release/bench', 'cow', 'ptr') 227 | results['cow']['str'] = run('target/release/bench', 'cow', 'str') 228 | if args.run == 'all' or args.run == 'hm': 229 | results['hm']['ptr'] = run('target/release/bench', 'hm', 'ptr') 230 | results['hm']['str'] = run('target/release/bench', 'hm', 'str') 231 | if args.run == 'all' or args.run == 'btm': 232 | results['btm']['ptr'] = run('target/release/bench', 'btm', 'ptr') 233 | results['btm']['str'] = run('target/release/bench', 'btm', 'str') 234 | if args.run == 'all' or args.run == 'oc': 235 | results['oc']['ptr'] = run('../bench-ocaml/test', 'oc', 'ptr') 236 | results['oc']['str'] = run('../bench-ocaml/test', 'oc', 'str') 237 | 238 | save_results(args, results) 239 | 240 | if args.chart: 241 | chart(args, results) 242 | -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [863.3333333333334, 1740.3333333333333, 2864.6666666666665, 4384.666666666667, 6529.333333333333], "insert_many": [658.3333333333334, 929.6666666666666, 1006.0, 1204.0, 1665.3333333333333], "insert_many_par": [1820.6666666666667, 1627.6666666666667, 1932.3333333333333, 2323.0, 3066.3333333333335], "get": [24.333333333333332, 43.666666666666664, 80.33333333333333, 168.33333333333334, 368.3333333333333], "get_parallel": [1.6333333333333335, 2.723333333333334, 6.423333333333333, 12.953333333333333, 35.653333333333336], "remove": [903.3333333333334, 1694.0, 2940.6666666666665, 4408.333333333333, 6623.0]}, "str": {"insert": [25651.0, 27782.333333333332, 33867.0, 48133.333333333336, 61132.666666666664], "insert_many": [12799.333333333334, 12974.666666666666, 14786.0, 15879.333333333334, 17085.333333333332], "insert_many_par": [9063.0, 10905.666666666666, 11916.666666666666, 12904.666666666666, 16595.0], "get": [173.0, 260.6666666666667, 421.6666666666667, 878.3333333333334, 1503.6666666666667], "get_parallel": [11.03, 17.16, 25.573333333333334, 64.11000000000001, 116.03666666666668], "remove": [25978.0, 27938.0, 33345.0, 43831.0, 55770.0]}}, "hm": {"ptr": {"insert": [41.0, 42.0, 52.0, 44.0, 73.66666666666667], "insert_many": [101.0, 83.0, 81.33333333333333, 104.33333333333333, 104.33333333333333], "insert_many_par": [363.6666666666667, 121.33333333333333, 85.66666666666667, 108.33333333333333, 114.0], "get": [31.0, 32.0, 34.0, 55.0, 93.0], "get_parallel": [2.4533333333333336, 2.6, 2.74, 4.403333333333333, 9.18], "remove": [41.666666666666664, 42.666666666666664, 42.666666666666664, 55.0, 90.66666666666667]}, "str": {"insert": [83.33333333333333, 75.33333333333333, 89.33333333333333, 90.0, 130.66666666666666], "insert_many": [207.66666666666666, 157.0, 154.66666666666666, 297.3333333333333, 309.3333333333333], "insert_many_par": [507.6666666666667, 200.0, 174.0, 358.3333333333333, 398.0], "get": [58.333333333333336, 68.0, 108.33333333333333, 228.33333333333334, 296.3333333333333], "get_parallel": [4.883333333333333, 5.86, 7.696666666666666, 20.01666666666667, 25.356666666666666], "remove": [231.33333333333334, 180.66666666666666, 229.66666666666666, 289.0, 348.0]}}, "btm": {"ptr": {"insert": [145.66666666666666, 186.66666666666666, 241.0, 388.3333333333333, 614.6666666666666], "insert_many": [147.66666666666666, 172.0, 213.33333333333334, 297.0, 477.0], "insert_many_par": [832.6666666666666, 222.33333333333334, 201.0, 252.0, 330.0], "get": [76.0, 108.0, 149.0, 242.66666666666666, 438.6666666666667], "get_parallel": [3.81, 5.55, 8.113333333333335, 14.54, 31.736666666666668], "remove": [159.33333333333334, 178.33333333333334, 230.66666666666666, 399.6666666666667, 634.0]}, "str": {"insert": [250.33333333333334, 336.3333333333333, 569.6666666666666, 1072.3333333333333, 1583.6666666666667], "insert_many": [245.0, 305.3333333333333, 443.6666666666667, 836.0, 1274.0], "insert_many_par": [836.3333333333334, 385.0, 433.3333333333333, 707.3333333333334, 952.3333333333334], "get": [157.66666666666666, 232.66666666666666, 380.6666666666667, 799.0, 1204.6666666666667], "get_parallel": [12.01, 19.12, 29.76, 65.35, 111.20333333333333], "remove": [349.0, 398.6666666666667, 604.0, 1044.0, 1566.3333333333333]}}, "oc": {"ptr": {"insert": [258.20733333333334, 588.3296666666666, 1033.6566666666668, 1866.7633333333333, 3109.5533333333333], "insert_many": [223.79566666666668, 482.82933333333335, 450.1216666666666, 505.356, 586.266], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [122.693, 171.70700000000002, 243.11866666666666, 406.026, 669.2996666666667], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [236.59066666666664, 399.1286666666667, 893.379, 1785.7333333333333, 3035.603333333333]}, "str": {"insert": [398.9536666666666, 818.658, 1442.2066666666667, 3036.976666666667, 4593.776666666667], "insert_many": [365.4956666666667, 687.0266666666666, 714.7186666666666, 852.406, 1042.0166666666667], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [242.94466666666668, 344.9676666666667, 502.62100000000004, 954.6149999999999, 1552.9433333333334], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [334.81933333333336, 564.13, 1293.0433333333333, 2592.6233333333334, 3825.486666666666]}}} -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/str_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/str_get.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/str_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/str_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/str_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/str_insert.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/str_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/str_insert_many.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/str_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/str_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/str_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/str_remove.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/usize_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/usize_get.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/usize_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/usize_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/usize_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/usize_insert.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/usize_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/usize_insert_many.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/usize_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/usize_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/ibm_power9_02CY089/usize_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/ibm_power9_02CY089/usize_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X-C128/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [331.3333333333333, 539.3333333333334, 941.6666666666666, 1805.3333333333333, 3964.0], "insert_many": [321.6666666666667, 393.3333333333333, 491.0, 775.3333333333334, 1437.0], "insert_many_par": [246.0, 245.66666666666666, 268.6666666666667, 396.0, 2609.3333333333335], "get": [30.0, 53.333333333333336, 82.66666666666667, 163.0, 428.3333333333333], "get_parallel": [4.0200000000000005, 6.8500000000000005, 10.863333333333332, 22.936666666666667, 57.36666666666667], "remove": [372.6666666666667, 535.3333333333334, 955.3333333333334, 1845.3333333333333, 5044.0]}, "str": {"insert": [10542.0, 11292.0, 18505.0, 36837.666666666664, 34082.666666666664], "insert_many": [5384.666666666667, 5735.333333333333, 8243.333333333334, 9483.666666666666, 10846.666666666666], "insert_many_par": [1141.0, 1449.0, 1881.6666666666667, 2581.6666666666665, 9721.666666666666], "get": [85.66666666666667, 138.66666666666666, 350.3333333333333, 872.6666666666666, 1522.6666666666667], "get_parallel": [10.950000000000001, 17.726666666666667, 45.74666666666667, 111.22666666666667, 191.34666666666666], "remove": [10810.0, 11308.666666666666, 16933.0, 29261.666666666668, 42470.333333333336]}}, "hm": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}, "btm": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}, "oc": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X-C256/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [371.6666666666667, 552.6666666666666, 1039.3333333333333, 1899.6666666666667, 4360.666666666667], "insert_many": [263.6666666666667, 299.0, 361.6666666666667, 511.3333333333333, 864.6666666666666], "insert_many_par": [195.33333333333334, 201.0, 202.66666666666666, 260.0, 1371.0], "get": [32.333333333333336, 50.333333333333336, 78.33333333333333, 150.0, 399.0], "get_parallel": [4.170000000000001, 6.453333333333333, 10.286666666666667, 20.903333333333332, 53.620000000000005], "remove": [372.3333333333333, 539.6666666666666, 1026.6666666666667, 1967.6666666666667, 5237.0]}, "str": {"insert": [20096.666666666668, 21418.666666666668, 31730.333333333332, 65012.0, 56893.0], "insert_many": [5684.0, 5892.333333333333, 7795.666666666667, 8412.333333333334, 9198.666666666666], "insert_many_par": [975.6666666666666, 1359.0, 1552.0, 2030.3333333333333, 5775.666666666667], "get": [89.33333333333333, 138.66666666666666, 341.6666666666667, 825.0, 1468.6666666666667], "get_parallel": [11.476666666666667, 18.153333333333332, 45.373333333333335, 106.46666666666665, 185.79], "remove": [20110.0, 20498.666666666668, 26124.0, 46464.666666666664, 61959.0]}}, "hm": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}, "btm": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}, "oc": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X-C512/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [369.0, 569.3333333333334, 1133.3333333333333, 2047.6666666666667, 4761.0], "insert_many": [171.33333333333334, 220.66666666666666, 281.6666666666667, 371.3333333333333, 567.6666666666666], "insert_many_par": [142.0, 157.66666666666666, 164.33333333333334, 195.66666666666666, 759.6666666666666], "get": [34.333333333333336, 48.666666666666664, 75.66666666666667, 143.66666666666666, 371.3333333333333], "get_parallel": [4.486666666666667, 6.2700000000000005, 9.846666666666666, 19.98, 49.93333333333334], "remove": [360.0, 547.0, 1039.6666666666667, 1974.3333333333333, 5427.666666666667]}, "str": {"insert": [39790.0, 40685.0, 58610.333333333336, 118664.66666666667, 89793.33333333333], "insert_many": [5421.0, 5823.333333333333, 7403.333333333333, 8064.666666666667, 8438.666666666666], "insert_many_par": [706.6666666666666, 1175.3333333333333, 1489.0, 1758.6666666666667, 3675.0], "get": [93.0, 141.0, 346.6666666666667, 793.0, 1459.3333333333333], "get_parallel": [11.923333333333334, 18.156666666666666, 45.50666666666667, 103.73333333333333, 185.61333333333334], "remove": [39731.0, 39561.0, 46480.0, 76648.33333333333, 98495.0]}}, "hm": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}, "btm": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}, "oc": {"ptr": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}, "str": {"insert": [], "insert_many": [], "insert_many_par": [], "get": [], "get_parallel": [], "remove": []}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X-C64/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [354.6666666666667, 641.3333333333334, 1026.0, 1808.0, 378.3333333333333], "insert_many": [393.3333333333333, 497.3333333333333, 631.6666666666666, 1137.3333333333333, 2229.3333333333335], "insert_many_par": [309.6666666666667, 298.6666666666667, 344.6666666666667, 552.3333333333334, 5447.333333333333], "get": [28.0, 55.666666666666664, 88.66666666666667, 176.33333333333334, 458.6666666666667], "get_parallel": [3.6133333333333333, 7.13, 11.75, 24.106666666666666, 60.550000000000004], "remove": [375.6666666666667, 640.0, 1056.0, 1865.0, 460.3333333333333]}, "str": {"insert": [1517.6666666666667, 2370.0, 4882.666666666667, 8386.333333333334, 1335.0], "insert_many": [1386.0, 2274.3333333333335, 4456.666666666667, 8085.666666666667, 10971.333333333334], "insert_many_par": [645.6666666666666, 803.6666666666666, 1320.0, 2048.3333333333335, 12559.666666666666], "get": [99.33333333333333, 163.33333333333334, 390.0, 992.6666666666666, 1797.3333333333333], "get_parallel": [12.603333333333333, 21.116666666666667, 52.31666666666666, 125.38, 217.94333333333336], "remove": [1532.0, 2431.0, 5119.666666666667, 8424.333333333334, 1492.3333333333333]}}, "hm": {"ptr": {"insert": [15.666666666666666, 16.0, 28.0, 28.666666666666668, 6.0], "insert_many": [53.333333333333336, 43.333333333333336, 39.0, 58.0, 70.66666666666667], "insert_many_par": [94.33333333333333, 55.666666666666664, 53.333333333333336, 69.33333333333333, 83.66666666666667], "get": [12.0, 12.0, 19.333333333333332, 57.0, 87.0], "get_parallel": [2.07, 1.7466666666666668, 2.783333333333333, 7.566666666666667, 11.07], "remove": [17.666666666666668, 19.333333333333332, 29.0, 59.333333333333336, 9.0]}, "str": {"insert": [50.0, 48.333333333333336, 96.66666666666667, 189.0, 25.333333333333332], "insert_many": [148.0, 157.66666666666666, 275.3333333333333, 526.3333333333334, 569.0], "insert_many_par": [215.66666666666666, 194.33333333333334, 318.0, 588.0, 624.3333333333334], "get": [40.333333333333336, 59.666666666666664, 149.33333333333334, 185.0, 231.66666666666666], "get_parallel": [5.123333333333334, 7.763333333333333, 17.153333333333332, 26.096666666666664, 31.58666666666667], "remove": [95.66666666666667, 102.33333333333333, 265.0, 382.6666666666667, 48.0]}}, "btm": {"ptr": {"insert": [56.333333333333336, 68.0, 104.66666666666667, 247.0, 43.0], "insert_many": [55.333333333333336, 66.0, 91.0, 160.66666666666666, 380.3333333333333], "insert_many_par": [101.66666666666667, 72.66666666666667, 83.66666666666667, 126.33333333333333, 165.66666666666666], "get": [27.0, 53.0, 86.66666666666667, 178.66666666666666, 414.6666666666667], "get_parallel": [3.4800000000000004, 6.8066666666666675, 11.503333333333332, 22.900000000000002, 51.74666666666667], "remove": [68.33333333333333, 69.33333333333333, 106.66666666666667, 277.6666666666667, 49.0]}, "str": {"insert": [112.66666666666667, 168.66666666666666, 376.3333333333333, 853.3333333333334, 150.66666666666666], "insert_many": [102.33333333333333, 153.0, 322.0, 706.6666666666666, 1297.3333333333333], "insert_many_par": [157.0, 178.66666666666666, 283.0, 436.6666666666667, 568.6666666666666], "get": [68.66666666666667, 119.0, 297.0, 663.6666666666666, 1256.3333333333333], "get_parallel": [8.846666666666666, 15.376666666666665, 38.19, 84.69333333333333, 153.96666666666667], "remove": [167.66666666666666, 197.0, 466.6666666666667, 893.3333333333334, 155.0]}}, "oc": {"ptr": {"insert": [132.48133333333334, 339.651, 718.3853333333333, 1651.0666666666666, 2621.066666666666], "insert_many": [101.56633333333333, 243.6163333333333, 229.0103333333333, 307.51433333333335, 455.8346666666667], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [64.92233333333333, 94.18536666666667, 171.73000000000002, 378.12166666666667, 605.8106666666666], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [122.38799999999999, 223.81933333333333, 721.697, 1656.6333333333332, 2550.806666666667]}, "str": {"insert": [175.55533333333335, 445.9536666666667, 1239.0100000000002, 2570.57, 3826.44], "insert_many": [139.95166666666665, 311.605, 336.2056666666667, 406.507, 489.442], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [105.54733333333333, 159.94633333333334, 337.3833333333334, 833.3103333333332, 1341.3600000000001], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [151.0776666666667, 303.022, 1114.6233333333332, 2234.0866666666666, 3303.396666666666]}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [320.0, 544.6666666666666, 954.0, 1831.6666666666667, 3256.0], "insert_many": [318.0, 394.3333333333333, 481.6666666666667, 781.6666666666666, 1327.3333333333333], "insert_many_par": [612.3333333333334, 447.0, 480.0, 662.6666666666666, 1822.3333333333333], "get": [30.666666666666668, 52.666666666666664, 82.66666666666667, 171.0, 380.3333333333333], "get_parallel": [2.2833333333333337, 4.496666666666667, 7.080000000000001, 15.63, 34.93], "remove": [383.0, 542.0, 975.0, 1796.0, 3208.3333333333335]}, "str": {"insert": [10450.333333333334, 11506.0, 18151.333333333332, 36501.333333333336, 48975.666666666664], "insert_many": [5399.0, 5721.666666666667, 7754.333333333333, 9389.333333333334, 10974.0], "insert_many_par": [2302.3333333333335, 2543.3333333333335, 3187.6666666666665, 3995.6666666666665, 7913.333333333333], "get": [82.0, 129.66666666666666, 316.0, 799.3333333333334, 1403.0], "get_parallel": [6.353333333333333, 11.246666666666668, 26.349999999999998, 61.39666666666667, 105.56333333333333], "remove": [10712.666666666666, 11464.0, 15832.0, 28358.333333333332, 40096.333333333336]}}, "hm": {"ptr": {"insert": [16.0, 17.666666666666668, 22.0, 30.0, 73.0], "insert_many": [53.666666666666664, 43.333333333333336, 39.333333333333336, 57.666666666666664, 72.33333333333333], "insert_many_par": [389.6666666666667, 73.33333333333333, 47.0, 72.66666666666667, 83.33333333333333], "get": [12.0, 13.666666666666666, 21.0, 63.666666666666664, 94.0], "get_parallel": [1.3566666666666667, 1.4933333333333334, 2.3433333333333333, 6.326666666666667, 9.696666666666665], "remove": [19.333333333333332, 21.0, 31.0, 85.66666666666667, 128.0]}, "str": {"insert": [32.0, 34.0, 58.0, 73.0, 121.66666666666667], "insert_many": [111.0, 109.33333333333333, 140.33333333333334, 272.6666666666667, 282.6666666666667], "insert_many_par": [386.3333333333333, 159.0, 204.33333333333334, 377.6666666666667, 384.0], "get": [31.0, 43.0, 85.66666666666667, 133.66666666666666, 179.0], "get_parallel": [2.8800000000000003, 3.8033333333333332, 8.33, 14.843333333333334, 18.89333333333333], "remove": [66.0, 68.66666666666667, 99.0, 161.0, 200.66666666666666]}}, "btm": {"ptr": {"insert": [64.0, 82.33333333333333, 123.33333333333333, 253.0, 476.3333333333333], "insert_many": [60.666666666666664, 75.0, 103.0, 178.66666666666666, 359.6666666666667], "insert_many_par": [295.3333333333333, 97.66666666666667, 95.66666666666667, 144.0, 194.0], "get": [37.0, 60.0, 93.0, 191.66666666666666, 380.6666666666667], "get_parallel": [3.246666666666666, 5.13, 8.076666666666666, 17.426666666666666, 30.833333333333332], "remove": [78.66666666666667, 88.66666666666667, 133.66666666666666, 300.0, 527.6666666666666]}, "str": {"insert": [101.33333333333333, 164.33333333333334, 384.3333333333333, 808.0, 1310.6666666666667], "insert_many": [107.33333333333333, 142.0, 308.6666666666667, 630.3333333333334, 1082.0], "insert_many_par": [426.0, 177.33333333333334, 268.3333333333333, 437.0, 517.6666666666666], "get": [64.0, 110.33333333333333, 267.0, 581.6666666666666, 1046.3333333333333], "get_parallel": [6.083333333333333, 11.269999999999998, 26.396666666666665, 52.57333333333333, 91.51666666666667], "remove": [134.0, 175.0, 419.6666666666667, 805.0, 1290.3333333333333]}}, "oc": {"ptr": {"insert": [132.64000000000001, 325.22700000000003, 710.652, 1654.4099999999999, 2630.9466666666667], "insert_many": [101.24833333333333, 242.41633333333334, 228.4216666666667, 309.449, 458.42633333333333], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [65.29809999999999, 92.9017, 168.97633333333332, 378.94866666666667, 602.3546666666666], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [122.38833333333332, 220.577, 712.2953333333334, 1664.45, 2561.91]}, "str": {"insert": [176.58900000000003, 432.8966666666667, 1246.55, 2617.713333333333, 3869.64], "insert_many": [141.77966666666666, 309.45133333333337, 334.6356666666666, 407.3243333333333, 489.08099999999996], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [105.855, 160.7346666666667, 332.5826666666666, 840.4966666666666, 1340.3633333333335], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [152.26999999999998, 302.60066666666665, 1110.62, 2269.86, 3322.5066666666667]}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/str_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/str_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/str_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/str_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/str_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/str_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/str_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/str_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/str_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/str_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/str_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/str_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/usize_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/usize_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/usize_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/usize_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/usize_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/usize_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/usize_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/usize_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/usize_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/usize_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-7820X/usize_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-7820X/usize_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [982.6666666666666, 1517.3333333333333, 2961.6666666666665, 4775.333333333333, 9529.333333333334], "insert_many": [462.6666666666667, 578.3333333333334, 658.6666666666666, 780.3333333333334, 985.0], "insert_many_par": [473.0, 413.6666666666667, 430.0, 501.3333333333333, 1769.0], "get": [82.66666666666667, 134.0, 236.33333333333334, 414.6666666666667, 823.3333333333334], "get_parallel": [11.783333333333333, 21.203333333333333, 35.89333333333333, 68.15333333333335, 133.31000000000003], "remove": [1011.3333333333334, 1499.3333333333333, 2795.0, 4785.333333333333, 11750.0]}, "str": {"insert": [22741.0, 24026.0, 42623.0, 56470.666666666664, 82525.66666666667], "insert_many": [3401.3333333333335, 3881.6666666666665, 7593.333333333333, 9899.0, 12727.0], "insert_many_par": [807.0, 1101.3333333333333, 1688.3333333333333, 2022.0, 3666.3333333333335], "get": [229.33333333333334, 393.3333333333333, 772.3333333333334, 1559.0, 2739.0], "get_parallel": [36.666666666666664, 61.73333333333333, 128.98333333333335, 254.08, 436.89000000000004], "remove": [22948.333333333332, 24025.666666666668, 42038.666666666664, 55706.0, 84659.0]}}, "cow": {"ptr": {"insert": [286.3333333333333, 470.6666666666667, 852.3333333333334, 1606.0, 3318.0], "insert_many": [293.6666666666667, 521.3333333333334, 910.6666666666666, 1668.3333333333333, 3424.0], "insert_many_par": [493.6666666666667, 489.3333333333333, 520.3333333333334, 666.0, 1023.6666666666666], "get": [82.66666666666667, 133.0, 236.33333333333334, 422.3333333333333, 884.0], "get_parallel": [11.083333333333334, 21.663333333333338, 37.38, 72.95333333333333, 147.89], "remove": [271.3333333333333, 418.0, 756.3333333333334, 1471.6666666666667, 2716.6666666666665]}, "str": {"insert": [483.6666666666667, 941.0, 1889.6666666666667, 3497.3333333333335, 6381.666666666667], "insert_many": [477.6666666666667, 960.3333333333334, 1883.3333333333333, 3520.6666666666665, 6346.666666666667], "insert_many_par": [834.0, 1241.3333333333333, 1887.0, 2452.0, 3330.3333333333335], "get": [231.33333333333334, 387.3333333333333, 778.0, 1580.0, 2844.0], "get_parallel": [37.22666666666666, 60.60999999999999, 127.77333333333335, 255.79, 454.3766666666667], "remove": [486.0, 876.0, 1806.3333333333333, 3340.3333333333335, 5671.333333333333]}}, "hm": {"ptr": {"insert": [40.333333333333336, 47.333333333333336, 65.0, 66.33333333333333, 153.33333333333334], "insert_many": [146.33333333333334, 120.0, 103.66666666666667, 161.33333333333334, 203.0], "insert_many_par": [378.3333333333333, 138.33333333333334, 111.66666666666667, 168.66666666666666, 209.33333333333334], "get": [31.0, 47.333333333333336, 46.0, 95.66666666666667, 143.66666666666666], "get_parallel": [6.7700000000000005, 7.8999999999999995, 10.693333333333333, 22.236666666666668, 31.653333333333336], "remove": [41.333333333333336, 43.333333333333336, 60.333333333333336, 99.66666666666667, 198.33333333333334]}, "str": {"insert": [126.0, 138.33333333333334, 207.66666666666666, 318.0, 440.6666666666667], "insert_many": [370.3333333333333, 346.3333333333333, 467.0, 779.0, 856.6666666666666], "insert_many_par": [592.3333333333334, 384.6666666666667, 504.3333333333333, 799.6666666666666, 885.3333333333334], "get": [112.66666666666667, 127.33333333333333, 217.0, 273.3333333333333, 361.0], "get_parallel": [21.540000000000003, 23.77, 35.39, 43.36333333333334, 54.82], "remove": [180.0, 187.66666666666666, 367.0, 571.0, 699.0]}}, "btm": {"ptr": {"insert": [130.66666666666666, 177.66666666666666, 249.66666666666666, 473.0, 732.0], "insert_many": [137.66666666666666, 163.0, 232.66666666666666, 374.3333333333333, 630.3333333333334], "insert_many_par": [285.3333333333333, 159.66666666666666, 169.33333333333334, 223.33333333333334, 286.3333333333333], "get": [80.33333333333333, 135.66666666666666, 207.33333333333334, 401.3333333333333, 650.3333333333334], "get_parallel": [11.943333333333333, 22.47666666666667, 32.97666666666667, 65.49, 100.06], "remove": [186.33333333333334, 202.66666666666666, 268.6666666666667, 518.3333333333334, 764.0]}, "str": {"insert": [278.3333333333333, 434.3333333333333, 846.3333333333334, 1520.6666666666667, 2434.3333333333335], "insert_many": [258.6666666666667, 386.0, 708.0, 1323.3333333333333, 2133.0], "insert_many_par": [430.0, 361.0, 552.3333333333334, 763.3333333333334, 1010.6666666666666], "get": [198.66666666666666, 334.0, 652.3333333333334, 1267.6666666666667, 2103.0], "get_parallel": [34.77666666666667, 58.88999999999999, 124.09333333333332, 238.48333333333335, 383.55], "remove": [316.3333333333333, 418.6666666666667, 844.3333333333334, 1483.3333333333333, 2371.0]}}, "oc": {"ptr": {"insert": [381.46999999999997, 984.5093333333334, 1672.533333333333, 3096.7099999999996, 4964.576666666667], "insert_many": [303.6656666666666, 709.16, 630.659, 772.445, 1058.3433333333332], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [180.59133333333332, 275.81666666666666, 447.92966666666666, 815.8256666666666, 1229.3566666666668], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [341.49500000000006, 623.5679999999999, 1545.01, 2961.533333333333, 4686.2]}, "str": {"insert": [509.02366666666666, 1217.7066666666667, 2407.48, 4653.346666666667, 7305.096666666667], "insert_many": [423.35200000000003, 847.0056666666666, 839.4406666666667, 1033.5466666666669, 1251.1533333333334], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [306.061, 512.7156666666666, 880.3036666666667, 1786.8633333333335, 2745.9066666666663], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [426.13366666666667, 847.9913333333334, 2141.826666666667, 4077.52, 6410.25]}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/str_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/str_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/str_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/str_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/str_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/str_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/str_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/str_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/str_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/str_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/str_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/str_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/usize_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/usize_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/usize_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/usize_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/usize_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/usize_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/usize_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/usize_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/usize_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/usize_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U/usize_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U/usize_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [1733.0, 2059.0, 2995.6666666666665, 4602.333333333333, 7591.0], "insert_many": [461.0, 590.6666666666666, 645.6666666666666, 745.6666666666666, 906.0], "insert_many_par": [525.6666666666666, 343.0, 361.3333333333333, 432.0, 1697.6666666666667], "get": [73.66666666666667, 132.66666666666666, 228.33333333333334, 392.6666666666667, 731.6666666666666], "get_parallel": [10.973333333333334, 20.98, 35.68666666666667, 63.346666666666664, 123.82000000000001], "remove": [1697.6666666666667, 2093.6666666666665, 3004.6666666666665, 4743.0, 10559.666666666666]}, "str": {"insert": [23543.666666666668, 24999.333333333332, 39698.333333333336, 51378.333333333336, 74773.0], "insert_many": [3401.3333333333335, 3883.6666666666665, 7356.666666666667, 9564.333333333334, 12423.333333333334], "insert_many_par": [886.6666666666666, 1059.3333333333333, 1588.6666666666667, 1940.6666666666667, 3591.6666666666665], "get": [233.33333333333334, 386.0, 772.0, 1482.0, 2660.3333333333335], "get_parallel": [38.96333333333334, 60.673333333333325, 125.46333333333332, 248.18000000000004, 429.03666666666663], "remove": [23633.0, 25067.666666666668, 40751.333333333336, 53735.0, 82554.0]}}, "cow": {"ptr": {"insert": [293.6666666666667, 438.3333333333333, 770.3333333333334, 1433.6666666666667, 2620.3333333333335], "insert_many": [288.3333333333333, 482.3333333333333, 824.0, 1419.6666666666667, 2811.6666666666665], "insert_many_par": [519.6666666666666, 408.3333333333333, 444.3333333333333, 568.3333333333334, 928.6666666666666], "get": [79.0, 132.33333333333334, 236.66666666666666, 412.3333333333333, 893.3333333333334], "get_parallel": [12.126666666666667, 22.05666666666667, 37.449999999999996, 67.72666666666667, 137.26], "remove": [279.6666666666667, 412.3333333333333, 721.0, 1371.0, 2480.6666666666665]}, "str": {"insert": [464.3333333333333, 903.6666666666666, 1805.6666666666667, 3295.3333333333335, 5591.0], "insert_many": [458.6666666666667, 930.6666666666666, 1770.6666666666667, 3258.0, 5681.333333333333], "insert_many_par": [957.6666666666666, 1244.3333333333333, 1783.0, 2317.0, 3180.3333333333335], "get": [233.33333333333334, 395.0, 771.6666666666666, 1522.3333333333333, 2742.6666666666665], "get_parallel": [38.76666666666666, 62.336666666666666, 126.51333333333334, 249.12333333333333, 440.77666666666664], "remove": [500.6666666666667, 872.3333333333334, 1763.3333333333333, 3232.6666666666665, 5306.333333333333]}}, "hm": {"ptr": {"insert": [41.666666666666664, 46.0, 65.66666666666667, 68.66666666666667, 154.0], "insert_many": [147.66666666666666, 118.66666666666667, 104.33333333333333, 163.0, 203.33333333333334], "insert_many_par": [308.6666666666667, 138.0, 119.66666666666667, 181.0, 229.66666666666666], "get": [31.666666666666668, 35.0, 47.333333333333336, 95.66666666666667, 146.33333333333334], "get_parallel": [7.1499999999999995, 8.01, 10.843333333333334, 22.060000000000002, 31.899999999999995], "remove": [44.333333333333336, 46.666666666666664, 64.33333333333333, 101.66666666666667, 198.66666666666666]}, "str": {"insert": [125.66666666666667, 140.66666666666666, 215.33333333333334, 326.0, 442.0], "insert_many": [393.6666666666667, 354.6666666666667, 479.6666666666667, 792.6666666666666, 871.3333333333334], "insert_many_par": [588.6666666666666, 391.0, 513.6666666666666, 812.0, 888.0], "get": [115.66666666666667, 129.66666666666666, 221.66666666666666, 285.3333333333333, 368.0], "get_parallel": [22.12, 24.463333333333335, 36.95, 44.79666666666666, 56.43666666666667], "remove": [186.0, 197.66666666666666, 401.0, 592.3333333333334, 756.3333333333334]}}, "btm": {"ptr": {"insert": [186.33333333333334, 193.0, 263.0, 489.6666666666667, 751.3333333333334], "insert_many": [144.66666666666666, 176.66666666666666, 245.0, 388.0, 646.6666666666666], "insert_many_par": [308.6666666666667, 173.33333333333334, 189.0, 245.33333333333334, 311.3333333333333], "get": [81.66666666666667, 139.33333333333334, 213.66666666666666, 412.0, 661.6666666666666], "get_parallel": [14.376666666666665, 24.629999999999995, 35.10333333333333, 66.52, 101.25], "remove": [201.33333333333334, 218.33333333333334, 284.6666666666667, 532.6666666666666, 780.0]}, "str": {"insert": [264.0, 422.0, 830.3333333333334, 1524.0, 2434.0], "insert_many": [247.66666666666666, 374.3333333333333, 699.3333333333334, 1320.0, 2135.6666666666665], "insert_many_par": [408.0, 341.6666666666667, 525.6666666666666, 733.0, 985.0], "get": [193.33333333333334, 329.0, 650.0, 1269.3333333333333, 2127.3333333333335], "get_parallel": [34.28333333333333, 58.81666666666666, 123.63333333333333, 238.76, 383.1566666666667], "remove": [312.3333333333333, 404.0, 833.3333333333334, 1482.0, 2368.3333333333335]}}, "oc": {"ptr": {"insert": [374.7146666666667, 975.919, 1677.71, 3117.2566666666667, 4984.223333333332], "insert_many": [302.9506666666667, 700.1320000000001, 629.6563333333334, 773.6193333333334, 1060.0766666666666], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [180.02833333333334, 276.36666666666673, 448.5203333333333, 822.0293333333333, 1234.2266666666667], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [340.14366666666666, 620.9216666666666, 1553.09, 2984.8033333333333, 4696.703333333334]}, "str": {"insert": [513.4739999999999, 1197.02, 2408.3233333333333, 4610.32, 7288.95], "insert_many": [421.36533333333335, 834.2423333333332, 839.7793333333333, 1032.71, 1250.5266666666666], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [306.90166666666664, 511.60066666666665, 880.6006666666667, 1781.83, 2723.566666666667], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [430.34566666666666, 848.4443333333334, 2139.1966666666663, 4046.866666666667, 6390.360000000001]}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/str_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/str_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/str_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/str_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/str_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/str_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/str_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/str_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/str_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/str_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/str_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/str_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/usize_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/usize_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/usize_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/usize_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/usize_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/usize_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/usize_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/usize_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/usize_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/usize_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec/usize_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec/usize_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/data.json: -------------------------------------------------------------------------------- 1 | {"cm": {"ptr": {"insert": [1805.6666666666667, 2194.6666666666665, 3182.0, 4675.666666666667, 7563.333333333333], "insert_many": [470.0, 599.6666666666666, 653.3333333333334, 757.0, 914.6666666666666], "insert_many_par": [626.0, 373.0, 379.0, 448.3333333333333, 1710.6666666666667], "get": [84.0, 133.66666666666666, 232.0, 404.6666666666667, 805.3333333333334], "get_parallel": [11.699999999999998, 21.463333333333335, 36.39, 65.47, 127.16333333333334], "remove": [1726.0, 2096.0, 3092.0, 4745.333333333333, 10201.666666666666]}, "str": {"insert": [23851.0, 24747.666666666668, 39162.0, 50812.0, 74889.0], "insert_many": [3434.0, 3894.0, 7303.0, 9434.333333333334, 12423.0], "insert_many_par": [1021.0, 1128.3333333333333, 1650.3333333333333, 1997.0, 3699.3333333333335], "get": [240.66666666666666, 391.6666666666667, 783.6666666666666, 1534.6666666666667, 2662.3333333333335], "get_parallel": [39.49, 61.85666666666666, 127.17999999999999, 247.20000000000002, 431.35999999999996], "remove": [23972.333333333332, 24469.0, 39856.333333333336, 52329.666666666664, 82125.66666666667]}}, "cow": {"ptr": {"insert": [302.3333333333333, 439.3333333333333, 770.3333333333334, 1413.0, 2624.6666666666665], "insert_many": [282.0, 478.6666666666667, 825.0, 1414.3333333333333, 2798.3333333333335], "insert_many_par": [526.6666666666666, 427.0, 457.3333333333333, 591.6666666666666, 946.0], "get": [86.66666666666667, 140.0, 241.0, 414.0, 847.3333333333334], "get_parallel": [11.126666666666667, 21.063333333333333, 36.07666666666666, 63.81, 131.55333333333337], "remove": [281.6666666666667, 435.0, 770.0, 1459.3333333333333, 2608.6666666666665]}, "str": {"insert": [563.3333333333334, 877.0, 1808.0, 3238.0, 5505.0], "insert_many": [463.6666666666667, 902.3333333333334, 1776.6666666666667, 3231.0, 5666.666666666667], "insert_many_par": [972.6666666666666, 1288.0, 1829.3333333333333, 2324.3333333333335, 3200.3333333333335], "get": [240.33333333333334, 394.3333333333333, 777.0, 1550.3333333333333, 2759.3333333333335], "get_parallel": [39.583333333333336, 61.843333333333334, 127.89, 250.21, 439.7833333333333], "remove": [496.3333333333333, 843.0, 1738.6666666666667, 3134.6666666666665, 5227.0]}}, "hm": {"ptr": {"insert": [41.333333333333336, 46.0, 63.333333333333336, 66.66666666666667, 155.0], "insert_many": [144.0, 116.0, 108.0, 160.66666666666666, 200.66666666666666], "insert_many_par": [330.0, 133.33333333333334, 114.0, 169.0, 210.0], "get": [31.0, 35.0, 46.333333333333336, 95.0, 145.33333333333334], "get_parallel": [7.52, 7.946666666666666, 10.72, 22.08, 31.98333333333333], "remove": [43.0, 45.0, 63.666666666666664, 104.66666666666667, 198.33333333333334]}, "str": {"insert": [129.66666666666666, 145.33333333333334, 212.33333333333334, 321.3333333333333, 445.0], "insert_many": [384.3333333333333, 350.0, 474.3333333333333, 786.6666666666666, 865.0], "insert_many_par": [592.3333333333334, 394.0, 509.0, 805.0, 890.6666666666666], "get": [114.33333333333333, 130.33333333333334, 220.66666666666666, 285.0, 380.6666666666667], "get_parallel": [22.28, 24.066666666666663, 35.830000000000005, 44.050000000000004, 54.78333333333333], "remove": [201.33333333333334, 192.66666666666666, 375.3333333333333, 549.3333333333334, 705.3333333333334]}}, "btm": {"ptr": {"insert": [133.66666666666666, 176.66666666666666, 257.0, 477.3333333333333, 735.0], "insert_many": [138.66666666666666, 165.33333333333334, 233.66666666666666, 377.6666666666667, 631.3333333333334], "insert_many_par": [275.6666666666667, 161.66666666666666, 171.66666666666666, 226.33333333333334, 288.6666666666667], "get": [81.0, 138.0, 211.0, 406.3333333333333, 661.3333333333334], "get_parallel": [13.11, 23.703333333333333, 34.669999999999995, 67.02333333333333, 101.89999999999999], "remove": [203.0, 217.0, 282.6666666666667, 535.6666666666666, 782.0]}, "str": {"insert": [272.3333333333333, 429.0, 828.6666666666666, 1514.3333333333333, 2404.0], "insert_many": [264.6666666666667, 386.3333333333333, 698.0, 1308.3333333333333, 2107.6666666666665], "insert_many_par": [416.0, 357.3333333333333, 544.0, 755.6666666666666, 1010.0], "get": [188.0, 331.6666666666667, 653.0, 1269.6666666666667, 2105.0], "get_parallel": [35.60666666666666, 60.92333333333334, 124.32333333333334, 238.99666666666667, 380.00666666666666], "remove": [297.3333333333333, 407.6666666666667, 839.0, 1489.6666666666667, 2399.0]}}, "oc": {"ptr": {"insert": [378.2906666666667, 990.7156666666666, 1670.28, 3104.633333333333, 4971.01], "insert_many": [304.3813333333333, 720.8186666666667, 629.003, 776.0589999999999, 1059.54], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [179.89033333333336, 276.5543333333333, 443.67833333333334, 814.9166666666666, 1233.19], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [340.2233333333333, 618.7040000000001, 1541.12, 2975.023333333333, 4687.443333333334]}, "str": {"insert": [512.1233333333333, 1207.33, 2389.646666666667, 4589.92, 7315.713333333333], "insert_many": [424.06733333333335, 845.5993333333334, 835.8326666666667, 1031.8933333333334, 1251.9466666666665], "insert_many_par": [0.0, 0.0, 0.0, 0.0, 0.0], "get": [306.37166666666667, 507.657, 870.7186666666666, 1775.2866666666666, 2735.9466666666667], "get_parallel": [0.0, 0.0, 0.0, 0.0, 0.0], "remove": [427.723, 844.677, 2121.7566666666667, 4032.5, 6417.763333333333]}}} -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/str_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/str_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/str_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/str_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/str_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/str_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/str_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/str_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/str_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/str_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/str_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/str_remove.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/usize_get.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/usize_get.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/usize_get_parallel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/usize_get_parallel.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert_many.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert_many.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert_many_par.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/usize_insert_many_par.png -------------------------------------------------------------------------------- /bench/charts/intel_corei7-8550U_arrayvec_compact/usize_remove.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/estokes/immutable-chunkmap/67bdff125681b8416d95ce2062f6d932c60f8f30/bench/charts/intel_corei7-8550U_arrayvec_compact/usize_remove.png -------------------------------------------------------------------------------- /bench/compare.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python3 2 | 3 | import json 4 | import argparse 5 | 6 | def load_results(path): 7 | with open(path, 'r') as f: 8 | return json.load(f) 9 | 10 | def compare(k, res0, res1, cmp0, cmp1): 11 | dat0 = res0[cmp0] 12 | dat1 = res1[cmp1] 13 | n = 1000; 14 | for i in range(0, 5): 15 | d0 = dat0[k] 16 | d1 = dat1[k] 17 | insert = d1['insert'][i] / d0['insert'][i] 18 | insert_many = d1['insert_many'][i] / d0['insert_many'][i] 19 | insert_many_par = d1['insert_many_par'][i] / d0['insert_many_par'][i] 20 | get = d1['get'][i] / d0['get'][i] 21 | get_parallel = d1['get_parallel'][i] / d0['get_parallel'][i] 22 | remove = d1['remove'][i] / d0['remove'][i] 23 | print(f'{n:8},{insert:.2f},{insert_many:.2f},{insert_many_par:.2f},{get:.2f},{get_parallel:.2f},{remove:.2f}') 24 | n = n*10 25 | 26 | parser = argparse.ArgumentParser(description = "compare benchmarks") 27 | parser.add_argument('data', nargs=2, metavar = 'FILE') 28 | parser.add_argument('compare', nargs=2, choices = ['cm', 'cow', 'hm', 'btm', 'oc']) 29 | args = parser.parse_args() 30 | 31 | res0 = load_results(args.data[0]) 32 | res1 = load_results(args.data[1]) 33 | 34 | compare('ptr', res0, res1, args.compare[0], args.compare[1]) 35 | compare('str', res0, res1, args.compare[0], args.compare[1]) 36 | -------------------------------------------------------------------------------- /bench/src/main.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | use arcstr::ArcStr; 3 | use std::{ 4 | env, mem, thread, 5 | borrow::Borrow, 6 | cmp::{max, min}, 7 | collections::{BTreeMap, HashMap}, 8 | hash::Hash, 9 | iter::FromIterator, 10 | marker::PhantomData, 11 | sync::{Arc, RwLock, mpsc::channel}, 12 | time::{Duration, Instant}, 13 | }; 14 | use immutable_chunkmap::map::{Map, DEFAULT_SIZE}; 15 | use crate::utils::Rand; 16 | 17 | const MIN_ITER: usize = 1000000; 18 | const MAX_ADD: usize = 100_000; 19 | 20 | trait Collection { 21 | fn new() -> Self; 22 | fn insert_many(&mut self, chunk: Vec<(K, V)>); 23 | fn insert(&mut self, k: K, v: V) -> Option; 24 | fn remove(&mut self, k: &Q) -> Option where Q: Ord + Hash + Clone, K: Borrow; 25 | fn get(&self, k: &Q) -> Option<&V> where Q: Ord + Hash + Clone, K: Borrow; 26 | fn merge_into(&mut self, from: Self); 27 | fn len(&self) -> usize; 28 | } 29 | 30 | fn chunk(keys: &Vec, vals: &Vec, denom: usize) -> Vec> 31 | where K: Clone, 32 | V: Clone 33 | { 34 | let csize = max(1, keys.len() / denom); 35 | let mut chunks = vec![]; 36 | let mut cur = vec![]; 37 | for (k, v) in keys.into_iter().zip(vals.into_iter()) { 38 | cur.push((k.clone(), v.clone())); 39 | if cur.len() >= csize { 40 | chunks.push(mem::replace(&mut cur, vec![])); 41 | } 42 | } 43 | if cur.len() > 0 { 44 | chunks.push(cur); 45 | } 46 | chunks 47 | } 48 | 49 | #[derive(Clone)] 50 | struct Bench(Arc>, PhantomData, PhantomData); 51 | 52 | impl Bench 53 | where K: Hash + Ord + Clone + Rand + Send + Sync + 'static, 54 | V: Hash + Ord + Clone + Rand + Send + Sync + 'static, 55 | C: Collection + Send + Sync + 'static, 56 | { 57 | fn bench_insert_many( 58 | keys: &Vec, 59 | vals: &Vec 60 | ) -> (Self, Duration) { 61 | let mut m = C::new(); 62 | let chunks = chunk(keys, vals, 100); 63 | let begin = Instant::now(); 64 | for chunk in chunks { 65 | m.insert_many(chunk); 66 | } 67 | (Bench(Arc::new(RwLock::new(m)), PhantomData, PhantomData), begin.elapsed()) 68 | } 69 | 70 | fn bench_insert_many_par( 71 | keys: &Vec, 72 | vals: &Vec, 73 | n: usize 74 | ) -> (Self, Duration) { 75 | let mut chunks = chunk(keys, vals, n); 76 | let len = chunks.len(); 77 | let (tx, rx) = channel(); 78 | let begin = Instant::now(); 79 | let mine = chunks.pop().unwrap(); 80 | for chunk in chunks { 81 | let tx = tx.clone(); 82 | thread::spawn(move || { 83 | let mut t = C::new(); 84 | t.insert_many(chunk); 85 | tx.send(t).unwrap(); 86 | }); 87 | } 88 | mem::drop(tx); 89 | let mut t = C::new(); 90 | let mut i = 0; 91 | t.insert_many(mine); 92 | while let Ok(part) = rx.recv() { 93 | t.merge_into(part); 94 | i += 1; 95 | } 96 | assert_eq!(i, len - 1); 97 | assert_eq!(t.len(), keys.len()); 98 | (Bench(Arc::new(RwLock::new(t)), PhantomData, PhantomData), 99 | begin.elapsed()) 100 | } 101 | 102 | fn bench_remove(&self, keys: &Arc>) -> Duration { 103 | let begin = Instant::now(); 104 | let mut m = self.0.write().unwrap(); 105 | for i in 0..(min(keys.len() / 10, MAX_ADD)) { 106 | m.remove(&keys[i]).unwrap(); 107 | } 108 | begin.elapsed() 109 | } 110 | 111 | fn bench_insert(&self, keys: &Vec, vals: &Vec) -> Duration { 112 | let len = min(keys.len() / 10, MAX_ADD); 113 | let chunk = 114 | keys[0..len].into_iter() 115 | .zip(vals[0..len].into_iter()) 116 | .map(|(k, v)| (k.clone(), v.clone())) 117 | .collect::>(); 118 | let mut m = self.0.write().unwrap(); 119 | let begin = Instant::now(); 120 | for (k, v) in chunk { 121 | m.insert(k, v); 122 | } 123 | begin.elapsed() 124 | } 125 | 126 | fn bench_get(&self, keys: &Arc>, n: usize) -> Duration { 127 | let begin = Instant::now(); 128 | let iter = max(MIN_ITER, keys.len()); 129 | let mut threads = vec![]; 130 | for n in 0..n { 131 | let (m, keys) = (self.0.clone(), keys.clone()); 132 | threads.push(thread::spawn(move || { 133 | let m = m.read().unwrap(); 134 | let mut r = 0; 135 | while r < iter { 136 | let mut j = n; 137 | while j < keys.len() && r < iter { 138 | m.get(&keys[j]).unwrap(); 139 | j += n; 140 | r += 1; 141 | } 142 | } 143 | })) 144 | } 145 | for th in threads { 146 | th.join().unwrap(); 147 | } 148 | begin.elapsed() 149 | } 150 | 151 | fn bench_get_seq(&self, keys: &Arc>) -> Duration { 152 | let begin = Instant::now(); 153 | let m = self.0.read().unwrap(); 154 | let mut i = 0; 155 | while i < MIN_ITER { 156 | for k in keys.iter() { 157 | i += 1; 158 | m.get(k).unwrap(); 159 | } 160 | } 161 | begin.elapsed() 162 | } 163 | 164 | pub(crate) fn run(size: usize) { 165 | let n = num_cpus::get(); 166 | let keys = Arc::new(utils::randvec::(n, size)); 167 | let vals = Arc::new(utils::randvec::(n, size)); 168 | let (m, insertmp) = Self::bench_insert_many_par(&*keys, &*vals, n); 169 | let rm = m.bench_remove(&keys); 170 | let insert = m.bench_insert(&*keys, &*vals); 171 | let (m, insertm) = Self::bench_insert_many(&*keys, &*vals); 172 | let get_par = m.bench_get(&keys, n); 173 | let get = m.bench_get_seq(&keys); 174 | let iter = max(MIN_ITER, size); 175 | let iterp = max(MIN_ITER * n, size * n); 176 | println!( 177 | "{},{:.0},{:.0},{:.0},{:.0},{:.2},{:.0}", 178 | size, 179 | utils::to_ns_per(insert, min(size / 10, MAX_ADD)), 180 | utils::to_ns_per(insertm, size), 181 | utils::to_ns_per(insertmp, size), 182 | utils::to_ns_per(get, iter), 183 | utils::to_ns_per(get_par, iterp), 184 | utils::to_ns_per(rm, min(size / 10, MAX_ADD)) 185 | ); 186 | } 187 | } 188 | 189 | impl Collection for HashMap 190 | where K: Hash + Ord + Clone + Rand + Send + Sync, 191 | V: Hash + Ord + Clone + Rand + Send + Sync 192 | { 193 | fn new() -> Self { HashMap::new() } 194 | fn insert_many(&mut self, chunk: Vec<(K, V)>) { 195 | for (k, v) in chunk { 196 | self.insert(k, v); 197 | } 198 | } 199 | fn insert(&mut self, k: K, v: V) -> Option { self.insert(k, v) } 200 | fn remove(&mut self, k: &Q) -> Option where Q: Ord + Hash + Clone, K: Borrow { 201 | self.remove(k) 202 | } 203 | fn get(&self, k: &Q) -> Option<&V> where Q: Ord + Hash + Clone, K: Borrow { 204 | self.get(k) 205 | } 206 | fn merge_into(&mut self, other: HashMap) { 207 | self.extend(other.into_iter()); 208 | } 209 | fn len(&self) -> usize { self.len() } 210 | } 211 | 212 | impl Collection for BTreeMap 213 | where K: Hash + Ord + Clone + Rand + Send + Sync, 214 | V: Hash + Ord + Clone + Rand + Send + Sync 215 | { 216 | fn new() -> Self { BTreeMap::new() } 217 | fn insert_many(&mut self, chunk: Vec<(K, V)>) { 218 | for (k, v) in chunk { 219 | self.insert(k, v); 220 | } 221 | } 222 | fn insert(&mut self, k: K, v: V) -> Option { self.insert(k, v) } 223 | fn remove(&mut self, k: &Q) -> Option where Q: Ord + Hash + Clone, K: Borrow { 224 | self.remove(k) 225 | } 226 | fn get(&self, k: &Q) -> Option<&V> where Q: Ord + Hash + Clone, K: Borrow { 227 | self.get(k) 228 | } 229 | fn merge_into(&mut self, other: BTreeMap) { 230 | self.extend(other.into_iter()) 231 | } 232 | fn len(&self) -> usize { self.len() } 233 | } 234 | 235 | struct CMWrap(Map); 236 | 237 | impl Collection for CMWrap 238 | where K: Hash + Ord + Clone + Rand + Send + Sync, 239 | V: Hash + Ord + Clone + Rand + Send + Sync 240 | { 241 | fn new() -> Self { CMWrap(Map::new()) } 242 | fn insert_many(&mut self, chunk: Vec<(K, V)>) { self.0 = self.0.insert_many(chunk) } 243 | fn insert(&mut self, k: K, v: V) -> Option { 244 | let (m, prev) = self.0.insert(k, v); 245 | self.0 = m; 246 | prev 247 | } 248 | fn remove(&mut self, k: &Q) -> Option where Q: Ord + Hash + Clone, K: Borrow { 249 | let (m, prev) = self.0.remove(k); 250 | self.0 = m; 251 | prev 252 | } 253 | fn get(&self, k: &Q) -> Option<&V> where Q: Ord + Hash + Clone, K: Borrow { 254 | self.0.get(k) 255 | } 256 | fn merge_into(&mut self, other: CMWrap) { 257 | self.0 = self.0.union(&other.0, |_, _, v| Some(v.clone())) 258 | } 259 | fn len(&self) -> usize { self.0.len() } 260 | } 261 | 262 | struct COWrap(Map); 263 | 264 | impl Collection for COWrap 265 | where K: Hash + Ord + Clone + Rand + Send + Sync, 266 | V: Hash + Ord + Clone + Rand + Send + Sync 267 | { 268 | fn new() -> Self { COWrap(Map::new()) } 269 | fn insert_many(&mut self, chunk: Vec<(K, V)>) { 270 | for (k, v) in chunk { 271 | self.0.insert_cow(k, v); 272 | } 273 | } 274 | fn insert(&mut self, k: K, v: V) -> Option { 275 | self.0.insert_cow(k, v) 276 | } 277 | fn remove(&mut self, k: &Q) -> Option where Q: Ord + Hash + Clone, K: Borrow { 278 | self.0.remove_cow(k) 279 | } 280 | fn get(&self, k: &Q) -> Option<&V> where Q: Ord + Hash + Clone, K: Borrow { 281 | self.0.get(k) 282 | } 283 | fn merge_into(&mut self, other: COWrap) { 284 | self.0 = self.0.union(&other.0, |_, _, v| Some(v.clone())) 285 | } 286 | fn len(&self) -> usize { self.0.len() } 287 | } 288 | 289 | fn usage() { 290 | println!("usage: ") 291 | } 292 | 293 | type S = ArcStr; 294 | type P = usize; 295 | 296 | fn main() { 297 | let args = Vec::from_iter(env::args()); 298 | if args.len() != 4 { usage() } 299 | else { 300 | let size = args[3].parse::().unwrap(); 301 | match (args[1].as_ref(), args[2].as_ref()) { 302 | ("cm", "ptr") => Bench::, P, P>::run(size), 303 | ("cm", "str") => Bench::, S, S>::run(size), 304 | ("cmS", "ptr") => Bench::, P, P>::run(size), 305 | ("cmS", "str") => Bench::, S, S>::run(size), 306 | ("cmL", "ptr") => Bench::, P, P>::run(size), 307 | ("cmL", "str") => Bench::, S, S>::run(size), 308 | ("cow", "ptr") => Bench::, P, P>::run(size), 309 | ("cow", "str") => Bench::, S, S>::run(size), 310 | ("cowS", "ptr") => Bench::, P, P>::run(size), 311 | ("cowS", "str") => Bench::, S, S>::run(size), 312 | ("cowL", "ptr") => Bench::, P, P>::run(size), 313 | ("cowL", "str") => Bench::, S, S>::run(size), 314 | ("btm", "ptr") => Bench::, P, P>::run(size), 315 | ("btm", "str") => Bench::, S, S>::run(size), 316 | ("hm", "ptr") => Bench::, P, P>::run(size), 317 | ("hm", "str") => Bench::, S, S>::run(size), 318 | _ => usage() 319 | } 320 | } 321 | } 322 | -------------------------------------------------------------------------------- /bench/src/utils.rs: -------------------------------------------------------------------------------- 1 | use rand::Rng; 2 | use arcstr::ArcStr; 3 | use smallvec::SmallVec; 4 | use std::{ 5 | time::Duration, 6 | sync::{Arc, mpsc::channel}, 7 | collections::HashSet, 8 | hash::Hash, 9 | iter::FromIterator, 10 | thread, mem, 11 | }; 12 | 13 | pub(crate) const STRSIZE: usize = 32; 14 | 15 | pub(crate) trait Rand: Sized { 16 | fn rand(r: &mut R) -> Self; 17 | } 18 | 19 | impl Rand for (T, U) { 20 | fn rand(r: &mut R) -> Self { 21 | (T::rand(r), U::rand(r)) 22 | } 23 | } 24 | 25 | impl Rand for SmallVec<[u8; STRSIZE]> { 26 | fn rand(r: &mut R) -> Self { 27 | let mut v = SmallVec::<[u8; STRSIZE]>::new(); 28 | for _ in 0..STRSIZE { 29 | v.push(r.gen()) 30 | } 31 | v 32 | } 33 | } 34 | 35 | impl Rand for String { 36 | fn rand(r: &mut R) -> Self { 37 | let mut s = String::new(); 38 | for _ in 0..STRSIZE { 39 | s.push(r.gen()) 40 | } 41 | s 42 | } 43 | } 44 | 45 | impl Rand for ArcStr { 46 | fn rand(r: &mut R) -> Self { 47 | let mut s = String::new(); 48 | for _ in 0..STRSIZE { 49 | s.push(r.gen()) 50 | } 51 | ArcStr::from(&s) 52 | } 53 | } 54 | 55 | impl Rand for Vec { 56 | fn rand(r: &mut R) -> Self { 57 | let mut s: Vec = Vec::with_capacity(STRSIZE); 58 | for _ in 0..STRSIZE { 59 | s.push(r.gen()) 60 | } 61 | s 62 | } 63 | } 64 | 65 | impl Rand for Arc { 66 | fn rand(r: &mut R) -> Self { 67 | let s = ::rand(r); 68 | Arc::from(s.as_str()) 69 | } 70 | } 71 | 72 | impl Rand for Arc { 73 | fn rand(r: &mut R) -> Self { 74 | Arc::new(::rand(r)) 75 | } 76 | } 77 | 78 | impl Rand for i32 { 79 | fn rand(r: &mut R) -> Self { 80 | r.gen() 81 | } 82 | } 83 | 84 | impl Rand for usize { 85 | fn rand(r: &mut R) -> Self { 86 | r.gen() 87 | } 88 | } 89 | 90 | pub(crate) fn random() -> T { 91 | let mut rng = rand::thread_rng(); 92 | T::rand(&mut rng) 93 | } 94 | 95 | pub(crate) fn randvec(n: usize, len: usize) -> Vec 96 | where T: Ord + Clone + Hash + Rand + Send + 'static 97 | { 98 | let csize = len / n; 99 | let (tx, rx) = channel(); 100 | for _ in 0..n - 1 { 101 | let tx = tx.clone(); 102 | thread::spawn(move || { 103 | let mut v: HashSet = HashSet::with_capacity(csize); 104 | while v.len() < csize { 105 | v.insert(random()); 106 | } 107 | tx.send(v).unwrap() 108 | }); 109 | } 110 | mem::drop(tx); 111 | let mut v: HashSet = HashSet::with_capacity(len); 112 | while v.len() < csize { 113 | v.insert(random()); 114 | } 115 | while let Ok(c) = rx.recv() { 116 | v.extend(c.into_iter()) 117 | } 118 | while v.len() < len { 119 | v.insert(random()); 120 | } 121 | Vec::from_iter(v.into_iter()) 122 | } 123 | 124 | #[allow(dead_code)] 125 | pub(crate) fn to_ms(t: Duration) -> u64 { 126 | t.as_secs() * 1000 + ((t.subsec_nanos() / 1000000) as u64) 127 | } 128 | 129 | #[allow(dead_code)] 130 | pub(crate) fn to_us(t: Duration) -> u64 { 131 | t.as_secs() * 1000000 + ((t.subsec_nanos() / 1000) as u64) 132 | } 133 | 134 | pub(crate) fn to_ns(t: Duration) -> u64 { 135 | t.as_secs() * 1000000000 + (t.subsec_nanos() as u64) 136 | } 137 | 138 | pub(crate) fn to_ns_per(t: Duration, n: usize) -> f64 { 139 | (to_ns(t) as f64) / (n as f64) 140 | } 141 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 90 2 | hard_tabs = false 3 | tab_spaces = 4 4 | newline_style = "Auto" 5 | use_small_heuristics = "Default" 6 | indent_style = "Block" 7 | wrap_comments = false 8 | comment_width = 80 9 | normalize_comments = false 10 | license_template_path = "" 11 | format_strings = false 12 | format_macro_matchers = false 13 | format_macro_bodies = true 14 | empty_item_single_line = true 15 | struct_lit_single_line = true 16 | fn_single_line = false 17 | where_single_line = false 18 | imports_indent = "Block" 19 | imports_layout = "Mixed" 20 | merge_imports = false 21 | reorder_imports = true 22 | reorder_modules = true 23 | reorder_impl_items = false 24 | type_punctuation_density = "Wide" 25 | space_before_colon = false 26 | space_after_colon = true 27 | spaces_around_ranges = false 28 | binop_separator = "Front" 29 | remove_nested_parens = true 30 | combine_control_expr = true 31 | struct_field_align_threshold = 0 32 | match_arm_blocks = true 33 | force_multiline_blocks = false 34 | fn_args_density = "Tall" 35 | brace_style = "SameLineWhere" 36 | control_brace_style = "AlwaysSameLine" 37 | trailing_semicolon = true 38 | trailing_comma = "Vertical" 39 | match_block_trailing_comma = false 40 | blank_lines_upper_bound = 1 41 | blank_lines_lower_bound = 0 42 | edition = "2018" 43 | merge_derives = true 44 | use_try_shorthand = false 45 | use_field_init_shorthand = false 46 | force_explicit_abi = true 47 | condense_wildcard_suffixes = false 48 | color = "Auto" 49 | required_version = "0.99.4" 50 | unstable_features = false 51 | disable_all_formatting = false 52 | skip_children = false 53 | hide_parse_errors = false 54 | error_on_line_overflow = false 55 | error_on_unformatted = false 56 | report_todo = "Never" 57 | report_fixme = "Never" 58 | ignore = [] 59 | emit_mode = "Files" 60 | make_backup = false 61 | -------------------------------------------------------------------------------- /src/chunk.rs: -------------------------------------------------------------------------------- 1 | use arrayvec::ArrayVec; 2 | use alloc::{sync::Arc, vec::Vec}; 3 | use core::{ 4 | borrow::Borrow, 5 | cmp::{min, Ord, Ordering}, 6 | fmt::{self, Debug, Formatter}, 7 | iter, mem, 8 | ops::Deref, 9 | slice, 10 | }; 11 | 12 | #[derive(PartialEq)] 13 | pub(crate) enum Loc { 14 | InRight, 15 | InLeft, 16 | NotPresent(usize), 17 | Here(usize), 18 | } 19 | 20 | /* 21 | elts is a sorted array of pairs, increasing the SIZE has several effects; 22 | 23 | -- decreases the height of the tree for a given number of elements, 24 | decreasing the amount of indirection necessary to get to any given 25 | key. 26 | 27 | -- decreases the number of objects allocated on the heap each time a 28 | key is added or removed 29 | 30 | -- increases the size of each allocation 31 | 32 | -- icreases the overall amount of memory allocated for each change to 33 | the tree 34 | */ 35 | pub const DEFAULT_SIZE: usize = 512; 36 | 37 | pub(crate) enum UpdateChunk< 38 | Q: Ord, 39 | K: Ord + Clone + Borrow, 40 | V: Clone, 41 | D, 42 | const SIZE: usize, 43 | > { 44 | UpdateLeft(Vec<(Q, D)>), 45 | UpdateRight(Vec<(Q, D)>), 46 | Updated { 47 | elts: Chunk, 48 | update_left: Vec<(Q, D)>, 49 | update_right: Vec<(Q, D)>, 50 | overflow_right: Vec<(K, V)>, 51 | }, 52 | Removed { 53 | not_done: Vec<(Q, D)>, 54 | update_left: Vec<(Q, D)>, 55 | update_right: Vec<(Q, D)>, 56 | }, 57 | } 58 | 59 | pub(crate) enum Update, V: Clone, D, const SIZE: usize> 60 | { 61 | UpdateLeft(Q, D), 62 | UpdateRight(Q, D), 63 | Updated { 64 | elts: Chunk, 65 | overflow: Option<(K, V)>, 66 | previous: Option, 67 | }, 68 | } 69 | 70 | pub(crate) enum MutUpdate, V: Clone, D> { 71 | UpdateLeft(Q, D), 72 | UpdateRight(Q, D), 73 | Updated { 74 | overflow: Option<(K, V)>, 75 | previous: Option, 76 | }, 77 | } 78 | 79 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] 80 | pub(crate) struct ChunkInner { 81 | keys: ArrayVec, 82 | vals: ArrayVec, 83 | } 84 | 85 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] 86 | pub(crate) struct Chunk(Arc>); 87 | 88 | impl Deref for Chunk { 89 | type Target = ChunkInner; 90 | 91 | fn deref(&self) -> &Self::Target { 92 | &*self.0 93 | } 94 | } 95 | 96 | impl Debug for Chunk 97 | where 98 | K: Debug, 99 | V: Debug, 100 | { 101 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 102 | f.debug_map().entries(self.into_iter()).finish() 103 | } 104 | } 105 | 106 | impl Chunk 107 | where 108 | K: Ord + Clone, 109 | V: Clone, 110 | { 111 | pub(crate) fn singleton(k: K, v: V) -> Self { 112 | let mut t = Chunk::empty(); 113 | let inner = Arc::make_mut(&mut t.0); 114 | inner.keys.push(k); 115 | inner.vals.push(v); 116 | t 117 | } 118 | 119 | pub(crate) fn empty() -> Self { 120 | Chunk(Arc::new(ChunkInner { 121 | keys: ArrayVec::new(), 122 | vals: ArrayVec::new(), 123 | })) 124 | } 125 | 126 | pub(crate) fn create_with(chunk: Vec<(Q, D)>, f: &mut F) -> Self 127 | where 128 | Q: Ord, 129 | K: Borrow, 130 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 131 | { 132 | let mut t = Chunk::empty(); 133 | let inner = Arc::make_mut(&mut t.0); 134 | for (k, v) in chunk.into_iter().filter_map(|(q, d)| f(q, d, None)) { 135 | inner.keys.push(k); 136 | inner.vals.push(v); 137 | } 138 | t 139 | } 140 | 141 | pub(crate) fn get_local(&self, k: &Q) -> Option 142 | where 143 | K: Borrow, 144 | { 145 | match self.keys.binary_search_by_key(&k, |k| k.borrow()) { 146 | Ok(i) => Some(i), 147 | Err(_) => None, 148 | } 149 | } 150 | 151 | pub(crate) fn get(&self, k: &Q) -> Loc 152 | where 153 | K: Borrow, 154 | { 155 | let len = self.len(); 156 | if len == 0 { 157 | Loc::NotPresent(0) 158 | } else { 159 | let first = k.cmp(&self.keys[0].borrow()); 160 | let last = k.cmp(&self.keys[len - 1].borrow()); 161 | match (first, last) { 162 | (Ordering::Equal, _) => Loc::Here(0), 163 | (_, Ordering::Equal) => Loc::Here(len - 1), 164 | (Ordering::Less, _) => Loc::InLeft, 165 | (_, Ordering::Greater) => Loc::InRight, 166 | (Ordering::Greater, Ordering::Less) => { 167 | match self.keys.binary_search_by_key(&k, |k| k.borrow()) { 168 | Result::Ok(i) => Loc::Here(i), 169 | Result::Err(i) => Loc::NotPresent(i), 170 | } 171 | } 172 | } 173 | } 174 | } 175 | 176 | // invariant: chunk is sorted and deduped 177 | pub(crate) fn update_chunk( 178 | &self, 179 | chunk: Vec<(Q, D)>, 180 | leaf: bool, 181 | f: &mut F, 182 | ) -> UpdateChunk 183 | where 184 | Q: Ord, 185 | K: Borrow, 186 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 187 | { 188 | assert!(chunk.len() <= SIZE && chunk.len() > 0 && self.len() > 0); 189 | let full = !leaf || self.len() >= SIZE; 190 | let in_left = self.get(&chunk[chunk.len() - 1].0) == Loc::InLeft; 191 | let in_right = self.get(&chunk[0].0) == Loc::InRight; 192 | if full && in_left { 193 | UpdateChunk::UpdateLeft(chunk) 194 | } else if full && in_right { 195 | UpdateChunk::UpdateRight(chunk) 196 | } else if leaf && (in_left || in_right) { 197 | let iter = chunk.into_iter().filter_map(|(q, d)| f(q, d, None)); 198 | let mut overflow_right = Vec::new(); 199 | let mut elts = Chunk::empty(); 200 | let inner = Arc::make_mut(&mut elts.0); 201 | if in_right { 202 | inner.clone_from(self); 203 | for (k, v) in iter { 204 | if inner.keys.len() < SIZE { 205 | inner.keys.push(k); 206 | inner.vals.push(v); 207 | } else { 208 | overflow_right.push((k, v)); 209 | } 210 | } 211 | } else { 212 | for (k, v) in iter { 213 | if inner.keys.len() < SIZE { 214 | inner.keys.push(k); 215 | inner.vals.push(v); 216 | } else { 217 | overflow_right.push((k, v)); 218 | } 219 | } 220 | for (k, v) in self.keys.iter().cloned().zip(self.vals.iter().cloned()) { 221 | if inner.keys.len() < SIZE { 222 | inner.keys.push(k); 223 | inner.vals.push(v); 224 | } else { 225 | overflow_right.push((k, v)); 226 | } 227 | } 228 | } 229 | UpdateChunk::Updated { 230 | elts, 231 | update_left: Vec::new(), 232 | update_right: Vec::new(), 233 | overflow_right, 234 | } 235 | } else { 236 | #[inline(always)] 237 | fn copy_up_to( 238 | t: &Chunk, 239 | elts: &mut ChunkInner, 240 | overflow_right: &mut Vec<(K, V)>, 241 | m: &mut usize, 242 | i: usize, 243 | ) where 244 | K: Ord + Clone, 245 | V: Clone, 246 | { 247 | let n = min(i - *m, SIZE - elts.keys.len()); 248 | if n > 0 { 249 | elts.keys.extend(t.keys[*m..*m + n].iter().cloned()); 250 | elts.vals.extend(t.vals[*m..*m + n].iter().cloned()); 251 | *m += n; 252 | } 253 | if *m < i { 254 | overflow_right.extend( 255 | t.keys.as_slice()[*m..i] 256 | .iter() 257 | .cloned() 258 | .zip(t.vals.as_slice()[*m..i].iter().cloned()), 259 | ); 260 | *m = i; 261 | } 262 | } 263 | // invariant: don't cross the streams. 264 | let mut not_done = Vec::new(); 265 | let mut update_left = Vec::new(); 266 | let mut update_right = Vec::new(); 267 | let mut overflow_right = Vec::new(); 268 | let mut m = 0; 269 | let mut elts = Chunk::empty(); 270 | let inner = Arc::make_mut(&mut elts.0); 271 | let mut chunk = chunk.into_iter(); 272 | loop { 273 | if m == self.len() && inner.keys.len() == 0 { 274 | not_done.extend(chunk); 275 | break; 276 | } 277 | match chunk.next() { 278 | None => { 279 | copy_up_to(self, inner, &mut overflow_right, &mut m, self.len()); 280 | break; 281 | } 282 | Some((q, d)) => { 283 | match self.get(&q) { 284 | Loc::Here(i) => { 285 | copy_up_to(self, inner, &mut overflow_right, &mut m, i); 286 | let r = f(q, d, Some((&self.keys[i], &self.vals[i]))); 287 | if let Some((k, v)) = r { 288 | if inner.keys.len() < SIZE { 289 | inner.keys.push(k); 290 | inner.vals.push(v); 291 | } else { 292 | overflow_right.push((k, v)) 293 | } 294 | } 295 | // self[i] was replaced or deleted, skip it 296 | m += 1; 297 | } 298 | Loc::NotPresent(i) => { 299 | copy_up_to(self, inner, &mut overflow_right, &mut m, i); 300 | if let Some((k, v)) = f(q, d, None) { 301 | if inner.keys.len() < SIZE { 302 | inner.keys.push(k); 303 | inner.vals.push(v); 304 | } else { 305 | overflow_right.push((k, v)); 306 | } 307 | } 308 | } 309 | Loc::InLeft => { 310 | if leaf && inner.keys.len() < SIZE { 311 | if let Some((k, v)) = f(q, d, None) { 312 | inner.keys.push(k); 313 | inner.vals.push(v); 314 | } 315 | } else { 316 | update_left.push((q, d)) 317 | } 318 | } 319 | Loc::InRight => { 320 | let len = self.len(); 321 | copy_up_to(self, inner, &mut overflow_right, &mut m, len); 322 | if leaf && inner.keys.len() < SIZE { 323 | let iter = iter::once((q, d)) 324 | .chain(chunk) 325 | .filter_map(|(q, d)| f(q, d, None)); 326 | for (k, v) in iter { 327 | if inner.keys.len() < SIZE { 328 | inner.keys.push(k); 329 | inner.vals.push(v); 330 | } else { 331 | overflow_right.push((k, v)); 332 | } 333 | } 334 | } else { 335 | update_right.push((q, d)); 336 | update_right.extend(chunk); 337 | } 338 | break; 339 | } 340 | } 341 | } 342 | } 343 | } 344 | if elts.len() > 0 { 345 | assert_eq!(not_done.len(), 0); 346 | UpdateChunk::Updated { 347 | elts, 348 | update_left, 349 | update_right, 350 | overflow_right, 351 | } 352 | } else { 353 | assert_eq!(overflow_right.len(), 0); 354 | UpdateChunk::Removed { 355 | not_done, 356 | update_left, 357 | update_right, 358 | } 359 | } 360 | } 361 | } 362 | 363 | pub(crate) fn update( 364 | &self, 365 | q: Q, 366 | d: D, 367 | leaf: bool, 368 | f: &mut F, 369 | ) -> Update 370 | where 371 | Q: Ord, 372 | K: Borrow, 373 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 374 | { 375 | match self.get(&q) { 376 | Loc::Here(i) => { 377 | let mut elts = Chunk::empty(); 378 | let inner = Arc::make_mut(&mut elts.0); 379 | inner.keys.extend(self.keys[0..i].iter().cloned()); 380 | inner.vals.extend(self.vals[0..i].iter().cloned()); 381 | if let Some((k, v)) = f(q, d, Some((&self.keys[i], &self.vals[i]))) { 382 | inner.keys.push(k); 383 | inner.vals.push(v); 384 | } 385 | if i + 1 < self.len() { 386 | inner 387 | .keys 388 | .extend(self.keys[i + 1..self.len()].iter().cloned()); 389 | inner 390 | .vals 391 | .extend(self.vals[i + 1..self.len()].iter().cloned()); 392 | } 393 | Update::Updated { 394 | elts, 395 | overflow: None, 396 | previous: Some(self.vals[i].clone()), 397 | } 398 | } 399 | Loc::NotPresent(i) => { 400 | let mut elts = Chunk::empty(); 401 | let inner = Arc::make_mut(&mut elts.0); 402 | inner.keys.extend(self.keys[0..i].iter().cloned()); 403 | inner.vals.extend(self.vals[0..i].iter().cloned()); 404 | let overflow = match f(q, d, None) { 405 | None => None, 406 | Some((k, v)) => { 407 | if inner.keys.len() == SIZE { 408 | let (ok, ov) = 409 | (inner.keys.pop().unwrap(), inner.vals.pop().unwrap()); 410 | inner.keys.push(k); 411 | inner.vals.push(v); 412 | Some((ok, ov)) 413 | } else { 414 | inner.keys.push(k); 415 | inner.vals.push(v); 416 | let mut iter = self.keys[i..self.len()] 417 | .iter() 418 | .cloned() 419 | .zip(self.vals[i..self.len()].iter().cloned()); 420 | loop { 421 | match iter.next() { 422 | None => break None, 423 | Some((k, v)) => { 424 | if inner.keys.len() < SIZE { 425 | inner.keys.push(k); 426 | inner.vals.push(v); 427 | } else { 428 | break Some((k, v)); 429 | } 430 | } 431 | } 432 | } 433 | } 434 | } 435 | }; 436 | Update::Updated { 437 | elts, 438 | overflow, 439 | previous: None, 440 | } 441 | } 442 | loc @ Loc::InLeft | loc @ Loc::InRight => { 443 | if !leaf || self.len() == SIZE { 444 | match loc { 445 | Loc::InLeft => Update::UpdateLeft(q, d), 446 | Loc::InRight => Update::UpdateRight(q, d), 447 | Loc::Here(..) | Loc::NotPresent(..) => unreachable!(), 448 | } 449 | } else { 450 | let mut elts = Chunk::empty(); 451 | let inner = Arc::make_mut(&mut elts.0); 452 | match loc { 453 | Loc::InLeft => { 454 | if let Some((k, v)) = f(q, d, None) { 455 | inner.keys.push(k); 456 | inner.vals.push(v); 457 | } 458 | inner.keys.extend(self.keys[0..self.len()].iter().cloned()); 459 | inner.vals.extend(self.vals[0..self.len()].iter().cloned()); 460 | } 461 | Loc::InRight => { 462 | inner.keys.extend(self.keys[0..self.len()].iter().cloned()); 463 | inner.vals.extend(self.vals[0..self.len()].iter().cloned()); 464 | if let Some((k, v)) = f(q, d, None) { 465 | inner.keys.push(k); 466 | inner.vals.push(v); 467 | } 468 | } 469 | _ => unreachable!("bug"), 470 | }; 471 | Update::Updated { 472 | elts, 473 | overflow: None, 474 | previous: None, 475 | } 476 | } 477 | } 478 | } 479 | } 480 | 481 | pub(crate) fn update_mut( 482 | &mut self, 483 | q: Q, 484 | d: D, 485 | leaf: bool, 486 | f: &mut F, 487 | ) -> MutUpdate 488 | where 489 | Q: Ord, 490 | K: Borrow, 491 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 492 | { 493 | match self.get(&q) { 494 | Loc::Here(i) => match f(q, d, Some((&self.keys[i], &self.vals[i]))) { 495 | Some((k, v)) => { 496 | let inner = Arc::make_mut(&mut self.0); 497 | inner.keys[i] = k; 498 | MutUpdate::Updated { 499 | overflow: None, 500 | previous: Some(mem::replace(&mut inner.vals[i], v)), 501 | } 502 | } 503 | None => { 504 | let inner = Arc::make_mut(&mut self.0); 505 | inner.keys.remove(i); 506 | MutUpdate::Updated { 507 | overflow: None, 508 | previous: Some(inner.vals.remove(i)), 509 | } 510 | } 511 | }, 512 | Loc::NotPresent(i) => match f(q, d, None) { 513 | Some((k, v)) => { 514 | let inner = Arc::make_mut(&mut self.0); 515 | let overflow = if inner.keys.len() == SIZE { 516 | let (ok, ov) = 517 | (inner.keys.pop().unwrap(), inner.vals.pop().unwrap()); 518 | inner.keys.insert(i, k); 519 | inner.vals.insert(i, v); 520 | Some((ok, ov)) 521 | } else { 522 | inner.keys.insert(i, k); 523 | inner.vals.insert(i, v); 524 | None 525 | }; 526 | MutUpdate::Updated { 527 | overflow, 528 | previous: None, 529 | } 530 | } 531 | None => MutUpdate::Updated { 532 | overflow: None, 533 | previous: None, 534 | }, 535 | }, 536 | loc @ Loc::InLeft | loc @ Loc::InRight => { 537 | if !leaf || self.len() == SIZE { 538 | match loc { 539 | Loc::InLeft => MutUpdate::UpdateLeft(q, d), 540 | Loc::InRight => MutUpdate::UpdateRight(q, d), 541 | Loc::Here(..) | Loc::NotPresent(..) => unreachable!(), 542 | } 543 | } else { 544 | let inner = Arc::make_mut(&mut self.0); 545 | match loc { 546 | Loc::InLeft => { 547 | if let Some((k, v)) = f(q, d, None) { 548 | inner.keys.insert(0, k); 549 | inner.vals.insert(0, v); 550 | } 551 | } 552 | Loc::InRight => { 553 | if let Some((k, v)) = f(q, d, None) { 554 | inner.keys.push(k); 555 | inner.vals.push(v); 556 | } 557 | } 558 | _ => unreachable!("bug"), 559 | }; 560 | MutUpdate::Updated { 561 | overflow: None, 562 | previous: None, 563 | } 564 | } 565 | } 566 | } 567 | } 568 | 569 | pub(crate) fn intersect( 570 | c0: &Chunk, 571 | c1: &Chunk, 572 | r: &mut Vec<(K, V)>, 573 | f: &mut F, 574 | ) where 575 | F: FnMut(&K, &V, &V) -> Option, 576 | { 577 | if c0.len() > 0 && c1.len() > 0 { 578 | let (c0, c1) = if c0.len() < c1.len() { 579 | (c0, c1) 580 | } else { 581 | (c1, c0) 582 | }; 583 | r.extend(c0.keys.iter().enumerate().filter_map(|(i, k)| { 584 | match c1.keys.binary_search(&k) { 585 | Err(_) => None, 586 | Ok(j) => f(k, &c0.vals[i], &c1.vals[j]).map(|v| (k.clone(), v)), 587 | } 588 | })) 589 | } 590 | } 591 | 592 | pub(crate) fn remove_elt_at(&self, i: usize) -> Self { 593 | let mut elts = Chunk::empty(); 594 | let t = Arc::make_mut(&mut elts.0); 595 | if self.keys.len() == 0 { 596 | panic!("can't remove from an empty chunk") 597 | } else if self.len() == 1 { 598 | assert_eq!(i, 0); 599 | elts 600 | } else if i == 0 { 601 | t.keys.extend(self.keys[1..self.len()].iter().cloned()); 602 | t.vals.extend(self.vals[1..self.len()].iter().cloned()); 603 | elts 604 | } else if i == self.keys.len() - 1 { 605 | t.keys.extend(self.keys[0..self.len() - 1].iter().cloned()); 606 | t.vals.extend(self.vals[0..self.len() - 1].iter().cloned()); 607 | elts 608 | } else { 609 | t.keys.extend(self.keys[0..i].iter().cloned()); 610 | t.keys.extend(self.keys[i + 1..self.len()].iter().cloned()); 611 | t.vals.extend(self.vals[0..i].iter().cloned()); 612 | t.vals.extend(self.vals[i + 1..self.len()].iter().cloned()); 613 | elts 614 | } 615 | } 616 | 617 | pub(crate) fn remove_elt_at_mut(&mut self, i: usize) -> (K, V) { 618 | if self.len() == 0 { 619 | panic!("can't remove from an empty chunk") 620 | } else { 621 | let inner = Arc::make_mut(&mut self.0); 622 | let k = inner.keys.remove(i); 623 | let v = inner.vals.remove(i); 624 | (k, v) 625 | } 626 | } 627 | 628 | pub(crate) fn append>(&self, other: I) -> Self { 629 | let mut elts = self.clone(); 630 | let inner = Arc::make_mut(&mut elts.0); 631 | for (k, v) in other { 632 | if inner.keys.len() < SIZE { 633 | inner.keys.push(k); 634 | inner.vals.push(v); 635 | } 636 | } 637 | elts 638 | } 639 | 640 | pub(crate) fn min_max_key(&self) -> Option<(K, K)> { 641 | if self.len() == 0 { 642 | None 643 | } else { 644 | Some((self.keys[0].clone(), self.keys[self.len() - 1].clone())) 645 | } 646 | } 647 | 648 | pub(crate) fn min_elt(&self) -> Option<(&K, &V)> { 649 | if self.len() == 0 { 650 | None 651 | } else { 652 | Some((&self.keys[0], &self.vals[0])) 653 | } 654 | } 655 | 656 | pub(crate) fn max_elt(&self) -> Option<(&K, &V)> { 657 | if self.len() == 0 { 658 | None 659 | } else { 660 | let last = self.len() - 1; 661 | Some((&self.keys[last], &self.vals[last])) 662 | } 663 | } 664 | 665 | pub(crate) fn len(&self) -> usize { 666 | self.keys.len() 667 | } 668 | 669 | pub(crate) fn key(&self, i: usize) -> &K { 670 | &self.keys[i] 671 | } 672 | 673 | pub(crate) fn val(&self, i: usize) -> &V { 674 | &self.vals[i] 675 | } 676 | 677 | pub(crate) fn val_mut(&mut self, i: usize) -> &mut V { 678 | &mut Arc::make_mut(&mut self.0).vals[i] 679 | } 680 | 681 | pub(crate) fn kv(&self, i: usize) -> (&K, &V) { 682 | (&self.keys[i], &self.vals[i]) 683 | } 684 | 685 | pub(crate) fn to_vec(&self) -> Vec<(K, V)> { 686 | self.into_iter() 687 | .map(|(k, v)| (k.clone(), v.clone())) 688 | .collect() 689 | } 690 | } 691 | 692 | impl IntoIterator for Chunk { 693 | type Item = (K, V); 694 | type IntoIter = iter::Zip, arrayvec::IntoIter>; 695 | fn into_iter(mut self) -> Self::IntoIter { 696 | let inner = mem::replace( 697 | Arc::make_mut(&mut self.0), 698 | ChunkInner { 699 | keys: ArrayVec::new(), 700 | vals: ArrayVec::new(), 701 | }, 702 | ); 703 | inner.keys.into_iter().zip(inner.vals.into_iter()) 704 | } 705 | } 706 | 707 | impl<'a, K, V, const SIZE: usize> IntoIterator for &'a Chunk { 708 | type Item = (&'a K, &'a V); 709 | type IntoIter = iter::Zip, slice::Iter<'a, V>>; 710 | fn into_iter(self) -> Self::IntoIter { 711 | (&self.keys).into_iter().zip(&self.vals) 712 | } 713 | } 714 | 715 | impl<'a, K: Clone, V: Clone, const SIZE: usize> IntoIterator for &'a mut Chunk { 716 | type Item = (&'a K, &'a mut V); 717 | type IntoIter = iter::Zip, slice::IterMut<'a, V>>; 718 | fn into_iter(self) -> Self::IntoIter { 719 | let inner = Arc::make_mut(&mut self.0); 720 | (&inner.keys).into_iter().zip(&mut inner.vals) 721 | } 722 | } 723 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Immutable maps and sets. See map and set modules for details. 2 | 3 | #![cfg_attr(not(feature = "rayon"), no_std)] 4 | 5 | extern crate alloc; 6 | 7 | pub(crate) mod chunk; 8 | pub(crate) mod avl; 9 | pub mod map; 10 | pub mod set; 11 | 12 | #[cfg(test)] 13 | mod tests; 14 | -------------------------------------------------------------------------------- /src/map.rs: -------------------------------------------------------------------------------- 1 | use crate::avl::{Iter, IterMut, Tree, WeakTree}; 2 | pub use crate::chunk::DEFAULT_SIZE; 3 | use core::{ 4 | borrow::Borrow, 5 | cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, 6 | default::Default, 7 | fmt::{self, Debug, Formatter}, 8 | hash::{Hash, Hasher}, 9 | iter::FromIterator, 10 | ops::{Index, IndexMut, RangeBounds, RangeFull}, 11 | }; 12 | 13 | #[cfg(feature = "serde")] 14 | use serde::{ 15 | de::{MapAccess, Visitor}, 16 | ser::SerializeMap, 17 | Deserialize, Deserializer, Serialize, Serializer, 18 | }; 19 | 20 | #[cfg(feature = "serde")] 21 | use core::marker::PhantomData; 22 | 23 | #[cfg(feature = "rayon")] 24 | use rayon::{ 25 | iter::{FromParallelIterator, IntoParallelIterator}, 26 | prelude::*, 27 | }; 28 | 29 | /// This Map uses a similar strategy to BTreeMap to ensure cache 30 | /// efficient performance on modern hardware while still providing 31 | /// log(N) get, insert, and remove operations. 32 | /// 33 | /// For good performance, it is very important to understand 34 | /// that clone is a fundamental operation, it needs to be fast 35 | /// for your key and data types, because it's going to be 36 | /// called a lot whenever you change the map. 37 | /// 38 | /// # Why 39 | /// 40 | /// 1. Multiple threads can read this structure even while one thread 41 | /// is updating it. Using a library like arc_swap you can avoid ever 42 | /// blocking readers. 43 | /// 44 | /// 2. Snapshotting this structure is free. 45 | /// 46 | /// # Examples 47 | /// ``` 48 | /// # extern crate alloc; 49 | /// use alloc::string::String; 50 | /// use self::immutable_chunkmap::map::MapM; 51 | /// 52 | /// let m = 53 | /// MapM::new() 54 | /// .insert(String::from("1"), 1).0 55 | /// .insert(String::from("2"), 2).0 56 | /// .insert(String::from("3"), 3).0; 57 | /// 58 | /// assert_eq!(m.get("1"), Option::Some(&1)); 59 | /// assert_eq!(m.get("2"), Option::Some(&2)); 60 | /// assert_eq!(m.get("3"), Option::Some(&3)); 61 | /// assert_eq!(m.get("4"), Option::None); 62 | /// 63 | /// for (k, v) in &m { 64 | /// println!("key {}, val: {}", k, v) 65 | /// } 66 | /// ``` 67 | #[derive(Clone)] 68 | pub struct Map(Tree); 69 | 70 | /// Map using a smaller chunk size, faster to update, slower to search 71 | pub type MapS = Map; 72 | 73 | /// Map using the default chunk size, a good balance of update and search 74 | pub type MapM = Map; 75 | 76 | /// Map using a larger chunk size, faster to search, slower to update 77 | pub type MapL = Map; 78 | 79 | /// A weak reference to a map. 80 | #[derive(Clone)] 81 | pub struct WeakMapRef(WeakTree); 82 | 83 | pub type WeakMapRefS = WeakMapRef; 84 | pub type WeakMapRefM = WeakMapRef; 85 | pub type WeakMapRefL = WeakMapRef; 86 | 87 | impl WeakMapRef 88 | where 89 | K: Ord + Clone, 90 | V: Clone, 91 | { 92 | pub fn upgrade(&self) -> Option> { 93 | self.0.upgrade().map(Map) 94 | } 95 | } 96 | 97 | impl Hash for Map 98 | where 99 | K: Hash + Ord + Clone, 100 | V: Hash + Clone, 101 | { 102 | fn hash(&self, state: &mut H) { 103 | self.0.hash(state) 104 | } 105 | } 106 | 107 | impl Default for Map 108 | where 109 | K: Ord + Clone, 110 | V: Clone, 111 | { 112 | fn default() -> Map { 113 | Map::new() 114 | } 115 | } 116 | 117 | impl PartialEq for Map 118 | where 119 | K: PartialEq + Ord + Clone, 120 | V: PartialEq + Clone, 121 | { 122 | fn eq(&self, other: &Map) -> bool { 123 | self.0 == other.0 124 | } 125 | } 126 | 127 | impl Eq for Map 128 | where 129 | K: Eq + Ord + Clone, 130 | V: Eq + Clone, 131 | { 132 | } 133 | 134 | impl PartialOrd for Map 135 | where 136 | K: Ord + Clone, 137 | V: PartialOrd + Clone, 138 | { 139 | fn partial_cmp(&self, other: &Map) -> Option { 140 | self.0.partial_cmp(&other.0) 141 | } 142 | } 143 | 144 | impl Ord for Map 145 | where 146 | K: Ord + Clone, 147 | V: Ord + Clone, 148 | { 149 | fn cmp(&self, other: &Map) -> Ordering { 150 | self.0.cmp(&other.0) 151 | } 152 | } 153 | 154 | impl Debug for Map 155 | where 156 | K: Debug + Ord + Clone, 157 | V: Debug + Clone, 158 | { 159 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 160 | self.0.fmt(f) 161 | } 162 | } 163 | 164 | impl<'a, Q, K, V, const SIZE: usize> Index<&'a Q> for Map 165 | where 166 | Q: Ord, 167 | K: Ord + Clone + Borrow, 168 | V: Clone, 169 | { 170 | type Output = V; 171 | fn index(&self, k: &Q) -> &V { 172 | self.get(k).expect("element not found for key") 173 | } 174 | } 175 | 176 | impl<'a, Q, K, V, const SIZE: usize> IndexMut<&'a Q> for Map 177 | where 178 | Q: Ord, 179 | K: Ord + Clone + Borrow, 180 | V: Clone, 181 | { 182 | fn index_mut(&mut self, k: &'a Q) -> &mut Self::Output { 183 | self.get_mut_cow(k).expect("element not found for key") 184 | } 185 | } 186 | 187 | impl FromIterator<(K, V)> for Map 188 | where 189 | K: Ord + Clone, 190 | V: Clone, 191 | { 192 | fn from_iter>(iter: T) -> Self { 193 | Map::new().insert_many(iter) 194 | } 195 | } 196 | 197 | impl<'a, K, V, const SIZE: usize> IntoIterator for &'a Map 198 | where 199 | K: 'a + Ord + Clone, 200 | V: 'a + Clone, 201 | { 202 | type Item = (&'a K, &'a V); 203 | type IntoIter = Iter<'a, RangeFull, K, K, V, SIZE>; 204 | fn into_iter(self) -> Self::IntoIter { 205 | self.0.into_iter() 206 | } 207 | } 208 | 209 | #[cfg(feature = "serde")] 210 | impl Serialize for Map 211 | where 212 | K: Serialize + Clone + Ord, 213 | V: Serialize + Clone, 214 | { 215 | fn serialize(&self, serializer: S) -> Result 216 | where 217 | S: Serializer, 218 | { 219 | let mut map = serializer.serialize_map(Some(self.len()))?; 220 | for (k, v) in self { 221 | map.serialize_entry(k, v)? 222 | } 223 | map.end() 224 | } 225 | } 226 | 227 | #[cfg(feature = "serde")] 228 | struct MapVisitor { 229 | marker: PhantomData Map>, 230 | } 231 | 232 | #[cfg(feature = "serde")] 233 | impl<'a, K, V, const SIZE: usize> Visitor<'a> for MapVisitor 234 | where 235 | K: Deserialize<'a> + Clone + Ord, 236 | V: Deserialize<'a> + Clone, 237 | { 238 | type Value = Map; 239 | 240 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 241 | formatter.write_str("expected an immutable_chunkmap::Map") 242 | } 243 | 244 | fn visit_map(self, mut map: A) -> Result 245 | where 246 | A: MapAccess<'a>, 247 | { 248 | let mut t = Map::::new(); 249 | while let Some((k, v)) = map.next_entry()? { 250 | t.insert_cow(k, v); 251 | } 252 | Ok(t) 253 | } 254 | } 255 | 256 | #[cfg(feature = "serde")] 257 | impl<'a, K, V, const SIZE: usize> Deserialize<'a> for Map 258 | where 259 | K: Deserialize<'a> + Clone + Ord, 260 | V: Deserialize<'a> + Clone, 261 | { 262 | fn deserialize(deserializer: D) -> Result 263 | where 264 | D: Deserializer<'a>, 265 | { 266 | deserializer.deserialize_map(MapVisitor { 267 | marker: PhantomData, 268 | }) 269 | } 270 | } 271 | 272 | #[cfg(feature = "rayon")] 273 | impl<'a, K, V, const SIZE: usize> IntoParallelIterator for &'a Map 274 | where 275 | K: 'a + Ord + Clone + Send + Sync, 276 | V: Clone + Send + Sync, 277 | { 278 | type Item = (&'a K, &'a V); 279 | type Iter = rayon::vec::IntoIter<(&'a K, &'a V)>; 280 | 281 | fn into_par_iter(self) -> Self::Iter { 282 | self.into_iter().collect::>().into_par_iter() 283 | } 284 | } 285 | 286 | #[cfg(feature = "rayon")] 287 | impl FromParallelIterator<(K, V)> for Map 288 | where 289 | K: Ord + Clone + Send + Sync, 290 | V: Clone + Send + Sync, 291 | { 292 | fn from_par_iter(i: I) -> Self 293 | where 294 | I: IntoParallelIterator, 295 | { 296 | i.into_par_iter() 297 | .fold_with(Map::new(), |mut m, (k, v)| { 298 | m.insert_cow(k, v); 299 | m 300 | }) 301 | .reduce_with(|m0, m1| m0.union(&m1, |_k, _v0, v1| Some(v1.clone()))) 302 | .unwrap_or_else(Map::new) 303 | } 304 | } 305 | 306 | impl Map 307 | where 308 | K: Ord + Clone, 309 | V: Clone, 310 | { 311 | /// Create a new empty map 312 | pub fn new() -> Self { 313 | Map(Tree::new()) 314 | } 315 | 316 | /// Create a weak reference to this map 317 | pub fn downgrade(&self) -> WeakMapRef { 318 | WeakMapRef(self.0.downgrade()) 319 | } 320 | 321 | /// Return the number of strong references to this map (see Arc) 322 | pub fn strong_count(&self) -> usize { 323 | self.0.strong_count() 324 | } 325 | 326 | /// Return the number of weak references to this map (see Arc) 327 | pub fn weak_count(&self) -> usize { 328 | self.0.weak_count() 329 | } 330 | 331 | /// This will insert many elements at once, and is 332 | /// potentially a lot faster than inserting one by one, 333 | /// especially if the data is sorted. It is just a wrapper 334 | /// around the more general update_many method. 335 | /// 336 | /// #Examples 337 | ///``` 338 | /// use self::immutable_chunkmap::map::MapM; 339 | /// 340 | /// let mut v = vec![(1, 3), (10, 1), (-12, 2), (44, 0), (50, -1)]; 341 | /// v.sort_unstable_by_key(|&(k, _)| k); 342 | /// 343 | /// let m = MapM::new().insert_many(v.iter().map(|(k, v)| (*k, *v))); 344 | /// 345 | /// for (k, v) in &v { 346 | /// assert_eq!(m.get(k), Option::Some(v)) 347 | /// } 348 | /// ``` 349 | pub fn insert_many>(&self, elts: E) -> Self { 350 | Map(self.0.insert_many(elts)) 351 | } 352 | 353 | /// This will remove many elements at once, and is potentially a 354 | /// lot faster than removing elements one by one, especially if 355 | /// the data is sorted. It is just a wrapper around the more 356 | /// general update_many method. 357 | pub fn remove_many(&self, elts: E) -> Self 358 | where 359 | E: IntoIterator, 360 | Q: Ord, 361 | K: Borrow, 362 | { 363 | self.update_many(elts.into_iter().map(|q| (q, ())), |_, _, _| None) 364 | } 365 | 366 | /// This method updates multiple bindings in one call. Given an 367 | /// iterator of an arbitrary type (Q, D), where Q is any borrowed 368 | /// form of K, an update function taking Q, D, the current binding 369 | /// in the map, if any, and producing the new binding, if any, 370 | /// this method will produce a new map with updated bindings of 371 | /// many elements at once. It will skip intermediate node 372 | /// allocations where possible. If the data in elts is sorted, it 373 | /// will be able to skip many more intermediate allocations, and 374 | /// can produce a speedup of about 10x compared to 375 | /// inserting/updating one by one. In any case it should always be 376 | /// faster than inserting elements one by one, even with random 377 | /// unsorted keys. 378 | /// 379 | /// #Examples 380 | /// ``` 381 | /// use core::iter::FromIterator; 382 | /// use self::immutable_chunkmap::map::MapM; 383 | /// 384 | /// let m = MapM::from_iter((0..4).map(|k| (k, k))); 385 | /// let m = m.update_many( 386 | /// (0..4).map(|x| (x, ())), 387 | /// |k, (), cur| cur.map(|(_, c)| (k, c + 1)) 388 | /// ); 389 | /// assert_eq!( 390 | /// m.into_iter().map(|(k, v)| (*k, *v)).collect::>(), 391 | /// vec![(0, 1), (1, 2), (2, 3), (3, 4)] 392 | /// ); 393 | /// ``` 394 | pub fn update_many(&self, elts: E, mut f: F) -> Self 395 | where 396 | E: IntoIterator, 397 | Q: Ord, 398 | K: Borrow, 399 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 400 | { 401 | Map(self.0.update_many(elts, &mut f)) 402 | } 403 | 404 | /// return a new map with (k, v) inserted into it. If k 405 | /// already exists in the old map, the old binding will be 406 | /// returned, and the new map will contain the new 407 | /// binding. In fact this method is just a wrapper around 408 | /// update. 409 | pub fn insert(&self, k: K, v: V) -> (Self, Option) { 410 | let (root, prev) = self.0.insert(k, v); 411 | (Map(root), prev) 412 | } 413 | 414 | /// insert in place using copy on write semantics if self is not a 415 | /// unique reference to the map. see `update_cow`. 416 | pub fn insert_cow(&mut self, k: K, v: V) -> Option { 417 | self.0.insert_cow(k, v) 418 | } 419 | 420 | /// return a new map with the binding for q, which can be any 421 | /// borrowed form of k, updated to the result of f. If f returns 422 | /// None, the binding will be removed from the new map, otherwise 423 | /// it will be inserted. This function is more efficient than 424 | /// calling `get` and then `insert`, since it makes only one tree 425 | /// traversal instead of two. This method runs in log(N) time and 426 | /// space where N is the size of the map. 427 | /// 428 | /// # Examples 429 | /// ``` 430 | /// use self::immutable_chunkmap::map::MapM; 431 | /// 432 | /// let (m, _) = MapM::new().update(0, 0, |k, d, _| Some((k, d))); 433 | /// let (m, _) = m.update(1, 1, |k, d, _| Some((k, d))); 434 | /// let (m, _) = m.update(2, 2, |k, d, _| Some((k, d))); 435 | /// assert_eq!(m.get(&0), Some(&0)); 436 | /// assert_eq!(m.get(&1), Some(&1)); 437 | /// assert_eq!(m.get(&2), Some(&2)); 438 | /// 439 | /// let (m, _) = m.update(0, (), |k, (), v| v.map(move |(_, v)| (k, v + 1))); 440 | /// assert_eq!(m.get(&0), Some(&1)); 441 | /// assert_eq!(m.get(&1), Some(&1)); 442 | /// assert_eq!(m.get(&2), Some(&2)); 443 | /// 444 | /// let (m, _) = m.update(1, (), |_, (), _| None); 445 | /// assert_eq!(m.get(&0), Some(&1)); 446 | /// assert_eq!(m.get(&1), None); 447 | /// assert_eq!(m.get(&2), Some(&2)); 448 | /// ``` 449 | pub fn update(&self, q: Q, d: D, mut f: F) -> (Self, Option) 450 | where 451 | Q: Ord, 452 | K: Borrow, 453 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 454 | { 455 | let (root, prev) = self.0.update(q, d, &mut f); 456 | (Map(root), prev) 457 | } 458 | 459 | /// Perform a copy on write update to the map. In the case that 460 | /// self is a unique reference to the map, then the update will be 461 | /// performed completly in place. self will be mutated, and no 462 | /// previous version will be available. In the case that self has 463 | /// a clone, or clones, then only the parts of the map that need 464 | /// to be mutated will be copied before the update is 465 | /// performed. self will reference the mutated copy, and previous 466 | /// versions of the map will not be modified. self will still 467 | /// share all the parts of the map that did not need to be mutated 468 | /// with any pre existing clones. 469 | /// 470 | /// COW semantics are a flexible middle way between full 471 | /// peristance and full mutability. Needless to say in the case 472 | /// where you have a unique reference to the map, using update_cow 473 | /// is a lot faster than using update, and a lot more flexible 474 | /// than update_many. 475 | /// 476 | /// Other than copy on write the semanics of this method are 477 | /// identical to those of update. 478 | /// 479 | /// #Examples 480 | ///``` 481 | /// use self::immutable_chunkmap::map::MapM; 482 | /// 483 | /// let mut m = MapM::new().update(0, 0, |k, d, _| Some((k, d))).0; 484 | /// let orig = m.clone(); 485 | /// m.update_cow(1, 1, |k, d, _| Some((k, d))); // copies the original chunk 486 | /// m.update_cow(2, 2, |k, d, _| Some((k, d))); // doesn't copy anything 487 | /// assert_eq!(m.len(), 3); 488 | /// assert_eq!(orig.len(), 1); 489 | /// assert_eq!(m.get(&0), Some(&0)); 490 | /// assert_eq!(m.get(&1), Some(&1)); 491 | /// assert_eq!(m.get(&2), Some(&2)); 492 | /// assert_eq!(orig.get(&0), Some(&0)); 493 | /// assert_eq!(orig.get(&1), None); 494 | /// assert_eq!(orig.get(&2), None); 495 | ///``` 496 | pub fn update_cow(&mut self, q: Q, d: D, mut f: F) -> Option 497 | where 498 | Q: Ord, 499 | K: Borrow, 500 | F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>, 501 | { 502 | self.0.update_cow(q, d, &mut f) 503 | } 504 | 505 | /// Merge two maps together. Bindings that exist in both maps will 506 | /// be passed to f, which may elect to remove the binding by 507 | /// returning None. This function runs in O(log(n) + m) time and 508 | /// space, where n is the size of the largest map, and m is the 509 | /// number of intersecting chunks. It will never be slower than 510 | /// calling update_many on the first map with an iterator over the 511 | /// second, and will be significantly faster if the intersection 512 | /// is minimal or empty. 513 | /// 514 | /// # Examples 515 | /// ``` 516 | /// use core::iter::FromIterator; 517 | /// use self::immutable_chunkmap::map::MapM; 518 | /// 519 | /// let m0 = MapM::from_iter((0..10).map(|k| (k, 1))); 520 | /// let m1 = MapM::from_iter((10..20).map(|k| (k, 1))); 521 | /// let m2 = m0.union(&m1, |_k, _v0, _v1| panic!("no intersection expected")); 522 | /// 523 | /// for i in 0..20 { 524 | /// assert!(m2.get(&i).is_some()) 525 | /// } 526 | /// 527 | /// let m3 = MapM::from_iter((5..9).map(|k| (k, 1))); 528 | /// let m4 = m3.union(&m2, |_k, v0, v1| Some(v0 + v1)); 529 | /// 530 | /// for i in 0..20 { 531 | /// assert!( 532 | /// *m4.get(&i).unwrap() == 533 | /// *m3.get(&i).unwrap_or(&0) + *m2.get(&i).unwrap_or(&0) 534 | /// ) 535 | /// } 536 | /// ``` 537 | pub fn union(&self, other: &Map, mut f: F) -> Self 538 | where 539 | F: FnMut(&K, &V, &V) -> Option, 540 | { 541 | Map(Tree::union(&self.0, &other.0, &mut f)) 542 | } 543 | 544 | /// Produce a map containing the mapping over F of the 545 | /// intersection (by key) of two maps. The function f runs on each 546 | /// intersecting element, and has the option to omit elements from 547 | /// the intersection by returning None, or change the value any 548 | /// way it likes. Runs in O(log(N) + M) time and space where N is 549 | /// the size of the smallest map, and M is the number of 550 | /// intersecting chunks. 551 | /// 552 | /// # Examples 553 | ///``` 554 | /// use core::iter::FromIterator; 555 | /// use self::immutable_chunkmap::map::MapM; 556 | /// 557 | /// let m0 = MapM::from_iter((0..100000).map(|k| (k, 1))); 558 | /// let m1 = MapM::from_iter((50..30000).map(|k| (k, 1))); 559 | /// let m2 = m0.intersect(&m1, |_k, v0, v1| Some(v0 + v1)); 560 | /// 561 | /// for i in 0..100000 { 562 | /// if i >= 30000 || i < 50 { 563 | /// assert!(m2.get(&i).is_none()); 564 | /// } else { 565 | /// assert!(*m2.get(&i).unwrap() == 2); 566 | /// } 567 | /// } 568 | /// ``` 569 | pub fn intersect(&self, other: &Map, mut f: F) -> Self 570 | where 571 | F: FnMut(&K, &V, &V) -> Option, 572 | { 573 | Map(Tree::intersect(&self.0, &other.0, &mut f)) 574 | } 575 | 576 | /// Produce a map containing the second map subtracted from the 577 | /// first. The function F is called for each intersecting element, 578 | /// and ultimately decides whether it appears in the result, for 579 | /// example, to compute a classical set diff, the function should 580 | /// always return None. 581 | /// 582 | /// # Examples 583 | ///``` 584 | /// use core::iter::FromIterator; 585 | /// use self::immutable_chunkmap::map::MapM; 586 | /// 587 | /// let m0 = MapM::from_iter((0..10000).map(|k| (k, 1))); 588 | /// let m1 = MapM::from_iter((50..3000).map(|k| (k, 1))); 589 | /// let m2 = m0.diff(&m1, |_k, _v0, _v1| None); 590 | /// 591 | /// m2.invariant(); 592 | /// dbg!(m2.len()); 593 | /// assert!(m2.len() == 10000 - 2950); 594 | /// for i in 0..10000 { 595 | /// if i >= 3000 || i < 50 { 596 | /// assert!(*m2.get(&i).unwrap() == 1); 597 | /// } else { 598 | /// assert!(m2.get(&i).is_none()); 599 | /// } 600 | /// } 601 | /// ``` 602 | pub fn diff(&self, other: &Map, mut f: F) -> Self 603 | where 604 | F: FnMut(&K, &V, &V) -> Option, 605 | K: Debug, 606 | V: Debug, 607 | { 608 | Map(Tree::diff(&self.0, &other.0, &mut f)) 609 | } 610 | 611 | /// lookup the mapping for k. If it doesn't exist return 612 | /// None. Runs in log(N) time and constant space. where N 613 | /// is the size of the map. 614 | pub fn get<'a, Q: ?Sized + Ord>(&'a self, k: &Q) -> Option<&'a V> 615 | where 616 | K: Borrow, 617 | { 618 | self.0.get(k) 619 | } 620 | 621 | /// lookup the mapping for k. Return the key. If it doesn't exist 622 | /// return None. Runs in log(N) time and constant space. where N 623 | /// is the size of the map. 624 | pub fn get_key<'a, Q: ?Sized + Ord>(&'a self, k: &Q) -> Option<&'a K> 625 | where 626 | K: Borrow, 627 | { 628 | self.0.get_key(k) 629 | } 630 | 631 | /// lookup the mapping for k. Return both the key and the 632 | /// value. If it doesn't exist return None. Runs in log(N) time 633 | /// and constant space. where N is the size of the map. 634 | pub fn get_full<'a, Q: ?Sized + Ord>(&'a self, k: &Q) -> Option<(&'a K, &'a V)> 635 | where 636 | K: Borrow, 637 | { 638 | self.0.get_full(k) 639 | } 640 | 641 | /// Get a mutable reference to the value mapped to `k` using copy on write semantics. 642 | /// This works as `Arc::make_mut`, it will only clone the parts of the tree that are, 643 | /// - required to reach `k` 644 | /// - have a strong count > 1 645 | /// 646 | /// This operation is also triggered by mut indexing on the map, e.g. `&mut m[k]` 647 | /// calls `get_mut_cow` on `m` 648 | /// 649 | /// # Example 650 | /// ``` 651 | /// use core::iter::FromIterator; 652 | /// use self::immutable_chunkmap::map::MapM as Map; 653 | /// 654 | /// let mut m = Map::from_iter((0..100).map(|k| (k, Map::from_iter((0..100).map(|k| (k, 1)))))); 655 | /// let orig = m.clone(); 656 | /// 657 | /// if let Some(inner) = m.get_mut_cow(&0) { 658 | /// if let Some(v) = inner.get_mut_cow(&0) { 659 | /// *v += 1 660 | /// } 661 | /// } 662 | /// 663 | /// assert_eq!(m.get(&0).and_then(|m| m.get(&0)), Some(&2)); 664 | /// assert_eq!(orig.get(&0).and_then(|m| m.get(&0)), Some(&1)); 665 | /// ``` 666 | pub fn get_mut_cow<'a, Q: ?Sized + Ord>(&'a mut self, k: &Q) -> Option<&'a mut V> 667 | where 668 | K: Borrow, 669 | { 670 | self.0.get_mut_cow(k) 671 | } 672 | 673 | /// Same as `get_mut_cow` except if the value is not in the map it will 674 | /// first be inserted by calling `f` 675 | pub fn get_or_insert_cow<'a, F>(&'a mut self, k: K, f: F) -> &'a mut V 676 | where 677 | F: FnOnce() -> V, 678 | { 679 | self.0.get_or_insert_cow(k, f) 680 | } 681 | 682 | /// return a new map with the mapping under k removed. If 683 | /// the binding existed in the old map return it. Runs in 684 | /// log(N) time and log(N) space, where N is the size of 685 | /// the map. 686 | pub fn remove(&self, k: &Q) -> (Self, Option) 687 | where 688 | K: Borrow, 689 | { 690 | let (t, prev) = self.0.remove(k); 691 | (Map(t), prev) 692 | } 693 | 694 | /// remove in place using copy on write semantics if self is not a 695 | /// unique reference to the map. see `update_cow`. 696 | pub fn remove_cow(&mut self, k: &Q) -> Option 697 | where 698 | K: Borrow, 699 | { 700 | self.0.remove_cow(k) 701 | } 702 | 703 | /// get the number of elements in the map O(1) time and space 704 | pub fn len(&self) -> usize { 705 | self.0.len() 706 | } 707 | 708 | /// return an iterator over the subset of elements in the 709 | /// map that are within the specified range. 710 | /// 711 | /// The returned iterator runs in O(log(N) + M) time, and 712 | /// constant space. N is the number of elements in the 713 | /// tree, and M is the number of elements you examine. 714 | /// 715 | /// if lbound >= ubound the returned iterator will be empty 716 | pub fn range<'a, Q, R>(&'a self, r: R) -> Iter<'a, R, Q, K, V, SIZE> 717 | where 718 | Q: Ord + ?Sized + 'a, 719 | K: Borrow, 720 | R: RangeBounds + 'a, 721 | { 722 | self.0.range(r) 723 | } 724 | 725 | /// return a mutable iterator over the subset of elements in the 726 | /// map that are within the specified range. The iterator will 727 | /// copy on write the part of the tree that it visits, 728 | /// specifically it will be as if you ran get_mut_cow on every 729 | /// element you visit. 730 | /// 731 | /// The returned iterator runs in O(log(N) + M) time, and 732 | /// constant space. N is the number of elements in the 733 | /// tree, and M is the number of elements you examine. 734 | /// 735 | /// if lbound >= ubound the returned iterator will be empty 736 | pub fn range_mut_cow<'a, Q, R>(&'a mut self, r: R) -> IterMut<'a, R, Q, K, V, SIZE> 737 | where 738 | Q: Ord + ?Sized + 'a, 739 | K: Borrow, 740 | R: RangeBounds + 'a, 741 | { 742 | self.0.range_mut_cow(r) 743 | } 744 | 745 | /// return a mutable iterator over the entire map. The iterator 746 | /// will copy on write every element in the tree, specifically it 747 | /// will be as if you ran get_mut_cow on every element. 748 | /// 749 | /// The returned iterator runs in O(log(N) + M) time, and 750 | /// constant space. N is the number of elements in the 751 | /// tree, and M is the number of elements you examine. 752 | pub fn iter_mut_cow<'a>(&'a mut self) -> IterMut<'a, RangeFull, K, K, V, SIZE> { 753 | self.0.iter_mut_cow() 754 | } 755 | } 756 | 757 | impl Map 758 | where 759 | K: Ord + Clone, 760 | V: Clone + Default, 761 | { 762 | /// Same as `get_mut_cow` except if the value isn't in the map it will 763 | /// be added by calling `V::default` 764 | pub fn get_or_default_cow<'a>(&'a mut self, k: K) -> &'a mut V { 765 | self.get_or_insert_cow(k, V::default) 766 | } 767 | } 768 | 769 | impl Map 770 | where 771 | K: Ord + Clone + Debug, 772 | V: Clone + Debug, 773 | { 774 | #[allow(dead_code)] 775 | pub fn invariant(&self) -> () { 776 | self.0.invariant() 777 | } 778 | } 779 | -------------------------------------------------------------------------------- /src/set.rs: -------------------------------------------------------------------------------- 1 | use crate::avl::{Iter, Tree, WeakTree}; 2 | pub use crate::chunk::DEFAULT_SIZE; 3 | use core::{ 4 | borrow::Borrow, 5 | cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, 6 | default::Default, 7 | fmt::{self, Debug, Formatter}, 8 | hash::{Hash, Hasher}, 9 | iter::FromIterator, 10 | ops::{RangeBounds, RangeFull}, 11 | }; 12 | 13 | #[cfg(feature = "serde")] 14 | use serde::{ 15 | de::{SeqAccess, Visitor}, 16 | ser::SerializeSeq, 17 | Deserialize, Deserializer, Serialize, Serializer, 18 | }; 19 | 20 | #[cfg(feature = "serde")] 21 | use core::marker::PhantomData; 22 | 23 | #[cfg(feature = "rayon")] 24 | use rayon::{ 25 | iter::{FromParallelIterator, IntoParallelIterator}, 26 | prelude::*, 27 | }; 28 | 29 | /// This set uses a similar strategy to BTreeSet to ensure cache 30 | /// efficient performance on modern hardware while still providing 31 | /// log(N) get, insert, and remove operations. 32 | /// # Examples 33 | /// ``` 34 | /// # extern crate alloc; 35 | /// use alloc::string::String; 36 | /// use self::immutable_chunkmap::set::SetM; 37 | /// 38 | /// let m = 39 | /// SetM::new() 40 | /// .insert(String::from("1")).0 41 | /// .insert(String::from("2")).0 42 | /// .insert(String::from("3")).0; 43 | /// 44 | /// assert_eq!(m.contains("1"), true); 45 | /// assert_eq!(m.contains("2"), true); 46 | /// assert_eq!(m.contains("3"), true); 47 | /// assert_eq!(m.contains("4"), false); 48 | /// 49 | /// for k in &m { println!("{}", k) } 50 | /// ``` 51 | #[derive(Clone)] 52 | pub struct Set(Tree); 53 | 54 | /// set with a smaller chunk size, faster to update, slower to search 55 | pub type SetS = Set; 56 | 57 | /// set with the default chunk size, a good balance of search and update performance 58 | pub type SetM = Set; 59 | 60 | /// set with a larger chunk size, faster to search, slower to update 61 | pub type SetL = Set; 62 | 63 | #[derive(Clone)] 64 | pub struct WeakSetRef(WeakTree); 65 | 66 | pub type WeakSetRefS = WeakSetRef; 67 | pub type WeakSetRefM = WeakSetRef; 68 | pub type WeakSetRefL = WeakSetRef; 69 | 70 | impl WeakSetRef 71 | where 72 | K: Ord + Clone, 73 | { 74 | pub fn upgrade(&self) -> Option> { 75 | self.0.upgrade().map(Set) 76 | } 77 | } 78 | 79 | impl Hash for Set 80 | where 81 | K: Hash + Ord + Clone, 82 | { 83 | fn hash(&self, state: &mut H) { 84 | self.0.hash(state) 85 | } 86 | } 87 | 88 | impl Default for Set 89 | where 90 | K: Ord + Clone, 91 | { 92 | fn default() -> Set { 93 | Set::new() 94 | } 95 | } 96 | 97 | impl PartialEq for Set 98 | where 99 | K: Ord + Clone, 100 | { 101 | fn eq(&self, other: &Set) -> bool { 102 | self.0 == other.0 103 | } 104 | } 105 | 106 | impl Eq for Set where K: Eq + Ord + Clone {} 107 | 108 | impl PartialOrd for Set 109 | where 110 | K: Ord + Clone, 111 | { 112 | fn partial_cmp(&self, other: &Set) -> Option { 113 | self.0.partial_cmp(&other.0) 114 | } 115 | } 116 | 117 | impl Ord for Set 118 | where 119 | K: Ord + Clone, 120 | { 121 | fn cmp(&self, other: &Set) -> Ordering { 122 | self.0.cmp(&other.0) 123 | } 124 | } 125 | 126 | impl Debug for Set 127 | where 128 | K: Debug + Ord + Clone, 129 | { 130 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 131 | f.debug_set().entries(self.into_iter()).finish() 132 | } 133 | } 134 | 135 | impl FromIterator for Set 136 | where 137 | K: Ord + Clone, 138 | { 139 | fn from_iter>(iter: T) -> Self { 140 | Set::new().insert_many(iter) 141 | } 142 | } 143 | 144 | pub struct SetIter< 145 | 'a, 146 | R: RangeBounds + 'a, 147 | Q: Ord + ?Sized, 148 | K: 'a + Clone + Ord + Borrow, 149 | const SIZE: usize, 150 | >(Iter<'a, R, Q, K, (), SIZE>); 151 | 152 | impl<'a, R, Q, K, const SIZE: usize> Iterator for SetIter<'a, R, Q, K, SIZE> 153 | where 154 | Q: Ord + ?Sized, 155 | R: RangeBounds + 'a, 156 | K: 'a + Clone + Ord + Borrow, 157 | { 158 | type Item = &'a K; 159 | fn next(&mut self) -> Option { 160 | self.0.next().map(|(k, ())| k) 161 | } 162 | } 163 | 164 | impl<'a, R, Q, K, const SIZE: usize> DoubleEndedIterator for SetIter<'a, R, Q, K, SIZE> 165 | where 166 | Q: Ord + ?Sized, 167 | R: RangeBounds + 'a, 168 | K: 'a + Clone + Ord + Borrow, 169 | { 170 | fn next_back(&mut self) -> Option { 171 | self.0.next_back().map(|(k, ())| k) 172 | } 173 | } 174 | 175 | impl<'a, K, const SIZE: usize> IntoIterator for &'a Set 176 | where 177 | K: 'a + Ord + Clone, 178 | { 179 | type Item = &'a K; 180 | type IntoIter = SetIter<'a, RangeFull, K, K, SIZE>; 181 | fn into_iter(self) -> Self::IntoIter { 182 | SetIter(self.0.into_iter()) 183 | } 184 | } 185 | 186 | #[cfg(feature = "serde")] 187 | impl Serialize for Set 188 | where 189 | V: Serialize + Clone + Ord, 190 | { 191 | fn serialize(&self, serializer: S) -> Result 192 | where 193 | S: Serializer, 194 | { 195 | let mut seq = serializer.serialize_seq(Some(self.len()))?; 196 | for v in self { 197 | seq.serialize_element(v)? 198 | } 199 | seq.end() 200 | } 201 | } 202 | 203 | #[cfg(feature = "serde")] 204 | struct SetVisitor { 205 | marker: PhantomData Set>, 206 | } 207 | 208 | #[cfg(feature = "serde")] 209 | impl<'a, V, const SIZE: usize> Visitor<'a> for SetVisitor 210 | where 211 | V: Deserialize<'a> + Clone + Ord, 212 | { 213 | type Value = Set; 214 | 215 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 216 | formatter.write_str("expecting an immutable_chunkmap::Set") 217 | } 218 | 219 | fn visit_seq(self, mut seq: A) -> Result 220 | where 221 | A: SeqAccess<'a>, 222 | { 223 | let mut t = Set::::new(); 224 | while let Some(v) = seq.next_element()? { 225 | t.insert_cow(v); 226 | } 227 | Ok(t) 228 | } 229 | } 230 | 231 | #[cfg(feature = "serde")] 232 | impl<'a, V, const SIZE: usize> Deserialize<'a> for Set 233 | where 234 | V: Deserialize<'a> + Clone + Ord, 235 | { 236 | fn deserialize(deserializer: D) -> Result 237 | where 238 | D: Deserializer<'a>, 239 | { 240 | deserializer.deserialize_seq(SetVisitor { 241 | marker: PhantomData, 242 | }) 243 | } 244 | } 245 | 246 | #[cfg(feature = "rayon")] 247 | impl<'a, V, const SIZE: usize> IntoParallelIterator for &'a Set 248 | where 249 | V: 'a + Ord + Clone + Send + Sync, 250 | { 251 | type Item = &'a V; 252 | type Iter = rayon::vec::IntoIter<&'a V>; 253 | 254 | fn into_par_iter(self) -> Self::Iter { 255 | self.into_iter().collect::>().into_par_iter() 256 | } 257 | } 258 | 259 | #[cfg(feature = "rayon")] 260 | impl FromParallelIterator for Set 261 | where 262 | V: Ord + Clone + Send + Sync, 263 | { 264 | fn from_par_iter(i: I) -> Self 265 | where 266 | I: IntoParallelIterator, 267 | { 268 | i.into_par_iter() 269 | .fold_with(Set::new(), |mut m, v| { 270 | m.insert_cow(v); 271 | m 272 | }) 273 | .reduce_with(|m0, m1| m0.union(&m1)) 274 | .unwrap_or_else(Set::new) 275 | } 276 | } 277 | 278 | impl Set 279 | where 280 | K: Ord + Clone, 281 | { 282 | /// Create a new empty set 283 | pub fn new() -> Self { 284 | Set(Tree::new()) 285 | } 286 | 287 | /// Create a weak reference to this set 288 | pub fn downgrade(&self) -> WeakSetRef { 289 | WeakSetRef(self.0.downgrade()) 290 | } 291 | 292 | /// Return the number of strong references to this set (see Arc) 293 | pub fn strong_count(&self) -> usize { 294 | self.0.strong_count() 295 | } 296 | 297 | /// Return the number of weak references to this set (see Arc) 298 | pub fn weak_count(&self) -> usize { 299 | self.0.weak_count() 300 | } 301 | 302 | /// This will insert many elements at once, and is 303 | /// potentially a lot faster than inserting one by one, 304 | /// especially if the data is sorted. 305 | /// 306 | /// #Examples 307 | ///``` 308 | /// use self::immutable_chunkmap::set::SetM; 309 | /// 310 | /// let mut v = vec![1, 10, -12, 44, 50]; 311 | /// v.sort_unstable(); 312 | /// 313 | /// let m = SetM::new().insert_many(v.iter().map(|k| *k)); 314 | /// 315 | /// for k in &v { 316 | /// assert_eq!(m.contains(k), true) 317 | /// } 318 | /// ``` 319 | pub fn insert_many>(&self, elts: E) -> Self { 320 | let root = self.0.insert_many(elts.into_iter().map(|k| (k, ()))); 321 | Set(root) 322 | } 323 | 324 | /// Remove multiple elements in a single pass. Similar performance 325 | /// to insert_many. 326 | pub fn remove_many(&self, elts: E) -> Self 327 | where 328 | Q: Ord, 329 | K: Borrow, 330 | E: IntoIterator, 331 | { 332 | let root = self 333 | .0 334 | .update_many(elts.into_iter().map(|k| (k, ())), &mut |_, _, _| None); 335 | Set(root) 336 | } 337 | 338 | /// This is just slightly wierd, however if you have a bunch of 339 | /// borrowed forms of members of the set, and you want to look at 340 | /// the real entries and possibly add/update/remove them, then 341 | /// this method is for you. 342 | pub fn update_many(&self, elts: E, mut f: F) -> Self 343 | where 344 | Q: Ord, 345 | K: Borrow, 346 | E: IntoIterator, 347 | F: FnMut(Q, Option<&K>) -> Option, 348 | { 349 | let root = 350 | self.0 351 | .update_many(elts.into_iter().map(|k| (k, ())), &mut |q, (), cur| { 352 | let cur = cur.map(|(k, ())| k); 353 | f(q, cur).map(|k| (k, ())) 354 | }); 355 | Set(root) 356 | } 357 | 358 | /// return a new set with k inserted into it. If k already 359 | /// exists in the old set return true, else false. If the 360 | /// element already exists in the set memory will not be 361 | /// allocated. 362 | pub fn insert(&self, k: K) -> (Self, bool) { 363 | if self.contains(&k) { 364 | (self.clone(), true) 365 | } else { 366 | (Set(self.0.insert(k, ()).0), false) 367 | } 368 | } 369 | 370 | /// insert `k` with copy on write semantics. if `self` is a unique 371 | /// reference to the set, then k will be inserted in 372 | /// place. Otherwise, only the parts of the set necessary to 373 | /// insert `k` will be copied, and then the copies will be 374 | /// mutated. self will share all the parts that weren't modfied 375 | /// with any previous clones. 376 | pub fn insert_cow(&mut self, k: K) -> bool { 377 | self.0.insert_cow(k, ()).is_some() 378 | } 379 | 380 | /// return true if the set contains k, else false. Runs in 381 | /// log(N) time and constant space. where N is the size of 382 | /// the set. 383 | pub fn contains<'a, Q>(&'a self, k: &Q) -> bool 384 | where 385 | Q: ?Sized + Ord, 386 | K: Borrow, 387 | { 388 | self.0.get(k).is_some() 389 | } 390 | 391 | /// return a reference to the item in the set that is equal to the 392 | /// given value, or None if no such value exists. 393 | pub fn get<'a, Q>(&'a self, k: &Q) -> Option<&K> 394 | where 395 | Q: ?Sized + Ord, 396 | K: Borrow, 397 | { 398 | self.0.get_key(k) 399 | } 400 | 401 | /// return a new set with k removed. Runs in log(N) time 402 | /// and log(N) space, where N is the size of the set 403 | pub fn remove(&self, k: &Q) -> (Self, bool) 404 | where 405 | K: Borrow, 406 | { 407 | let (t, prev) = self.0.remove(k); 408 | (Set(t), prev.is_some()) 409 | } 410 | 411 | /// remove `k` from the set in place with copy on write semantics 412 | /// (see `insert_cow`). return true if `k` was in the set. 413 | pub fn remove_cow(&mut self, k: &Q) -> bool 414 | where 415 | K: Borrow, 416 | { 417 | self.0.remove_cow(k).is_some() 418 | } 419 | 420 | /// return the union of 2 sets. Runs in O(log(N) + M) time and 421 | /// space, where N is the largest of the two sets, and M is the 422 | /// number of chunks that intersect, which is roughly proportional 423 | /// to the size of the intersection. 424 | /// 425 | /// # Examples 426 | /// ``` 427 | /// use core::iter::FromIterator; 428 | /// use self::immutable_chunkmap::set::SetM; 429 | /// 430 | /// let s0 = SetM::from_iter(0..10); 431 | /// let s1 = SetM::from_iter(5..15); 432 | /// let s2 = s0.union(&s1); 433 | /// for i in 0..15 { 434 | /// assert!(s2.contains(&i)); 435 | /// } 436 | /// ``` 437 | pub fn union(&self, other: &Set) -> Self { 438 | Set(Tree::union(&self.0, &other.0, &mut |_, (), ()| Some(()))) 439 | } 440 | 441 | /// return the intersection of 2 sets. Runs in O(log(N) + M) time 442 | /// and space, where N is the smallest of the two sets, and M is 443 | /// the number of intersecting chunks. 444 | /// 445 | /// # Examples 446 | /// use core::iter::FromIterator; 447 | /// use self::immutable_chunkmap::set::SetM; 448 | /// 449 | /// let s0 = SetM::from_iter(0..100); 450 | /// let s1 = SetM::from_iter(20..50); 451 | /// let s2 = s0.intersect(&s1); 452 | /// 453 | /// assert!(s2.len() == 30); 454 | /// for i in 0..100 { 455 | /// if i < 20 || i >= 50 { 456 | /// assert!(!s2.contains(&i)); 457 | /// } else { 458 | /// assert!(s2.contains(&i)); 459 | /// } 460 | /// } 461 | pub fn intersect(&self, other: &Set) -> Self { 462 | Set(Tree::intersect( 463 | &self.0, 464 | &other.0, 465 | &mut |_, (), ()| Some(()), 466 | )) 467 | } 468 | 469 | /// Return the difference of two sets. Runs in O(log(N) + M) time 470 | /// and space, where N is the smallest of the two sets, and M is 471 | /// the number of intersecting chunks. 472 | /// 473 | /// # Examples 474 | /// ``` 475 | /// use core::iter::FromIterator; 476 | /// use self::immutable_chunkmap::set::SetM; 477 | /// 478 | /// let s0 = SetM::from_iter(0..100); 479 | /// let s1 = SetM::from_iter(0..50); 480 | /// let s2 = s0.diff(&s1); 481 | /// 482 | /// assert!(s2.len() == 50); 483 | /// for i in 0..50 { 484 | /// assert!(!s2.contains(&i)); 485 | /// } 486 | /// for i in 50..100 { 487 | /// assert!(s2.contains(&i)); 488 | /// } 489 | /// ``` 490 | pub fn diff(&self, other: &Set) -> Self 491 | where 492 | K: Debug, 493 | { 494 | Set(Tree::diff(&self.0, &other.0, &mut |_, (), ()| None)) 495 | } 496 | 497 | /// get the number of elements in the map O(1) time and space 498 | pub fn len(&self) -> usize { 499 | self.0.len() 500 | } 501 | 502 | /// return an iterator over the subset of elements in the 503 | /// set that are within the specified range. 504 | /// 505 | /// The returned iterator runs in O(log(N) + M) time, and 506 | /// constant space. N is the number of elements in the 507 | /// tree, and M is the number of elements you examine. 508 | /// 509 | /// if lbound >= ubound the returned iterator will be empty 510 | pub fn range<'a, Q, R>(&'a self, r: R) -> SetIter<'a, R, Q, K, SIZE> 511 | where 512 | Q: Ord + ?Sized + 'a, 513 | K: 'a + Clone + Ord + Borrow, 514 | R: RangeBounds + 'a, 515 | { 516 | SetIter(self.0.range(r)) 517 | } 518 | } 519 | 520 | impl Set 521 | where 522 | K: Ord + Clone + Debug, 523 | { 524 | #[allow(dead_code)] 525 | pub(crate) fn invariant(&self) -> () { 526 | self.0.invariant() 527 | } 528 | } 529 | -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | use crate::{avl, chunk::DEFAULT_SIZE, map::MapM, set::SetM}; 2 | use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec, vec}; 3 | use core::{ 4 | borrow::Borrow, 5 | cmp::Ordering, 6 | fmt::Debug, 7 | hash::Hash, 8 | i32, 9 | iter::{FromIterator, IntoIterator}, 10 | ops::Bound::{Excluded, Included}, 11 | }; 12 | use hashbrown::{HashMap, HashSet}; 13 | use rand::Rng; 14 | 15 | const STRSIZE: usize = 10; 16 | const SIZE: usize = 500000; 17 | const CHECK: usize = 5000; 18 | 19 | macro_rules! make_tests { 20 | ($name:ident) => { 21 | paste::item! { 22 | #[test] 23 | fn [<$name _i32_i32>]() { 24 | $name::(); 25 | } 26 | } 27 | 28 | paste::item! { 29 | #[test] 30 | fn [<$name _i32_usize>]() { 31 | $name::(); 32 | } 33 | } 34 | 35 | paste::item! { 36 | #[test] 37 | fn [<$name _usize_i32>]() { 38 | $name::(); 39 | } 40 | } 41 | 42 | paste::item! { 43 | #[test] 44 | fn [<$name _usize_usize>]() { 45 | $name::(); 46 | } 47 | } 48 | 49 | paste::item! { 50 | #[test] 51 | fn [<$name _i32_string>]() { 52 | $name::>(); 53 | } 54 | } 55 | 56 | paste::item! { 57 | #[test] 58 | fn [<$name _string_i32>]() { 59 | $name::, i32>(); 60 | } 61 | } 62 | 63 | paste::item! { 64 | #[test] 65 | fn [<$name _usize_string_pair>]() { 66 | $name::, Arc)>(); 67 | } 68 | } 69 | 70 | paste::item! { 71 | #[test] 72 | fn [<$name _string_pair_usize>]() { 73 | $name::<(Arc, Arc), usize>(); 74 | } 75 | } 76 | }; 77 | } 78 | 79 | trait Rand: Sized { 80 | fn rand(r: &mut R) -> Self; 81 | } 82 | 83 | impl Rand for (T, U) { 84 | fn rand(r: &mut R) -> Self { 85 | (T::rand(r), U::rand(r)) 86 | } 87 | } 88 | 89 | impl Rand for Arc { 90 | fn rand(r: &mut R) -> Self { 91 | let mut s = String::new(); 92 | for _ in 0..STRSIZE { 93 | s.push(r.gen()) 94 | } 95 | Arc::from(s.as_str()) 96 | } 97 | } 98 | 99 | impl Rand for i32 { 100 | fn rand(r: &mut R) -> Self { 101 | r.gen() 102 | } 103 | } 104 | 105 | impl Rand for usize { 106 | fn rand(r: &mut R) -> Self { 107 | r.gen() 108 | } 109 | } 110 | 111 | fn random() -> T { 112 | let mut rng = rand::thread_rng(); 113 | T::rand(&mut rng) 114 | } 115 | 116 | fn randvec(len: usize) -> Vec { 117 | let mut v: Vec = Vec::new(); 118 | for _ in 0..len { 119 | v.push(random()) 120 | } 121 | v 122 | } 123 | 124 | fn permutation(v: &Vec) -> Vec { 125 | let p = randvec::(v.len()); 126 | let mut p = p.iter().zip(v).collect::>(); 127 | p.sort_by(|(k0, _), (k1, _)| k0.cmp(k1)); 128 | p.into_iter().map(|(_, v)| v.clone()).collect::>() 129 | } 130 | 131 | fn insert(r: I) -> avl::Tree 132 | where 133 | I: IntoIterator, 134 | K: Ord + Clone + Debug, 135 | V: Clone + Debug, 136 | { 137 | let mut t = avl::Tree::new(); 138 | for (k, v) in r { 139 | t = t.insert(k.clone(), v.clone()).0; 140 | if t.len() % CHECK == 0 { 141 | t.invariant(); 142 | } 143 | } 144 | t.invariant(); 145 | t 146 | } 147 | 148 | #[test] 149 | fn test_insert_int_seq_asc() { 150 | let t = insert((0..SIZE).into_iter().map(|i| (i, i))); 151 | let len = t.len(); 152 | if len != SIZE { 153 | panic!("length is wrong expected 10000 got {}", len) 154 | } 155 | } 156 | 157 | #[test] 158 | fn test_insert_int_seq_dec() { 159 | let t = insert(((0..SIZE).into_iter().map(|i| (i, i))).rev()); 160 | let len = t.len(); 161 | if len != SIZE { 162 | panic!("length is wrong expected 10000 got {}", len) 163 | } 164 | } 165 | 166 | #[test] 167 | fn test_insert_int_rand() { 168 | insert(randvec::(SIZE).iter().map(|i| (*i, *i))); 169 | () 170 | } 171 | 172 | fn test_get_rand_gen() 173 | where 174 | K: Ord + Clone + Debug + Hash + Rand, 175 | V: Ord + Clone + Debug + Hash + Rand, 176 | { 177 | let mut vals = randvec::<(K, V)>(SIZE); 178 | dedup_with(&mut vals, |(ref k, _)| k); 179 | let t = insert(vals.iter().cloned()); 180 | for (k, v) in &vals { 181 | assert_eq!(t.get(k).unwrap(), v); 182 | } 183 | } 184 | 185 | make_tests!(test_get_rand_gen); 186 | 187 | fn test_insert_remove_rand_gen() 188 | where 189 | K: Ord + Clone + Debug + Rand + Hash, 190 | V: Ord + Clone + Debug + Rand + Hash, 191 | { 192 | let mut v = randvec::<(K, V)>(SIZE); 193 | dedup_with(&mut v, |(ref k, _)| k); 194 | let mut t = avl::Tree::<_, _, DEFAULT_SIZE>::new(); 195 | for (k, v) in &v { 196 | let (tn, p) = t.insert(k.clone(), v.clone()); 197 | assert_eq!(p, None); 198 | t = tn; 199 | assert_eq!(t.get(k).unwrap(), v); 200 | if t.len() % CHECK == 0 { 201 | let (tn, p) = t.remove(k); 202 | assert_eq!(p.as_ref(), Some(v)); 203 | t = tn; 204 | assert_eq!(t.get(k), Option::None); 205 | } 206 | } 207 | t.invariant(); 208 | } 209 | 210 | make_tests!(test_insert_remove_rand_gen); 211 | 212 | fn test_cow_rand_gen() 213 | where 214 | K: Ord + Clone + Debug + Rand + Hash, 215 | V: Ord + Clone + Debug + Rand + Hash, 216 | { 217 | let mut model: HashMap = HashMap::new(); 218 | let mut v = randvec::<(K, V)>(SIZE); 219 | let mut o = randvec::<(K, V)>(SIZE); 220 | dedup_with(&mut v, |(ref k, _)| k); 221 | dedup_with(&mut o, |(ref k, _)| k); 222 | let v = v; 223 | let o = o; 224 | let t = insert(v.iter().cloned()); 225 | for (k, v) in &v { 226 | model.insert(k.clone(), v.clone()); 227 | } 228 | let mut cow = t.clone(); 229 | for (i, (k, v)) in o.iter().enumerate() { 230 | *cow.get_or_insert_cow(k.clone(), || v.clone()) = v.clone(); 231 | model.insert(k.clone(), v.clone()); 232 | assert_eq!(cow.get(k), Some(v)); 233 | if i > 0 && i % CHECK == 0 { 234 | loop { 235 | let j = rand::thread_rng().gen_range(0..i); 236 | let k = &o[j].0; 237 | if let Some(v) = model.remove(k) { 238 | let p = cow.remove_cow(k); 239 | assert_eq!(p.as_ref(), Some(&v)); 240 | assert_eq!(cow.get(k), Option::None); 241 | break; 242 | } 243 | } 244 | } 245 | if i > 0 && i % CHECK == 1 { 246 | loop { 247 | let j = rand::thread_rng().gen_range(0..i); 248 | let k = &o[j].0; 249 | if let Some(mv) = model.get_mut(k) { 250 | let v: V = random(); 251 | *cow.get_mut_cow(k).unwrap() = v.clone(); 252 | *mv = v.clone(); 253 | assert_eq!(cow.get(k), model.get(k)); 254 | break; 255 | } 256 | } 257 | } 258 | } 259 | cow.invariant(); 260 | t.invariant(); 261 | // check that the original is unchanged after the cow was modified 262 | assert_eq!(t.len(), v.len()); 263 | for (k, v) in &v { 264 | assert_eq!(t.get(k), Some(v)) 265 | } 266 | // check that the cow matches the model 267 | assert_eq!(model.len(), cow.len()); 268 | for (k, v) in &model { 269 | assert_eq!(cow.get(k), Some(v)) 270 | } 271 | for (k, v) in &cow { 272 | assert_eq!(model.get(k), Some(v)) 273 | } 274 | } 275 | 276 | make_tests!(test_cow_rand_gen); 277 | 278 | #[test] 279 | fn test_insert_many_small() { 280 | let v: Vec = vec![ 281 | 1, 9, 16, 11, 7, 12, 8, 12, 12, 11, 9, 12, 9, 7, 16, 9, 1, 9, 1, 1, 22, 112, 282 | ]; 283 | let mut t = 284 | avl::Tree::<_, _, DEFAULT_SIZE>::new().insert_many(v.iter().map(|k| (*k, *k))); 285 | t.invariant(); 286 | for k in &v { 287 | assert_eq!(t.get(k).unwrap(), k) 288 | } 289 | t = t.remove(&22i32).0; 290 | t = t.remove(&112i32).0; 291 | t.invariant(); 292 | for k in &v { 293 | if *k == 22i32 || *k == 112i32 { 294 | assert_eq!(t.get(k), Option::None); 295 | } else { 296 | assert_eq!(t.get(k), Option::Some(k)); 297 | } 298 | } 299 | let v2: Vec = vec![12i32, 987i32, 19i32, 98i32]; 300 | t = t.insert_many(v2.iter().map(|k| (k.clone(), k.clone()))); 301 | for k in &v2 { 302 | assert_eq!(t.get(k).unwrap(), k); 303 | } 304 | } 305 | 306 | fn dedup_with(v: &mut Vec, f: F) 307 | where 308 | F: Fn(&T) -> &K, 309 | K: Ord + Clone + Hash, 310 | { 311 | let mut seen = HashSet::new(); 312 | let mut i = 0; 313 | while i < v.len() { 314 | if seen.contains(f(&v[i])) { 315 | v.remove(i); 316 | } else { 317 | seen.insert(f(&v[i]).clone()); 318 | i += 1 319 | } 320 | } 321 | } 322 | 323 | fn test_insert_many_gen() 324 | where 325 | K: Ord + Clone + Debug + Rand + Hash, 326 | V: Ord + Clone + Debug + Rand + Hash, 327 | { 328 | let mut v = randvec::<(K, V)>(SIZE); 329 | dedup_with(&mut v, |(ref k, _)| k); 330 | let mut t = avl::Tree::<_, _, DEFAULT_SIZE>::new() 331 | .insert_many(v.iter().map(|(k, v)| (k.clone(), v.clone()))); 332 | t.invariant(); 333 | for (k, v) in &v { 334 | assert_eq!(t.get(k).unwrap(), v) 335 | } 336 | { 337 | let mut i = 0; 338 | for (k, _) in &v { 339 | if i % CHECK == 0 { 340 | t = t.remove(k).0; 341 | t.invariant(); 342 | } 343 | i = i + 1; 344 | } 345 | i = 0; 346 | for (k, v) in &v { 347 | if i % CHECK == 0 { 348 | assert_eq!(t.get(k), None); 349 | } else { 350 | assert_eq!(t.get(k), Some(v)); 351 | } 352 | i = i + 1; 353 | } 354 | }; 355 | let v2 = { 356 | let len = v.len(); 357 | v.append(&mut randvec::<(K, V)>(SIZE)); 358 | dedup_with(&mut v, |(ref k, _)| k); 359 | v.split_off(len) 360 | }; 361 | t = t.insert_many(v2.iter().map(|(k, v)| (k.clone(), v.clone()))); 362 | t.invariant(); 363 | { 364 | let mut i = 0; 365 | for (k, v) in &v { 366 | if i % CHECK != 0 { 367 | assert_eq!(t.get(k), Some(v)); 368 | } 369 | i += 1 370 | } 371 | } 372 | for (k, v) in &v2 { 373 | assert_eq!(t.get(k), Some(v)); 374 | } 375 | let mut i = 0; 376 | t = t.update_many( 377 | v2.iter().map(|(k, v)| (k.clone(), v.clone())), 378 | &mut |k, v, cur| { 379 | i += 1; 380 | assert_eq!(cur, Some((&k, &v))); 381 | None 382 | }, 383 | ); 384 | t.invariant(); 385 | assert_eq!(i, v2.len()); 386 | for (k, _) in &v2 { 387 | assert_eq!(t.get(k), None) 388 | } 389 | } 390 | 391 | make_tests!(test_insert_many_gen); 392 | 393 | fn test_map_rand_gen() 394 | where 395 | K: Ord + Clone + Debug + Rand + Hash, 396 | V: Ord + Clone + Debug + Rand + Hash, 397 | { 398 | let mut vals = randvec::<(K, V)>(SIZE); 399 | dedup_with(&mut vals, |(ref k, _)| k); 400 | let mut t = MapM::new(); 401 | let mut i = 0; 402 | for (k, v) in &vals { 403 | t = t.insert(k.clone(), v.clone()).0; 404 | assert_eq!(t.get(k).unwrap(), v); 405 | i = i + 1; 406 | } 407 | for (k, v) in &vals { 408 | assert_eq!(t.get(k).unwrap(), v); 409 | } 410 | t.invariant(); 411 | 412 | i = 0; 413 | for (k, _) in &vals { 414 | t = t.remove(k).0; 415 | i = i + 1; 416 | } 417 | for (k, _) in &vals { 418 | assert_eq!(t.get(k), Option::None); 419 | } 420 | t.invariant(); 421 | } 422 | 423 | make_tests!(test_map_rand_gen); 424 | 425 | fn test_map_iter_gen() 426 | where 427 | K: Ord + Clone + Debug + Rand + Hash, 428 | V: Ord + Clone + Debug + Rand + Hash, 429 | { 430 | let mut vals = randvec::<(K, V)>(SIZE); 431 | dedup_with(&mut vals, |(ref k, _)| k); 432 | let t = MapM::new().insert_many(vals.iter().cloned()); 433 | t.invariant(); 434 | assert_eq!(vals.len(), t.len()); 435 | vals.sort_unstable_by(|t0, t1| t0.0.cmp(&t1.0)); 436 | let mut i = 0; 437 | for (k, v) in &t { 438 | let (k_, v_) = (&vals[i].0, &vals[i].1); 439 | assert_eq!(k, k_); 440 | assert_eq!(v, v_); 441 | i = i + 1; 442 | } 443 | } 444 | 445 | make_tests!(test_map_iter_gen); 446 | 447 | fn test_map_iter_mut_gen() 448 | where 449 | K: Ord + Clone + Debug + Rand + Hash, 450 | V: Ord + Clone + Debug + Rand + Hash, 451 | { 452 | let mut vals = randvec::<(K, V)>(SIZE); 453 | dedup_with(&mut vals, |(ref k, _)| k); 454 | let mut model: BTreeMap = BTreeMap::from_iter(vals.iter().cloned()); 455 | let model_u: BTreeMap = BTreeMap::from_iter(vals.iter().cloned()); 456 | let mut t = MapM::new().insert_many(vals.iter().cloned()); 457 | let u = t.clone(); 458 | t.invariant(); 459 | u.invariant(); 460 | // t and model are equal 461 | assert_eq!(model.len(), t.len()); 462 | for ((k, v), (k_, v_)) in t.into_iter().zip(model.iter()) { 463 | assert_eq!(k, k_); 464 | assert_eq!(v, v_); 465 | } 466 | // mutate t and model 467 | assert_eq!(model.len(), t.len()); 468 | let mut iter = t.iter_mut_cow(); 469 | let mut miter = model.iter_mut(); 470 | let mut i = 0; 471 | while i < vals.len() { 472 | let ((k, v), (k_, v_)) = if rand::thread_rng().gen_bool(0.8) { 473 | let p = iter.next().unwrap(); 474 | let p_ = miter.next().unwrap(); 475 | (p, p_) 476 | } else { 477 | let p = iter.next_back().unwrap(); 478 | let p_ = miter.next_back().unwrap(); 479 | (p, p_) 480 | }; 481 | assert_eq!(k, k_); 482 | assert_eq!(v, v_); 483 | let n: V = random(); 484 | *v = n.clone(); 485 | *v_ = n; 486 | i += 1; 487 | } 488 | assert_eq!(iter.next(), None); 489 | assert_eq!(iter.next_back(), None); 490 | t.invariant(); 491 | // t and model are equal after mutation 492 | assert_eq!(model.len(), t.len()); 493 | for ((k, v), (k_, v_)) in t.into_iter().zip(model.iter()) { 494 | assert_eq!(k, k_); 495 | assert_eq!(v, v_); 496 | } 497 | // u is unchanged after t's mutation because COW 498 | u.invariant(); 499 | assert_eq!(model_u.len(), u.len()); 500 | for ((k, v), (k_, v_)) in u.into_iter().zip(model_u.iter()) { 501 | assert_eq!(k, k_); 502 | assert_eq!(v, v_); 503 | } 504 | } 505 | 506 | make_tests!(test_map_iter_mut_gen); 507 | 508 | #[test] 509 | fn test_map_range_small() { 510 | let mut v = Vec::new(); 511 | v.extend((-5000..5000).into_iter()); 512 | let t = MapM::new().insert_many(v.iter().map(|x| (*x, *x))); 513 | t.invariant(); 514 | assert_eq!(t.len(), 10000); 515 | { 516 | let mut i = 0; 517 | for e in &t { 518 | assert_eq!(e.0, e.1); 519 | assert_eq!(&v[i], e.0); 520 | assert!(i < 10000); 521 | i += 1 522 | } 523 | assert_eq!(i, 10000) 524 | } 525 | { 526 | let mut i = 5000; 527 | for e in t.range(0..100) { 528 | assert_eq!(e.0, e.1); 529 | assert_eq!(&v[i], e.0); 530 | assert!(i < 5100); 531 | i += 1 532 | } 533 | assert_eq!(i, 5100) 534 | } 535 | { 536 | let mut i = 5000; 537 | for e in t.range((Excluded(&0), Included(&100))) { 538 | assert_eq!(e.0, e.1); 539 | assert_eq!(&v[i + 1], e.0); 540 | assert!(i < 5100); 541 | i += 1 542 | } 543 | assert_eq!(i, 5100) 544 | } 545 | { 546 | let mut i = 7300; 547 | for e in t.range(2300..3500) { 548 | assert_eq!(e.0, e.1); 549 | assert_eq!(&v[i], e.0); 550 | assert!(i < 8500); 551 | i += 1 552 | } 553 | assert_eq!(i, 8500) 554 | } 555 | { 556 | let mut i = 7900; 557 | for e in t.range(2900..) { 558 | assert_eq!(e.0, e.1); 559 | assert_eq!(&v[i], e.0); 560 | assert!(i < 10000); 561 | i += 1 562 | } 563 | assert_eq!(i, 10000) 564 | } 565 | { 566 | let mut i = 0; 567 | for e in t.range(-5000..-4000) { 568 | assert_eq!(e.0, e.1); 569 | assert_eq!(&v[i], e.0); 570 | assert!(i < 1000); 571 | i += 1 572 | } 573 | assert_eq!(i, 1000) 574 | } 575 | { 576 | let mut i = 0; 577 | for _ in t.range((Excluded(&-5000), Excluded(&-4999))) { 578 | i += 1 579 | } 580 | assert_eq!(i, 0) 581 | } 582 | { 583 | let mut i = 0; 584 | for _ in t.range(1..=0) { 585 | i += 1 586 | } 587 | assert_eq!(i, 0) 588 | } 589 | } 590 | 591 | fn test_map_range_gen() 592 | where 593 | K: Ord + Clone + Debug + Rand + Hash, 594 | V: Ord + Clone + Debug + Rand + Hash, 595 | { 596 | let mut vals = randvec::<(K, V)>(SIZE); 597 | dedup_with(&mut vals, |(ref k, _)| k); 598 | let mut t: MapM = MapM::new(); 599 | t = t.insert_many(vals.iter().map(|(k, v)| (k.clone(), v.clone()))); 600 | t.invariant(); 601 | vals.sort_unstable_by(|t0, t1| t0.0.cmp(&t1.0)); 602 | let (start, end) = loop { 603 | let mut r = rand::thread_rng(); 604 | let i = r.gen_range(0..SIZE); 605 | let j = r.gen_range(0..SIZE); 606 | if i == j { 607 | continue; 608 | } else if i < j { 609 | break (i, j); 610 | } else { 611 | break (j, i); 612 | } 613 | }; 614 | { 615 | let mut i = start; 616 | for (k, v) in t.range(&vals[i].0..&vals[end].0) { 617 | let (k_, v_) = (&vals[i].0, &vals[i].1); 618 | assert_eq!(k, k_); 619 | assert_eq!(v, v_); 620 | assert!(i < end); 621 | i += 1; 622 | } 623 | assert_eq!(i, end); 624 | } 625 | { 626 | let mut i = start; 627 | let lbound = Excluded(&vals[i].0); 628 | let ubound = Included(&vals[end].0); 629 | for (k, v) in t.range((lbound, ubound)) { 630 | let (k_, v_) = (&vals[i + 1].0, &vals[i + 1].1); 631 | assert_eq!(k, k_); 632 | assert_eq!(v, v_); 633 | assert!(i < end); 634 | i += 1; 635 | } 636 | assert_eq!(i, end); 637 | } 638 | { 639 | let mut i = 0; 640 | for (k, v) in t.range(..&vals[end].0) { 641 | let (k_, v_) = (&vals[i].0, &vals[i].1); 642 | assert_eq!(k, k_); 643 | assert_eq!(v, v_); 644 | assert!(i < end); 645 | i += 1; 646 | } 647 | assert_eq!(i, end); 648 | } 649 | { 650 | let mut i = end - 1; 651 | let mut r = t.range(&vals[start].0..&vals[end].0); 652 | while let Some((k, v)) = r.next_back() { 653 | let (k_, v_) = (&vals[i].0, &vals[i].1); 654 | assert_eq!(k, k_); 655 | assert_eq!(v, v_); 656 | assert!(i >= start); 657 | i -= 1; 658 | } 659 | assert_eq!(start - 1, i); 660 | } 661 | } 662 | 663 | make_tests!(test_map_range_gen); 664 | 665 | fn test_set_gen + Ord + Clone + Debug + Rand + Hash>() { 666 | let mut v = randvec::(SIZE); 667 | dedup_with(&mut v, |k| k); 668 | let mut t = SetM::new(); 669 | let mut i = 0; 670 | for k in &v { 671 | let (tn, p) = t.insert(k.clone()); 672 | t = tn; 673 | assert_eq!(p, false); 674 | assert_eq!(t.contains(k), true); 675 | if i % (CHECK * 10) == 0 { 676 | for j in 0..i { 677 | assert_eq!(t.contains(&v[j]), true) 678 | } 679 | t.invariant() 680 | } 681 | i += 1 682 | } 683 | i = 0; 684 | for k in &v { 685 | let (tn, p) = t.remove(k); 686 | t = tn; 687 | assert_eq!(p, true); 688 | if i % (CHECK * 10) == 0 { 689 | for j in 0..i { 690 | assert_eq!(t.contains(&v[j]), false); 691 | } 692 | for j in (i + 1)..v.len() { 693 | assert_eq!(t.get(&v[j]), Some(&v[j])); 694 | } 695 | t.invariant() 696 | } 697 | i += 1 698 | } 699 | } 700 | 701 | #[test] 702 | fn test_set() { 703 | test_set_gen::(); 704 | test_set_gen::(); 705 | test_set_gen::>(); 706 | test_set_gen::<(i32, Arc)>(); 707 | } 708 | 709 | #[test] 710 | fn test_ord() { 711 | let v0 = randvec::(SIZE); 712 | let v1 = permutation(&v0); 713 | let mut v2 = permutation(&v0); 714 | let mut v3 = permutation(&v0); 715 | for i in (0..SIZE).rev() { 716 | if v2[i] < i32::MAX { 717 | v2[i] += 1; 718 | break; 719 | } 720 | } 721 | for i in (0..SIZE).rev() { 722 | if v3[i] > i32::MIN { 723 | v3[i] -= 1; 724 | break; 725 | } 726 | } 727 | let s0 = v0.iter().map(|v| v.clone()).collect::>(); 728 | let s1 = v1.iter().map(|v| v.clone()).collect::>(); 729 | let s2 = v2.iter().map(|v| v.clone()).collect::>(); 730 | let s3 = v3.iter().map(|v| v.clone()).collect::>(); 731 | assert!(s0 == s1); 732 | assert_eq!(s0.cmp(&s1), Ordering::Equal); 733 | assert!(s0 != s2); 734 | assert_eq!(s0.cmp(&s2), Ordering::Less); 735 | assert!(s0 != s3); 736 | assert_eq!(s0.cmp(&s3), Ordering::Greater); 737 | } 738 | 739 | fn test_union_gen + Ord + Clone + Debug + Rand + Hash>() { 740 | let mut v0 = randvec::(SIZE); 741 | let mut v1 = randvec::(SIZE); 742 | dedup_with(&mut v0, |k| k); 743 | dedup_with(&mut v1, |k| k); 744 | let m0 = MapM::from_iter(v0.iter().map(|k| (k.clone(), 1))); 745 | let m1 = MapM::from_iter(v1.iter().map(|k| (k.clone(), 1))); 746 | let m2 = m0.union(&m1, |_, v0, v1| Some(v0 + v1)); 747 | m2.invariant(); 748 | let mut hm = HashMap::new(); 749 | for k in v0.iter().chain(v1.iter()) { 750 | *hm.entry(k.clone()).or_insert(0) += 1; 751 | } 752 | for (k, v) in &hm { 753 | assert!(m2.get(k).unwrap() == v) 754 | } 755 | for (k, v) in &m2 { 756 | assert!(hm.get(k).unwrap() == v) 757 | } 758 | } 759 | 760 | #[test] 761 | fn test_union() { 762 | test_union_gen::(); 763 | test_union_gen::(); 764 | test_union_gen::>(); 765 | test_union_gen::<(i32, Arc)>(); 766 | } 767 | 768 | fn test_intersect_gen + Ord + Clone + Debug + Rand + Hash>() { 769 | let mut v0 = randvec::(SIZE); 770 | let mut v1 = randvec::(SIZE); 771 | dedup_with(&mut v0, |k| k); 772 | dedup_with(&mut v1, |k| k); 773 | let m0 = MapM::from_iter(v0.iter().map(|k| (k.clone(), 1))); 774 | let m1 = MapM::from_iter(v1.iter().map(|k| (k.clone(), 1))); 775 | let m2 = m0.intersect(&m1, |_, v0, v1| Some(v0 + v1)); 776 | m2.invariant(); 777 | let mut hm0 = HashMap::new(); 778 | let mut hm1 = HashMap::new(); 779 | let mut hm2 = HashMap::new(); 780 | let ins = |v: Vec, hm: &mut HashMap| { 781 | for k in v.iter() { 782 | *hm.entry(k.clone()).or_insert(0) += 1; 783 | } 784 | }; 785 | ins(v0, &mut hm0); 786 | ins(v1, &mut hm1); 787 | for (k, v0) in &hm0 { 788 | match hm1.get(k) { 789 | None => (), 790 | Some(v1) => { 791 | hm2.insert(k.clone(), *v0 + *v1); 792 | } 793 | } 794 | } 795 | for (k, v) in &hm2 { 796 | assert_eq!(v, m2.get(k).unwrap()) 797 | } 798 | for (k, v) in &m2 { 799 | assert_eq!(v, hm2.get(k).unwrap()) 800 | } 801 | } 802 | 803 | #[test] 804 | fn test_intersect() { 805 | test_intersect_gen::(); 806 | test_intersect_gen::(); 807 | test_intersect_gen::>(); 808 | test_intersect_gen::<(i32, Arc)>(); 809 | } 810 | 811 | fn test_diff_gen + Ord + Clone + Debug + Rand + Hash>() { 812 | let mut v0 = randvec::(SIZE); 813 | let mut v1 = randvec::(SIZE); 814 | dedup_with(&mut v0, |k| k); 815 | dedup_with(&mut v1, |k| k); 816 | let m0 = MapM::from_iter(v0.iter().map(|k| (k.clone(), ()))); 817 | let m1 = MapM::from_iter(v1.iter().map(|k| (k.clone(), ()))); 818 | let m2 = m0.diff(&m1, |_, (), ()| None); 819 | m2.invariant(); 820 | let mut hm = HashMap::new(); 821 | for k in v0.iter() { 822 | hm.insert(k, ()); 823 | } 824 | for k in &v1 { 825 | hm.remove(k); 826 | } 827 | for (k, ()) in &hm { 828 | m2.get(k).unwrap(); 829 | } 830 | for (k, ()) in &m2 { 831 | hm.get(k).unwrap(); 832 | } 833 | } 834 | 835 | #[test] 836 | fn test_diff() { 837 | test_diff_gen::(); 838 | test_diff_gen::(); 839 | test_diff_gen::>(); 840 | test_diff_gen::<(i32, Arc)>(); 841 | } 842 | 843 | #[cfg(feature = "serde")] 844 | #[test] 845 | fn test_serde_map() { 846 | let k = randvec::(SIZE); 847 | let v = randvec::(SIZE); 848 | let m0 = MapM::from_iter(k.iter().zip(v.iter()).map(|(k, v)| (*k, *v))); 849 | let json = serde_json::to_string(&m0).unwrap(); 850 | let m1: MapM = serde_json::from_str(&json).unwrap(); 851 | assert_eq!(&m0, &m1) 852 | } 853 | 854 | #[cfg(feature = "serde")] 855 | #[test] 856 | fn test_serde_set() { 857 | let v = randvec::(SIZE); 858 | let s0 = SetM::from_iter(v.iter().map(|v| *v)); 859 | let json = serde_json::to_string(&s0).unwrap(); 860 | let s1: SetM = serde_json::from_str(&json).unwrap(); 861 | assert_eq!(&s0, &s1) 862 | } 863 | 864 | #[cfg(feature = "rayon")] 865 | #[test] 866 | fn test_rayon_map() { 867 | use rayon::prelude::*; 868 | let k = randvec::(SIZE); 869 | let v = randvec::(SIZE); 870 | let m0 = MapM::from_iter(k.iter().zip(v.iter()).map(|(k, v)| (*k, *v))); 871 | let sum_par: i64 = m0.into_par_iter().map(|(_, v)| *v as i64).sum(); 872 | let sum_seq: i64 = m0.into_iter().map(|(_, v)| *v as i64).sum(); 873 | assert_eq!(sum_par, sum_seq); 874 | let m1 = m0 875 | .into_par_iter() 876 | .map(|(k, v)| (*k, *v)) 877 | .collect::>(); 878 | assert_eq!(m0, m1) 879 | } 880 | 881 | #[cfg(feature = "rayon")] 882 | #[test] 883 | fn test_rayon_set() { 884 | use rayon::prelude::*; 885 | let v = randvec::(SIZE); 886 | let s0 = SetM::from_iter(v.iter().copied()); 887 | let sum_par: i64 = s0.into_par_iter().map(|v| *v as i64).sum(); 888 | let sum_seq: i64 = s0.into_iter().map(|v| *v as i64).sum(); 889 | assert_eq!(sum_par, sum_seq); 890 | let s1 = s0.into_par_iter().map(|v| *v).collect::>(); 891 | assert_eq!(s0, s1) 892 | } 893 | 894 | fn remove_random_contig_slice( 895 | v: &Vec<(i32, i32)>, 896 | map: &MapM, 897 | ) -> (HashMap, MapM) { 898 | let start = rand::thread_rng().gen_range(0..v.len() - 1); 899 | let end = rand::thread_rng().gen_range(start..v.len()); 900 | let r = v 901 | .iter() 902 | .enumerate() 903 | .filter_map(|(i, kv)| { 904 | if i >= start && i < end { 905 | Some(kv) 906 | } else { 907 | None 908 | } 909 | }) 910 | .copied() 911 | .collect::>(); 912 | let map_r = map.update_many(r.iter().map(|(k, _)| (*k, ())), |_, _, _| None); 913 | map_r.invariant(); 914 | (r, map_r) 915 | } 916 | 917 | fn remove_random_entries( 918 | v: &Vec<(i32, i32)>, 919 | map: &MapM, 920 | ) -> (HashMap, MapM) { 921 | let mut rng = rand::thread_rng(); 922 | let r = v 923 | .iter() 924 | .filter(|(_, _)| rng.gen_range(0..4) == 0) 925 | .copied() 926 | .collect::>(); 927 | let map_r = map.update_many(r.iter().map(|(k, _)| (*k, ())), |_, _, _| None); 928 | map_r.invariant(); 929 | (r, map_r) 930 | } 931 | 932 | fn remove_maybe_nonexist_entries( 933 | map: &MapM, 934 | ) -> (HashMap, MapM) { 935 | let size = rand::thread_rng().gen_range(10..SIZE); 936 | let r = randvec::<(i32, i32)>(size) 937 | .into_iter() 938 | .collect::>(); 939 | let map_r = map.update_many(r.iter().map(|(k, _)| (*k, ())), |_, _, _| None); 940 | map_r.invariant(); 941 | (r, map_r) 942 | } 943 | 944 | fn check_removed(v: &Vec<(i32, i32)>, r: &HashMap, map_r: &MapM) { 945 | let expected_len = 946 | v.iter().fold( 947 | v.len(), 948 | |len, (k, _)| { 949 | if r.contains_key(k) { 950 | len - 1 951 | } else { 952 | len 953 | } 954 | }, 955 | ); 956 | assert_eq!(map_r.len(), expected_len); 957 | for (k, v) in v { 958 | if r.contains_key(k) { 959 | assert_eq!(None, map_r.get(k)); 960 | } else { 961 | assert_eq!(Some(v), map_r.get(k)); 962 | } 963 | } 964 | } 965 | 966 | #[test] 967 | fn test_remove_many_patterns() { 968 | let size = rand::thread_rng().gen_range(10..SIZE); 969 | let mut v = randvec::<(i32, i32)>(size); 970 | dedup_with(&mut v, |(k, _)| k); 971 | v.sort_by_key(|(k, _)| *k); 972 | let map = MapM::from_iter(v.iter().copied()); 973 | map.invariant(); 974 | for (k, v) in &v { 975 | assert_eq!(Some(v), map.get(k)); 976 | } 977 | let (r, map_r) = remove_random_contig_slice(&v, &map); 978 | check_removed(&v, &r, &map_r); 979 | let (r, map_r) = remove_random_entries(&v, &map); 980 | check_removed(&v, &r, &map_r); 981 | let (r, map_r) = remove_maybe_nonexist_entries(&map); 982 | check_removed(&v, &r, &map_r); 983 | } 984 | --------------------------------------------------------------------------------