├── .gitignore ├── LICENSE ├── README.md ├── cf_hashmap.hpp ├── cf_hashset.hpp ├── cf_memorypool.hpp └── examples ├── hashmap.cpp ├── hashset.cpp └── memorypool.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # example binaries 2 | examples/hashmap 3 | examples/hashset 4 | examples/memorypool 5 | 6 | # Prerequisites 7 | *.d 8 | 9 | # Object files 10 | *.o 11 | *.ko 12 | *.obj 13 | *.elf 14 | 15 | # Linker output 16 | *.ilk 17 | *.map 18 | *.exp 19 | 20 | # Precompiled Headers 21 | *.gch 22 | *.pch 23 | 24 | # Libraries 25 | *.lib 26 | *.a 27 | *.la 28 | *.lo 29 | 30 | # Shared objects (inc. Windows DLLs) 31 | *.dll 32 | *.so 33 | *.so.* 34 | *.dylib 35 | 36 | # Executables 37 | *.exe 38 | *.out 39 | *.app 40 | *.i*86 41 | *.x86_64 42 | *.hex 43 | 44 | # Debug files 45 | *.dSYM/ 46 | *.su 47 | *.idb 48 | *.pdb 49 | 50 | # Kernel Module Compile Results 51 | *.mod* 52 | *.cmd 53 | .tmp_versions/ 54 | modules.order 55 | Module.symvers 56 | Mkfile.old 57 | dkms.conf 58 | 59 | # QtCreator files 60 | *.config 61 | *.files 62 | *.includes 63 | *.creator 64 | *.creator.user 65 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cfstructs - cache friendly data structures 2 | 3 | A collection of single-header C++ data structures with focus on cache friendliness and performance. 4 | 5 | ------ 6 | 7 | This project was mostly inspired by [Godot Engine](https://godotengine.org/)'s [`OAHashMap`](https://github.com/godotengine/godot/blob/b22f048700105dec26154cc90f10b0ef34b3f5ed/core/oa_hash_map.h) type. 8 | 9 | Unfortunately, that class depends on other engine-internal classes, so it can't be ported easily to other projects. 10 | 11 | Another huge inspiration is Google's [`dense_hash_map` type](https://github.com/sparsehash/sparsehash/blob/4cb924025b8c622d1a1e11f4c1e9db15410c75fb/src/sparsehash/dense_hash_map), which is a lot easier to integrate into existing projects, but not as simple as a single-header library. 12 | 13 | This repositoy aims to implement similar containers, focussed on performance and ease of use (or more like, ease of *integration*). All data structures implemented here should not depend on any third party libraries (including `libc`). Not handling memory **at all** leaves the user of the library more fine grained control over memory management. 14 | 15 | ## Container types 16 | 17 | ### [`cf::hashmap`](https://github.com/karroffel/cfstructs/blob/master/cf_hashmap.hpp) 18 | 19 | The `cf::hashmap` is a HashMap implementation that uses open addressing with robinhood hashing. Its main focus is on lookup and iteration speed. 20 | 21 | The user has to hand the `cf::hashmap` a buffer which will hold all the data managed by the hashmap. This buffer is a single chunk of memory, the hashmap however will internally divide this buffer into 3 different "regions": 22 | - hashes 23 | - keys 24 | - values 25 | 26 | The "hashes" region stores the hash of each entry. Each hash is represented by a `uint32_t`. 27 | 28 | The "keys" region stores the keys of each entry, which are needed to resolve possible hash collisions. 29 | 30 | The "values" regions stores the values. Apart from storing and letting the caller read the value, the hashmap doesn't interact with this region much at all. 31 | 32 | A simple usage example can be found in the [`examples/hashmap.cpp`](https://github.com/karroffel/cfstructs/blob/master/examples/hashmap.cpp) file. 33 | 34 | ### [`cf::hashset`](https://github.com/karroffel/cfstructs/blob/master/cf_hashset.hpp) 35 | 36 | The `cf::hashset` is a HashSet implementation that operates in a similar way to `cf::hashmap` in that it uses open addressing with robinhood hashing. 37 | 38 | As with the `cf::hashmap`, this container hold all the data in a user-provided buffer. That buffer gets internally divided into 2 "regions": 39 | - hashes 40 | - values 41 | 42 | The regions have the same purpose as with `cf::hashmap`, but the "values" region corresponds to the "keys" region in the HashMap. 43 | 44 | A simple usage example can be found in the [`examples/hashset.cpp`](https://github.com/karroffel/cfstructs/blob/master/examples/hashset.cpp) file. 45 | 46 | ### [`cf::memorypool`](https://github.com/karroffel/cfstructs/blob/master/cf_memorypool.hpp) 47 | 48 | A basic memory allocator that uses a user provided buffer to allocate fixed size elements. 49 | 50 | The allocator works by re-using unused elements to point to the next unused element. 51 | When a new element should be allocated, the allocator grabs the last unused element it knew about and sets the pointer to the next unused element to the one saved in the previously allocated element. 52 | 53 | Because unused elements are mis-used to store the index to the next free element, only POD types can be used. 54 | Furthermore, the space required for each element in the buffer is the size of **the union of element type and index type**. 55 | 56 | For example, when using `uint8_t` as element type and `uint32_t` as index type, each element will need the same space as the `uint32_t`. 57 | The index type can be customized but defaults to `uint32_t`. 58 | 59 | A simple usage example can be found in the [`examples/memorypool.cpp`](https://github.com/karroffel/cfstructs/blob/master/examples/memorypool.cpp) file. 60 | 61 | ## Planned 62 | 63 | - I don't know, maybe something else that I need in a project. 64 | -------------------------------------------------------------------------------- /cf_hashmap.hpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | /// 6 | /// This is a single-header library that provides a cache-friendly hash map 7 | /// implementation that uses open addressing with robin hood hashing. 8 | /// 9 | #ifndef CF_HASHMAP_HPP 10 | #define CF_HASHMAP_HPP 11 | 12 | #include 13 | #include 14 | 15 | namespace cf { 16 | 17 | #define CF_HASHMAP_GET_BUFFER_SIZE(key_type, value_type, num_elements) \ 18 | ((sizeof(uint32_t) + sizeof(key_type) + sizeof(value_type)) * num_elements) 19 | 20 | /// A hashmap type that uses open addressing with robinhood hashing. 21 | /// The hashmap uses 3 different regions of memory: hashes, keys and values. 22 | /// Those regions are located next to each other in a buffer in a Struct-of-Arrays 23 | /// kind of fashion. 24 | /// This hashmap doesn't perform any hashing itself, so the the user has to provide 25 | /// the hash values. The keys have to be POD types. Comparision of keys to 26 | /// resolve hash collisions uses operator==, so this might need to be implemented 27 | /// if the key type is not a primitive type. 28 | template 29 | struct hashmap { 30 | 31 | private: 32 | size_t m_num_elements; 33 | 34 | size_t m_capacity; 35 | 36 | uint8_t *m_buffer; 37 | 38 | static const uint32_t EMPTY_HASH = 0; 39 | static const uint32_t DELETED_HASH_BIT = 1 << 31; 40 | 41 | template 42 | static void _swap(T &a, T &b) 43 | { 44 | T tmp = a; 45 | a = b; 46 | b = tmp; 47 | } 48 | 49 | // We want only hashes != 0 since we use that for detecting empty 50 | // entries. 51 | // The leftmost bit indicates that the entry was deleted in the past. 52 | // We can't use just a "deleted value" because otherwise we lose information 53 | // about the previous probe distance 54 | static uint32_t _hash(uint32_t hash) 55 | { 56 | if (hash == EMPTY_HASH) { 57 | hash = EMPTY_HASH + 1; 58 | } else if (hash & DELETED_HASH_BIT) { 59 | hash &= ~DELETED_HASH_BIT; 60 | } 61 | 62 | return hash; 63 | } 64 | 65 | uint32_t _get_probe_distance(uint32_t pos, uint32_t hash) const 66 | { 67 | hash = hash & ~DELETED_HASH_BIT; 68 | 69 | uint32_t ideal_pos = hash % m_capacity; 70 | 71 | return pos - ideal_pos; 72 | } 73 | 74 | bool _lookup_pos(uint32_t hash, const TKey &key, uint32_t &pos) const 75 | { 76 | pos = hash % m_capacity; 77 | uint32_t distance = 0; 78 | 79 | uint32_t *hashes = (uint32_t *) m_buffer; 80 | TKey *keys = (TKey *) (m_buffer + m_capacity * sizeof(uint32_t)); 81 | 82 | while (distance < m_capacity) { 83 | if (hashes[pos] == EMPTY_HASH) { 84 | return false; 85 | } 86 | 87 | if (distance > _get_probe_distance(pos, hashes[pos])) { 88 | return false; 89 | } 90 | 91 | if (hashes[pos] == hash && keys[pos] == key) { 92 | return true; 93 | } 94 | 95 | pos = (pos + 1) % m_capacity; 96 | distance++; 97 | } 98 | 99 | return false; 100 | } 101 | 102 | void insert(uint32_t hash, const TKey &key, const TValue &value) 103 | { 104 | 105 | if (m_num_elements == m_capacity) { 106 | // if this is the case then this will just keep trying to 107 | // swap stuff around, never terminating. 108 | return; 109 | } 110 | 111 | uint32_t distance = 0; 112 | uint32_t pos = hash % m_capacity; 113 | 114 | TKey _key = key; 115 | TValue _value = value; 116 | 117 | uint32_t *hashes = (uint32_t *) m_buffer; 118 | TKey *keys = (TKey *) (m_buffer + sizeof(uint32_t) * m_capacity); 119 | TValue *values = (TValue *) (m_buffer + (sizeof(uint32_t) + sizeof(TKey)) * m_capacity); 120 | 121 | while (distance < m_capacity) { 122 | 123 | // An empty slot, put our stuff in there, then we're done! 124 | if (hashes[pos] == EMPTY_HASH) { 125 | hashes[pos] = hash; 126 | keys[pos] = _key; 127 | values[pos] = _value; 128 | m_num_elements++; 129 | return; 130 | } 131 | 132 | uint32_t exiting_distance = _get_probe_distance(pos, hashes[pos]); 133 | if (exiting_distance < distance) { 134 | // we found a slot that should be further to the right 135 | 136 | if (hashes[pos] & DELETED_HASH_BIT) { 137 | // buuuut it was deleted so we can use it 138 | 139 | hashes[pos] = hash; 140 | keys[pos] = _key; 141 | values[pos] = _value; 142 | m_num_elements++; 143 | return; 144 | } 145 | 146 | // swap out the entry and now operate on the other value 147 | // that should be further to the right 148 | _swap(hash, hashes[pos]); 149 | _swap(_key, keys[pos]); 150 | _swap(_value, values[pos]); 151 | distance = exiting_distance; 152 | } 153 | 154 | pos = (pos + 1) % m_capacity; 155 | distance++; 156 | } 157 | 158 | } 159 | 160 | public: 161 | 162 | /// An iterator for iterating over key-value pairs. Use `iter_start()` to acquire 163 | /// such an iterator. Use `iter_next()` to advance the iteration. 164 | struct iter { 165 | size_t offset; 166 | }; 167 | 168 | /// This function constructs a new hashmap value. 169 | /// The buffer is a chunk of memory that will be used as the storage. It should probably be 170 | /// created by using the `CF_HASHMAP_GET_BUFFER_SIZE` macro. 171 | /// Don't modify the contents of the buffer after handing it to a hashmap. 172 | static hashmap create(size_t buffer_size, void *buffer) 173 | { 174 | hashmap map = {}; 175 | 176 | map.m_buffer = (uint8_t *) buffer; 177 | map.m_num_elements = 0; 178 | map.m_capacity = (size_t)(buffer_size / (sizeof(TKey) + sizeof(TValue) + sizeof(uint32_t))); 179 | 180 | size_t capacity = map.m_capacity; 181 | 182 | uint32_t *hashes = (uint32_t *) map.m_buffer; 183 | 184 | for (size_t i = 0; i < capacity; i++) { 185 | hashes[i] = EMPTY_HASH; 186 | } 187 | 188 | return map; 189 | } 190 | 191 | /// Associate a key with a value. The hash is the hash value of the key. This hashmap doesn't 192 | /// perform any hashing itself, so the caller has to provide the hash. 193 | /// For collision resolution, the key itself has to be provided as well. 194 | void set(uint32_t hash, const TKey &key, const TValue &value) 195 | { 196 | hash = _hash(hash); 197 | uint32_t pos = 0; 198 | bool exists = _lookup_pos(hash, key, pos); 199 | 200 | TValue *values = (TValue *) (m_buffer + (sizeof(uint32_t) + sizeof(TKey)) * m_capacity); 201 | 202 | if (exists) { 203 | values[pos] = value; 204 | } else { 205 | insert(hash, key, value); 206 | } 207 | } 208 | 209 | /// Lookup a value in the hashmap. The hash is the hash of the key. The key value itself 210 | /// has to be provided in case a collision occurs. 211 | /// If an entry is found, the value will be written to the out-parameter `value`. 212 | /// Returns true if an entry was found, false otherwise. 213 | bool lookup(uint32_t hash, const TKey &key, TValue &value) const 214 | { 215 | uint32_t pos = 0; 216 | bool exists = _lookup_pos(_hash(hash), key, pos); 217 | 218 | TValue *values = (TValue *) (m_buffer + (sizeof(uint32_t) + sizeof(TKey)) * m_capacity); 219 | 220 | if (exists) { 221 | value = values[pos]; 222 | return true; 223 | } 224 | 225 | return false; 226 | } 227 | 228 | /// Get the value associated with the given hash and key. 229 | /// This uses `lookup()` internally, but discards the bool return value 230 | /// and returns the value instead of having it as an out parameter. 231 | /// WARNING: If the entry was not found then the return value is **undefined**. 232 | inline TValue get(uint32_t hash, const TKey &key) const 233 | { 234 | TValue value; 235 | lookup(_hash(hash), key, value); 236 | return value; 237 | } 238 | 239 | /// Remove an entry from the hashtable by proving the hash and the key value, in case a 240 | /// collision occurs. 241 | void remove(uint32_t hash, const TKey &key) 242 | { 243 | uint32_t pos = 0; 244 | bool exists = _lookup_pos(_hash(hash), key, pos); 245 | uint32_t *hashes = (uint32_t *) m_buffer; 246 | 247 | if (!exists) { 248 | return; 249 | } 250 | 251 | hashes[pos] |= DELETED_HASH_BIT; 252 | m_num_elements--; 253 | } 254 | 255 | /// Create an iterator for the hashmap. Use `iter_next()` to advance the iteration. 256 | iter iter_start() const 257 | { 258 | hashmap::iter iter = {}; 259 | iter.offset = 0; 260 | return iter; 261 | } 262 | 263 | /// Advance the iterator to the next elements found. Key and value will be written to the 264 | /// out parameters `key` and `value` in case a next iteration was possible. 265 | /// In that case the function will return true. 266 | /// The function will return false when the end was reached. 267 | bool iter_next(iter &iter, TKey &key, TValue &value) const 268 | { 269 | uint32_t *hashes = (uint32_t *) m_buffer; 270 | TKey *keys = (TKey *) (m_buffer + sizeof(uint32_t) * m_capacity); 271 | TValue *values = (TValue *) (m_buffer + (sizeof(uint32_t) + sizeof(TKey)) * m_capacity); 272 | 273 | for (size_t i = iter.offset; i < m_capacity; i++) { 274 | if (hashes[i] == EMPTY_HASH) { 275 | continue; 276 | } 277 | if (hashes[i] & DELETED_HASH_BIT) { 278 | continue; 279 | } 280 | 281 | key = keys[i]; 282 | value = values[i]; 283 | iter.offset = i + 1; 284 | return true; 285 | } 286 | return false; 287 | } 288 | 289 | /// Calculates the load factor of the map. When the load factor is greater than 0.95 290 | /// then `copy()` should be used to relocate the hashmap for better performance. 291 | inline float load_factor() const 292 | { 293 | return m_num_elements / (float) m_capacity; 294 | } 295 | 296 | /// Creates a new hashmap using a different buffer. All the entries of the 297 | /// current map will be inserted into the new map. 298 | hashmap copy(size_t buffer_size, void *buffer) const 299 | { 300 | hashmap new_hashmap = hashmap::create(buffer_size, buffer); 301 | 302 | uint32_t *hashes = (uint32_t *) m_buffer; 303 | TKey *keys = (TKey *) (m_buffer + sizeof(uint32_t) * m_capacity); 304 | TValue *values = (TValue *) (m_buffer + (sizeof(uint32_t) + sizeof(TKey)) * m_capacity); 305 | 306 | for (size_t i = 0; i < m_capacity; i++) { 307 | if (hashes[i] == EMPTY_HASH) { 308 | continue; 309 | } 310 | if (hashes[i] & DELETED_HASH_BIT) { 311 | continue; 312 | } 313 | 314 | new_hashmap.insert(hashes[i], keys[i], values[i]); 315 | } 316 | 317 | return new_hashmap; 318 | 319 | } 320 | 321 | /// The number of elements in this hash map. 322 | size_t num_elements() const 323 | { 324 | return m_num_elements; 325 | } 326 | 327 | /// The capacity of how many elements *could* be held in this map. 328 | size_t capacity() const 329 | { 330 | return m_capacity; 331 | } 332 | }; 333 | 334 | } 335 | 336 | #endif 337 | -------------------------------------------------------------------------------- /cf_hashset.hpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | /// 6 | /// This is a single-header library that provides a chache-friend hash set that 7 | /// uses open addressing with robinhood hashing. 8 | /// 9 | #ifndef CF_HASHSET_HPP 10 | #define CF_HASHSET_HPP 11 | 12 | #include 13 | #include 14 | 15 | namespace cf { 16 | 17 | #define CF_HASHSET_GET_BUFFER_SIZE(key_type, num_elements) \ 18 | ((sizeof(uint32_t) + sizeof(key_type)) * num_elements) 19 | 20 | /// A hashset type that uses open addressing with robinhood hashing. 21 | /// The hashset uses 2 different regions of memory: hashes and values. 22 | /// Those regions are located next to each other in a buffer in a Struct-of-Arrays 23 | /// kind of fashion. 24 | /// The hashes are the hashes provided by the user. This hashset doesn't do any hashing itself. 25 | /// The values region contains the values. They are used to resolve collisions and check for existance. 26 | template 27 | struct hashset { 28 | 29 | private: 30 | size_t m_num_elements; 31 | 32 | size_t m_capacity; 33 | 34 | uint8_t *m_buffer; 35 | 36 | static const uint32_t EMPTY_HASH = 0; 37 | static const uint32_t DELETED_HASH_BIT = 1 << 31; 38 | 39 | template 40 | static void _swap(A &a, A &b) { 41 | A tmp = a; 42 | a = b; 43 | b = tmp; 44 | } 45 | 46 | // We want only hashes != 0 since we use that for detecting empty 47 | // entries. 48 | // The leftmost bit indicates that the entry was deleted in the past. 49 | // We can't use just a "deleted value" because otherwise we lose information 50 | // about the previous probe distance 51 | static uint32_t _hash(uint32_t hash) 52 | { 53 | if (hash == EMPTY_HASH) { 54 | hash = EMPTY_HASH + 1; 55 | } else if (hash & DELETED_HASH_BIT) { 56 | hash &= ~DELETED_HASH_BIT; 57 | } 58 | 59 | return hash; 60 | } 61 | 62 | uint32_t _get_probe_distance(uint32_t pos, uint32_t hash) const 63 | { 64 | hash = hash & ~DELETED_HASH_BIT; 65 | 66 | uint32_t ideal_pos = hash % m_capacity; 67 | 68 | return pos - ideal_pos; 69 | } 70 | 71 | bool _lookup_pos(uint32_t hash, const T &value, uint32_t &pos) const 72 | { 73 | pos = hash % m_capacity; 74 | uint32_t distance = 0; 75 | 76 | uint32_t *hashes = (uint32_t *) m_buffer; 77 | T *values = (T *) (m_buffer + m_capacity * sizeof(uint32_t)); 78 | 79 | while (distance < m_capacity) { 80 | if (hashes[pos] == EMPTY_HASH) { 81 | return false; 82 | } 83 | 84 | if (distance > _get_probe_distance(pos, hashes[pos])) { 85 | return false; 86 | } 87 | 88 | if (hashes[pos] == hash && values[pos] == value) { 89 | return true; 90 | } 91 | 92 | pos = (pos + 1) % m_capacity; 93 | distance++; 94 | } 95 | 96 | return false; 97 | } 98 | 99 | void _insert(uint32_t hash, const T &value) 100 | { 101 | if (m_num_elements == m_capacity) { 102 | // if this is the case then this will just keep trying to 103 | // swap stuff around, never terminating. 104 | return; 105 | } 106 | uint32_t distance = 0; 107 | uint32_t pos = hash % m_capacity; 108 | 109 | T _value = value; 110 | 111 | uint32_t *hashes = (uint32_t *) m_buffer; 112 | T *values = (T *) (m_buffer + sizeof(uint32_t) * m_capacity); 113 | 114 | while (distance < m_capacity) { 115 | 116 | // An empty slot, put our stuff in there, then we're done! 117 | if (hashes[pos] == EMPTY_HASH) { 118 | hashes[pos] = hash; 119 | values[pos] = _value; 120 | m_num_elements++; 121 | return; 122 | } 123 | 124 | uint32_t exiting_distance = _get_probe_distance(pos, hashes[pos]); 125 | if (exiting_distance < distance) { 126 | // we found a slot that should be further to the right 127 | 128 | if (hashes[pos] & DELETED_HASH_BIT) { 129 | // buuuut it was deleted so we can use it 130 | 131 | hashes[pos] = hash; 132 | values[pos] = _value; 133 | m_num_elements++; 134 | return; 135 | } 136 | 137 | // swap out the entry and now operate on the other value 138 | // that should be further to the right 139 | _swap(hash, hashes[pos]); 140 | _swap(_value, values[pos]); 141 | distance = exiting_distance; 142 | } 143 | 144 | pos = (pos + 1) % m_capacity; 145 | distance++; 146 | } 147 | } 148 | public: 149 | /// An iterator for iterating over the values. Use `iter_start()` to acquire 150 | /// such an iterator. Use `iter_next()` to advance the iteration. 151 | struct iter { 152 | size_t offset; 153 | }; 154 | 155 | /// This functions constructs a new hashet value. 156 | /// The buffer is a chunk of memory that will be used as the storage. That 157 | /// buffer should probably be created/sized by using the `CF_HASHSET_GET_BUFFER_SIZE` macro. 158 | /// Don't modify the contents of the buffer after handing it to a hashset. 159 | static hashset create(size_t buffer_size, void *buffer) 160 | { 161 | hashset set = {}; 162 | 163 | set.m_buffer = (uint8_t *) buffer; 164 | set.m_num_elements = 0; 165 | set.m_capacity = (size_t)(buffer_size / (sizeof(T) + sizeof(uint32_t))); 166 | 167 | size_t capacity = set.m_capacity; 168 | uint32_t *hashes = (uint32_t *) set.m_buffer; 169 | 170 | // Set the flags os that every element is considered empty 171 | for (size_t i = 0; i < capacity; i++) { 172 | hashes[i] = EMPTY_HASH; 173 | } 174 | 175 | return set; 176 | } 177 | 178 | /// Inserts a value into the hashset. Since this hashset doesn't perform any hashing 179 | /// itself, the caller has to provide the hash value. 180 | /// The value is used for checking for existance as well as collision resolution. 181 | void insert(uint32_t hash, const T &value) 182 | { 183 | hash = _hash(hash); 184 | uint32_t pos = 0; 185 | bool exists = _lookup_pos(hash, value, pos); 186 | 187 | if (exists) { 188 | return; 189 | } 190 | 191 | _insert(hash, value); 192 | } 193 | 194 | /// Checks if `value` is an element of the hashset. 195 | /// Returns true if an entry with `value` was found, false otherwise. 196 | bool has(uint32_t hash, const T &value) const 197 | { 198 | hash = _hash(hash); 199 | uint32_t _pos = 0; 200 | return _lookup_pos(hash, value, _pos); 201 | } 202 | 203 | /// Remove a value from the hashset. 204 | void remove(uint32_t hash, const T &value) 205 | { 206 | hash = _hash(hash); 207 | uint32_t pos = 0; 208 | bool exists = _lookup_pos(hash, value, pos); 209 | 210 | if (!exists) { 211 | return; 212 | } 213 | 214 | uint32_t *hashes = (uint32_t *) m_buffer; 215 | hashes[pos] |= DELETED_HASH_BIT; 216 | m_num_elements--; 217 | } 218 | 219 | /// Creates an iterator for the hashset. Use `iter_next()` to advance the iteration. 220 | iter iter_start() const 221 | { 222 | hashset::iter iter = {}; 223 | iter.offset = 0; 224 | return iter; 225 | } 226 | 227 | /// Advance the iterator to the next element found. The value will be written to the 228 | /// out parameter `value` if an element was found. 229 | /// If an element was found, true will be returned, otherwise false. 230 | bool iter_next(iter &iter, T &value) const 231 | { 232 | uint32_t *hashes = (uint32_t *) m_buffer; 233 | T *values = (T *) (m_buffer + sizeof(uint32_t) * m_capacity); 234 | 235 | for (size_t i = iter.offset; i < m_capacity; i++) { 236 | if (hashes[i] == EMPTY_HASH) { 237 | continue; 238 | } 239 | if (hashes[i] & DELETED_HASH_BIT) { 240 | continue; 241 | } 242 | 243 | value = values[i]; 244 | iter.offset = i + 1; 245 | return true; 246 | } 247 | return false; 248 | } 249 | 250 | /// Calculates the load factor of the hashset. If the load factor is greater than 0.95 251 | /// then `copy()` should be used to relocate the hashet for better performance. 252 | inline float load_factor() const 253 | { 254 | return m_num_elements / (float) m_capacity; 255 | } 256 | 257 | /// Creates a new hashset using a different buffer. All values of the current map 258 | /// will be inserted into the new map. 259 | hashset copy(size_t buffer_size, void *buffer) const 260 | { 261 | hashset new_hashset = hashset::create(buffer_size, buffer); 262 | 263 | uint32_t *hashes = (uint32_t *) m_buffer; 264 | T *values = (T *) (m_buffer + sizeof(uint32_t) * m_capacity); 265 | 266 | for (size_t i = 0; i < m_capacity; i++) { 267 | if (hashes[i] == EMPTY_HASH) { 268 | continue; 269 | } 270 | if (hashes[i] & DELETED_HASH_BIT) { 271 | continue; 272 | } 273 | 274 | new_hashset.insert(hashes[i], values[i]); 275 | } 276 | 277 | return new_hashset; 278 | } 279 | 280 | /// The number of elements in this hashset. 281 | size_t num_elements() const 282 | { 283 | return m_num_elements; 284 | } 285 | 286 | /// The capacity of how many elements *could* be held in this set. 287 | size_t capacity() const 288 | { 289 | return m_capacity; 290 | } 291 | 292 | }; 293 | 294 | 295 | } 296 | 297 | #endif 298 | -------------------------------------------------------------------------------- /cf_memorypool.hpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | /// 6 | /// This is a single-header library that provides an implementation of a 7 | /// memory pool / pool allocator. This memory pool can be used to manage 8 | /// fixed-size allocations in a user-given buffer. 9 | /// 10 | #ifndef CF_MEMORYPOOL_HPP 11 | #define CF_MEMORYPOOL_HPP 12 | 13 | #include 14 | #include 15 | 16 | /// In some cases (where the type of data to be allocated is small, usually) 17 | /// it is better to use a smaller indexing type (default is uint32_t). 18 | /// In such a case, this macro calculates the size of a buffer that can hold 19 | /// n elements. 20 | #define CF_MEMORYPOOL_BUFFER_SIZE_CUSTOM_IDX(type, idx, n) \ 21 | ((sizeof(type) > sizeof(idx) ? sizeof(type) : sizeof(idx)) * n) 22 | 23 | /// This macro calculates the size of a buffer that can hold n elements of 24 | /// type `type`. 25 | #define CF_MEMORYPOOL_BUFFER_SIZE(type, n) \ 26 | CF_MEMORYPOOL_BUFFER_SIZE_CUSTOM_IDX(type, uint32_t, n) 27 | 28 | namespace cf { 29 | 30 | /// A memory pool type that manages allocations of fixed size elements of 31 | /// type `T` in a user-given buffer. 32 | /// The allocator is implemented by re-using free elements to store the 33 | /// index of the next free element. This index type is uint32_t by default, 34 | /// but a custom index type can be used as well. 35 | /// Each element stored in the buffer is a union of the actual data and 36 | /// the index type. So for maximum space efficiency, the index type should 37 | /// be smaller than the value type. 38 | template 39 | struct memorypool { 40 | private: 41 | 42 | size_t m_num_elements; 43 | 44 | size_t m_capacity; 45 | 46 | IndexType next_free; 47 | 48 | typedef union { T value; IndexType next; } element_t; 49 | 50 | element_t *m_buffer; 51 | 52 | public: 53 | 54 | /// This function constructs a new memory pool. The `buffer` is a chunk of memory 55 | /// of size `buffer_size` which the memory pool will "draw" from. 56 | static memorypool create(size_t buffer_size, void *buffer) 57 | { 58 | memorypool pool; 59 | pool.m_buffer = (element_t *) buffer; 60 | 61 | pool.m_num_elements = 0; 62 | pool.m_capacity = buffer_size / sizeof(element_t); 63 | 64 | // now set all the next pointers to the next element 65 | for (IndexType i = 0; i < pool.m_capacity; i++) { 66 | pool.m_buffer[i].next = (i + 1) % pool.m_capacity; 67 | } 68 | 69 | pool.next_free = 0; 70 | 71 | return pool; 72 | } 73 | 74 | /// Allocate a new element of type `T`. 75 | /// If not enough space is available, `nullptr` will be returned. 76 | T *allocate() 77 | { 78 | if (m_num_elements == m_capacity) { 79 | return nullptr; 80 | } 81 | 82 | IndexType new_next_free = m_buffer[next_free].next; 83 | IndexType old_next_free = next_free; 84 | m_buffer[next_free].next = m_buffer[new_next_free].next; 85 | 86 | m_num_elements++; 87 | next_free = new_next_free; 88 | 89 | return &m_buffer[old_next_free].value; 90 | } 91 | 92 | /// Free a previously used element. 93 | void free(T *element) 94 | { 95 | IndexType index = ((element_t *) element - m_buffer); 96 | 97 | IndexType old_next_free = next_free; 98 | next_free = index; 99 | m_num_elements--; 100 | 101 | m_buffer[index].next = old_next_free; 102 | } 103 | 104 | /// The load factor of the memory pool (from 0.0 to 1.0). 105 | float load_factor() const 106 | { 107 | return (float)m_num_elements / m_capacity; 108 | } 109 | 110 | /// number of used elements in the memory pool 111 | size_t num_elements() const 112 | { 113 | return m_num_elements; 114 | } 115 | 116 | /// maxium number of elements the memory pool can hold. 117 | size_t capacity() const 118 | { 119 | return m_capacity; 120 | } 121 | 122 | }; 123 | 124 | } 125 | 126 | 127 | #endif 128 | -------------------------------------------------------------------------------- /examples/hashmap.cpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "cf_hashmap.hpp" 10 | 11 | int main(int argc, char **argv) 12 | { 13 | using cf::hashmap; 14 | 15 | printf("=== cf_hashmap tests ===\n"); 16 | 17 | { 18 | uint8_t buffer[CF_HASHMAP_GET_BUFFER_SIZE(uint32_t, uint16_t, 1024)]; 19 | auto map = hashmap::create(sizeof(buffer), buffer); 20 | assert(map.num_elements() == 0); 21 | 22 | map.set(13, 13, 42); 23 | assert(map.num_elements() == 1); 24 | 25 | map.set(13, 13, 37); 26 | assert(map.num_elements() == 1); 27 | 28 | { 29 | uint16_t value; 30 | 31 | if (map.lookup(13, 13, value)) { 32 | printf("map[13] = %hu\n", value); 33 | } else { 34 | printf("Whaaat, this is a bug. Please report it. Or better, fix it. =)\n"); 35 | } 36 | } 37 | 38 | map.set(13, 42, 1337); // cause a hash collision 39 | printf("map[42] = %hu\n", map.get(13, 42)); 40 | 41 | { 42 | uint16_t value; 43 | map.remove(13, 42); 44 | assert(map.num_elements() == 1); 45 | assert(!map.lookup(13, 42, value)); 46 | } 47 | 48 | map.set(12, 12, 24); 49 | map.set(1337, 1337, 7331); 50 | 51 | { 52 | // iter test 53 | printf("=== iterator test ===\n"); 54 | auto iter = map.iter_start(); 55 | 56 | uint32_t key; 57 | uint16_t value; 58 | 59 | while (map.iter_next(iter, key, value)) { 60 | printf("map[%u] = %hu\n", key, value); 61 | } 62 | } 63 | 64 | } 65 | 66 | #define CHAR_HASH(str) ((uint32_t) ((uintptr_t) str & 0xFFFFFFFF)) // don't judge me 67 | { 68 | // This actually performs pointer comparison. Just so you know. 69 | // If you want to have value comparisons then a POD string type 70 | // (probably just a wrapper for `const char *` should be used). 71 | 72 | printf("=== const char * test ===\n"); 73 | 74 | uint8_t old_buffer[CF_HASHMAP_GET_BUFFER_SIZE(const char *, uint16_t, 3)]; 75 | auto map = hashmap::create(sizeof(old_buffer), old_buffer); 76 | 77 | map.set(CHAR_HASH("Alice"), "Alice", 23); 78 | map.set(CHAR_HASH("Bob"), "Bob", 31); 79 | map.set(CHAR_HASH("Eve"), "Eve", 1337); 80 | 81 | { 82 | // iteration test 83 | auto iter = map.iter_start(); 84 | 85 | const char *key; 86 | uint16_t value; 87 | 88 | while (map.iter_next(iter, key, value)) { 89 | printf("map[\"%s\"] = %hu\n", key, value); 90 | } 91 | } 92 | 93 | { 94 | printf("=== resize test ===\n"); 95 | 96 | printf("old loadfactor: %f\n", map.load_factor()); 97 | 98 | uint8_t new_buffer[CF_HASHMAP_GET_BUFFER_SIZE(const char *, uint16_t, 256)]; 99 | auto new_map = map.copy(sizeof(new_buffer), new_buffer); 100 | 101 | printf("new loadfactor: %f\n", new_map.load_factor()); 102 | 103 | 104 | auto iter = new_map.iter_start(); 105 | 106 | const char *key; 107 | uint16_t value; 108 | 109 | while (new_map.iter_next(iter, key, value)) { 110 | printf("map[\"%s\"] = %hu\n", key, value); 111 | } 112 | } 113 | } 114 | 115 | return 0; 116 | } 117 | -------------------------------------------------------------------------------- /examples/hashset.cpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | #include 6 | #include 7 | 8 | #include "cf_hashset.hpp" 9 | 10 | int main(int argc, char **argv) 11 | { 12 | using cf::hashset; 13 | 14 | printf("=== cf_hashset tests ===\n"); 15 | 16 | { 17 | uint8_t buffer[CF_HASHSET_GET_BUFFER_SIZE(uint32_t, 3)]; 18 | 19 | auto set = hashset::create(sizeof(buffer), buffer); 20 | 21 | assert(set.num_elements() == 0); 22 | 23 | set.insert(13, 13); 24 | 25 | assert(set.has(13, 13)); 26 | assert(set.num_elements() == 1); 27 | 28 | set.insert(13, 13); // insert the same thing again 29 | assert(set.num_elements() == 1); 30 | 31 | set.insert(1337, 1337); 32 | assert(set.num_elements() == 2); 33 | 34 | set.insert(11, 11); 35 | set.insert(12, 12); // the set isn't big enough to deal with this, 36 | // so it will be discarded. 37 | set.remove(11, 11); 38 | 39 | set.remove(13, 13); 40 | assert(!set.has(13, 13)); 41 | assert(set.num_elements() == 1); 42 | 43 | set.insert(13, 13); 44 | set.insert(13, 21); // cause a hash collision 45 | 46 | { 47 | // iter test 48 | printf("=== iterator test ===\n"); 49 | 50 | auto iter = set.iter_start(); 51 | 52 | uint32_t value; 53 | 54 | printf("{"); 55 | while (set.iter_next(iter, value)) { 56 | printf("%u, ", value); 57 | } 58 | printf("}\n"); 59 | } 60 | 61 | { 62 | // copy test 63 | printf("=== copy test ===\n"); 64 | 65 | printf("old loadfactor: %f\n", set.load_factor()); 66 | 67 | uint8_t new_buffer[CF_HASHSET_GET_BUFFER_SIZE(uint32_t, 256)]; 68 | auto new_set = set.copy(sizeof(new_buffer), new_buffer); 69 | 70 | printf("new loadfactor: %f\n", new_set.load_factor()); 71 | 72 | 73 | auto iter = new_set.iter_start(); 74 | 75 | uint32_t value; 76 | 77 | printf("{"); 78 | while (new_set.iter_next(iter, value)) { 79 | printf("%u, ", value); 80 | } 81 | printf("}\n"); 82 | } 83 | } 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /examples/memorypool.cpp: -------------------------------------------------------------------------------- 1 | /* This Source Code Form is subject to the terms of the Mozilla Public 2 | * License, v. 2.0. If a copy of the MPL was not distributed with this 3 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 | 5 | #include 6 | #include 7 | 8 | #include "cf_memorypool.hpp" 9 | 10 | struct Velocity { 11 | float x; 12 | float y; 13 | }; 14 | 15 | int main(int argc, char **argv) 16 | { 17 | printf("=== memory pool tests ===\n"); 18 | 19 | { 20 | uint8_t buffer[CF_MEMORYPOOL_BUFFER_SIZE(Velocity, 5)]; 21 | auto pool = cf::memorypool::create(sizeof(buffer), buffer); 22 | 23 | { 24 | Velocity *ptrs[5]; 25 | 26 | for (int i = 0; i < 5; i++) { 27 | ptrs[i] = pool.allocate(); 28 | } 29 | 30 | pool.free(ptrs[1]); 31 | pool.free(ptrs[3]); 32 | 33 | ptrs[1] = pool.allocate(); 34 | ptrs[3] = pool.allocate(); 35 | 36 | // make sure non of them are null 37 | for (int i = 0; i < 5; i++) { 38 | printf("ptrs[%d] = %p\n", i, ptrs[i]); 39 | } 40 | 41 | pool.free(ptrs[0]); 42 | pool.free(ptrs[2]); 43 | pool.free(ptrs[4]); 44 | 45 | printf("load factor: %f\n", pool.load_factor()); 46 | 47 | pool.free(ptrs[1]); 48 | pool.free(ptrs[3]); 49 | } 50 | 51 | for (int i = 0; i < 5; i++) { 52 | pool.allocate(); // allocate and leak. Just fill the pool 53 | } 54 | 55 | assert(pool.allocate() == nullptr); 56 | 57 | } 58 | return 0; 59 | } 60 | --------------------------------------------------------------------------------