├── .gitattributes ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── README.tpl ├── src ├── lib.rs └── rayon.rs └── tests └── readme_up_to_date.rs /.gitattributes: -------------------------------------------------------------------------------- 1 | README.md -diff -merge 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | cache: 5 | - cargo 6 | 7 | matrix: 8 | include: 9 | - name: "test" 10 | rust: stable 11 | before_script: 12 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 13 | - (test -x $HOME/.cargo/bin/cargo-readme || cargo install --vers "^3" cargo-readme) 14 | - cargo install-update -a 15 | script: 16 | - cargo test 17 | - cargo test --features rayon 18 | - name: "check no_std" 19 | rust: nightly 20 | script: 21 | - cargo check --no-default-features 22 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 2.2.1 2 | 3 | Released 2019-02-15. 4 | 5 | * Make sure our rayon parallel iterators are exported. Previously instances of 6 | them were returned by `pub` methods but the types themselves were not 7 | exported. 8 | 9 | # 2.2.0 10 | 11 | Released 2019-01-30. 12 | 13 | * Add the `Arena::alloc_with_id` method. This is better than using 14 | `Arena::next_id` directly most of the time (but is also not *quite* as 15 | flexible). See [#9](https://github.com/fitzgen/id-arena/issues/9) and 16 | [#10](https://github.com/fitzgen/id-arena/pull/10). 17 | 18 | -------------------------------------------------------------------------------- 19 | 20 | # 2.1.0 21 | 22 | Released 2019-01-25. 23 | 24 | * Added optional support for `rayon` parallel iteration. Enable the `rayon` 25 | Cargo feature to get access. 26 | 27 | -------------------------------------------------------------------------------- 28 | 29 | # 2.0.1 30 | 31 | Released 2019-01-09. 32 | 33 | * Implemented `Ord` and `PartialOrd` for `Id`. 34 | * Added an `Arena::with_capacity` constructor. 35 | * Added `Arena::next_id` to get the id that will be used for the next 36 | allocation. 37 | 38 | -------------------------------------------------------------------------------- 39 | 40 | # 2.0.0 41 | 42 | Released 2018-11-28. 43 | 44 | * Introduces the `ArenaBehavior` trait, which allows one to customize identifier 45 | types and do things like implement space optimizations or use identifiers for 46 | many arenas at once. 47 | * Implements `Clone`, `PartialEq` and `Eq` for arenas. 48 | 49 | -------------------------------------------------------------------------------- 50 | 51 | # 1.0.2 52 | 53 | Released 2018-11-25. 54 | 55 | * `Id` now implements `Send` and `Sync` 56 | * The `PartialEq` implementation for `Id` now correctly checks that two ids 57 | are for the same arena when checking equality. 58 | 59 | -------------------------------------------------------------------------------- 60 | 61 | # 1.0.1 62 | 63 | -------------------------------------------------------------------------------- 64 | 65 | # 1.0.0 66 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Nick Fitzgerald ", "Aleksey Kladov "] 3 | categories = ["memory-management", "rust-patterns", "no-std"] 4 | description = "A simple, id-based arena." 5 | documentation = "https://docs.rs/id-arena" 6 | license = "MIT/Apache-2.0" 7 | name = "id-arena" 8 | readme = "README.md" 9 | repository = "https://github.com/fitzgen/id-arena" 10 | edition = "2021" 11 | version = "2.2.1" 12 | 13 | [package.metadata.docs.rs] 14 | features = ['rayon'] 15 | 16 | [dependencies] 17 | rayon = { version = "1.0.3", optional = true } 18 | 19 | [features] 20 | default = ["std"] 21 | std = [] 22 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 (c) 2014 Alex Crichton 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `id-arena` 2 | 3 | [![](https://img.shields.io/crates/v/id-arena.svg)](https://crates.io/crates/id-arena) 4 | [![](https://img.shields.io/crates/d/id-arena.svg)](https://crates.io/crates/id-arena) 5 | [![Travis CI Build Status](https://travis-ci.org/fitzgen/id-arena.svg?branch=master)](https://travis-ci.org/fitzgen/id-arena) 6 | 7 | A simple, id-based arena. 8 | 9 | ### Id-based 10 | 11 | Allocate objects and get an identifier for that object back, *not* a 12 | reference to the allocated object. Given an id, you can get a shared or 13 | exclusive reference to the allocated object from the arena. This id-based 14 | approach is useful for constructing mutable graph data structures. 15 | 16 | If you want allocation to return a reference, consider [the `typed-arena` 17 | crate](https://github.com/SimonSapin/rust-typed-arena/) instead. 18 | 19 | ### No Deletion 20 | 21 | This arena does not support deletion, which makes its implementation simple 22 | and allocation fast. If you want deletion, you need a way to solve the ABA 23 | problem. Consider using [the `generational-arena` 24 | crate](https://github.com/fitzgen/generational-arena) instead. 25 | 26 | ### Homogeneous 27 | 28 | This crate's arenas can only contain objects of a single type `T`. If you 29 | need an arena of objects with heterogeneous types, consider another crate. 30 | 31 | ### `#![no_std]` Support 32 | 33 | Requires the `alloc` nightly feature. Disable the on-by-default `"std"` feature: 34 | 35 | ```toml 36 | [dependencies.id-arena] 37 | version = "2" 38 | default-features = false 39 | ``` 40 | 41 | ### `rayon` Support 42 | 43 | If the `rayon` feature of this crate is activated: 44 | 45 | ```toml 46 | [dependencies] 47 | id-arena = { version = "2", features = ["rayon"] } 48 | ``` 49 | 50 | then you can use [`rayon`](https://crates.io/crates/rayon)'s support for 51 | parallel iteration. The `Arena` type will have a `par_iter` family of 52 | methods where appropriate. 53 | 54 | ### Example 55 | 56 | ```rust 57 | use id_arena::{Arena, Id}; 58 | 59 | type AstNodeId = Id; 60 | 61 | #[derive(Debug, Eq, PartialEq)] 62 | pub enum AstNode { 63 | Const(i64), 64 | Var(String), 65 | Add { 66 | lhs: AstNodeId, 67 | rhs: AstNodeId, 68 | }, 69 | Sub { 70 | lhs: AstNodeId, 71 | rhs: AstNodeId, 72 | }, 73 | Mul { 74 | lhs: AstNodeId, 75 | rhs: AstNodeId, 76 | }, 77 | Div { 78 | lhs: AstNodeId, 79 | rhs: AstNodeId, 80 | }, 81 | } 82 | 83 | let mut ast_nodes = Arena::::new(); 84 | 85 | // Create the AST for `a * (b + 3)`. 86 | let three = ast_nodes.alloc(AstNode::Const(3)); 87 | let b = ast_nodes.alloc(AstNode::Var("b".into())); 88 | let b_plus_three = ast_nodes.alloc(AstNode::Add { 89 | lhs: b, 90 | rhs: three, 91 | }); 92 | let a = ast_nodes.alloc(AstNode::Var("a".into())); 93 | let a_times_b_plus_three = ast_nodes.alloc(AstNode::Mul { 94 | lhs: a, 95 | rhs: b_plus_three, 96 | }); 97 | 98 | // Can use indexing to access allocated nodes. 99 | assert_eq!(ast_nodes[three], AstNode::Const(3)); 100 | ``` 101 | -------------------------------------------------------------------------------- /README.tpl: -------------------------------------------------------------------------------- 1 | # `{{crate}}` 2 | 3 | {{readme}} 4 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [![](https://img.shields.io/crates/v/id-arena.svg)](https://crates.io/crates/id-arena) 2 | //! [![](https://img.shields.io/crates/d/id-arena.svg)](https://crates.io/crates/id-arena) 3 | //! [![Travis CI Build Status](https://travis-ci.org/fitzgen/id-arena.svg?branch=master)](https://travis-ci.org/fitzgen/id-arena) 4 | //! 5 | //! A simple, id-based arena. 6 | //! 7 | //! ## Id-based 8 | //! 9 | //! Allocate objects and get an identifier for that object back, *not* a 10 | //! reference to the allocated object. Given an id, you can get a shared or 11 | //! exclusive reference to the allocated object from the arena. This id-based 12 | //! approach is useful for constructing mutable graph data structures. 13 | //! 14 | //! If you want allocation to return a reference, consider [the `typed-arena` 15 | //! crate](https://github.com/SimonSapin/rust-typed-arena/) instead. 16 | //! 17 | //! ## No Deletion 18 | //! 19 | //! This arena does not support deletion, which makes its implementation simple 20 | //! and allocation fast. If you want deletion, you need a way to solve the ABA 21 | //! problem. Consider using [the `generational-arena` 22 | //! crate](https://github.com/fitzgen/generational-arena) instead. 23 | //! 24 | //! ## Homogeneous 25 | //! 26 | //! This crate's arenas can only contain objects of a single type `T`. If you 27 | //! need an arena of objects with heterogeneous types, consider another crate. 28 | //! 29 | //! ## `#![no_std]` Support 30 | //! 31 | //! Requires the `alloc` nightly feature. Disable the on-by-default `"std"` feature: 32 | //! 33 | //! ```toml 34 | //! [dependencies.id-arena] 35 | //! version = "2" 36 | //! default-features = false 37 | //! ``` 38 | //! 39 | //! ## `rayon` Support 40 | //! 41 | //! If the `rayon` feature of this crate is activated: 42 | //! 43 | //! ```toml 44 | //! [dependencies] 45 | //! id-arena = { version = "2", features = ["rayon"] } 46 | //! ``` 47 | //! 48 | //! then you can use [`rayon`](https://crates.io/crates/rayon)'s support for 49 | //! parallel iteration. The `Arena` type will have a `par_iter` family of 50 | //! methods where appropriate. 51 | //! 52 | //! ## Example 53 | //! 54 | //! ```rust 55 | //! use id_arena::{Arena, Id}; 56 | //! 57 | //! type AstNodeId = Id; 58 | //! 59 | //! #[derive(Debug, Eq, PartialEq)] 60 | //! pub enum AstNode { 61 | //! Const(i64), 62 | //! Var(String), 63 | //! Add { 64 | //! lhs: AstNodeId, 65 | //! rhs: AstNodeId, 66 | //! }, 67 | //! Sub { 68 | //! lhs: AstNodeId, 69 | //! rhs: AstNodeId, 70 | //! }, 71 | //! Mul { 72 | //! lhs: AstNodeId, 73 | //! rhs: AstNodeId, 74 | //! }, 75 | //! Div { 76 | //! lhs: AstNodeId, 77 | //! rhs: AstNodeId, 78 | //! }, 79 | //! } 80 | //! 81 | //! let mut ast_nodes = Arena::::new(); 82 | //! 83 | //! // Create the AST for `a * (b + 3)`. 84 | //! let three = ast_nodes.alloc(AstNode::Const(3)); 85 | //! let b = ast_nodes.alloc(AstNode::Var("b".into())); 86 | //! let b_plus_three = ast_nodes.alloc(AstNode::Add { 87 | //! lhs: b, 88 | //! rhs: three, 89 | //! }); 90 | //! let a = ast_nodes.alloc(AstNode::Var("a".into())); 91 | //! let a_times_b_plus_three = ast_nodes.alloc(AstNode::Mul { 92 | //! lhs: a, 93 | //! rhs: b_plus_three, 94 | //! }); 95 | //! 96 | //! // Can use indexing to access allocated nodes. 97 | //! assert_eq!(ast_nodes[three], AstNode::Const(3)); 98 | //! ``` 99 | 100 | #![forbid(unsafe_code)] 101 | #![deny(missing_debug_implementations)] 102 | #![deny(missing_docs)] 103 | // In no-std mode, use the alloc crate to get `Vec`. 104 | #![no_std] 105 | #![cfg_attr(not(feature = "std"), feature(alloc))] 106 | 107 | use core::cmp::Ordering; 108 | use core::fmt; 109 | use core::hash::{Hash, Hasher}; 110 | use core::iter; 111 | use core::marker::PhantomData; 112 | use core::ops; 113 | use core::slice; 114 | use core::sync::atomic::{self, AtomicUsize}; 115 | 116 | #[cfg(not(feature = "std"))] 117 | extern crate alloc; 118 | #[cfg(not(feature = "std"))] 119 | use alloc::vec::{self, Vec}; 120 | 121 | #[cfg(feature = "std")] 122 | extern crate std; 123 | #[cfg(feature = "std")] 124 | use std::vec::{self, Vec}; 125 | 126 | #[cfg(feature = "rayon")] 127 | mod rayon; 128 | #[cfg(feature = "rayon")] 129 | pub use crate::rayon::*; 130 | 131 | /// A trait representing the implementation behavior of an arena and how 132 | /// identifiers are represented. 133 | /// 134 | /// ## When should I implement `ArenaBehavior` myself? 135 | /// 136 | /// Usually, you should just use `DefaultArenaBehavior`, which is simple and 137 | /// correct. However, there are some scenarios where you might want to implement 138 | /// `ArenaBehavior` yourself: 139 | /// 140 | /// * **Space optimizations:** The default identifier is two words in size, 141 | /// which is larger than is usually necessary. For example, if you know that an 142 | /// arena *cannot* contain more than 256 items, you could make your own 143 | /// identifier type that stores the index as a `u8` and then you can save some 144 | /// space. 145 | /// 146 | /// * **Trait Coherence:** If you need to implement an upstream crate's traits 147 | /// for identifiers, then defining your own identifier type allows you to work 148 | /// with trait coherence rules. 149 | /// 150 | /// * **Share identifiers across arenas:** You can coordinate and share 151 | /// identifiers across different arenas to enable a "struct of arrays" style 152 | /// data representation. 153 | pub trait ArenaBehavior { 154 | /// The identifier type. 155 | type Id: Copy; 156 | 157 | /// Construct a new object identifier from the given index and arena 158 | /// identifier. 159 | /// 160 | /// ## Panics 161 | /// 162 | /// Implementations are allowed to panic if the given index is larger than 163 | /// the underlying storage (e.g. the implementation uses a `u8` for storing 164 | /// indices and the given index value is larger than 255). 165 | fn new_id(arena_id: u32, index: usize) -> Self::Id; 166 | 167 | /// Get the given identifier's index. 168 | fn index(id: Self::Id) -> usize; 169 | 170 | /// Get the given identifier's arena id. 171 | fn arena_id(id: Self::Id) -> u32; 172 | 173 | /// Construct a new arena identifier. 174 | /// 175 | /// This is used to disambiguate `Id`s across different arenas. To make 176 | /// identifiers with the same index from different arenas compare false for 177 | /// equality, return a unique `u32` on every invocation. This is the 178 | /// default, provided implementation's behavior. 179 | /// 180 | /// To make identifiers with the same index from different arenas compare 181 | /// true for equality, return the same `u32` on every invocation. 182 | fn new_arena_id() -> u32 { 183 | static ARENA_COUNTER: AtomicUsize = AtomicUsize::new(0); 184 | ARENA_COUNTER.fetch_add(1, atomic::Ordering::SeqCst) as u32 185 | } 186 | } 187 | 188 | /// An identifier for an object allocated within an arena. 189 | pub struct Id { 190 | idx: usize, 191 | arena_id: u32, 192 | _ty: PhantomData T>, 193 | } 194 | 195 | impl fmt::Debug for Id { 196 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 197 | f.debug_struct("Id").field("idx", &self.idx).finish() 198 | } 199 | } 200 | 201 | impl Copy for Id {} 202 | 203 | impl Clone for Id { 204 | #[inline] 205 | fn clone(&self) -> Id { 206 | *self 207 | } 208 | } 209 | 210 | impl PartialEq for Id { 211 | #[inline] 212 | fn eq(&self, rhs: &Self) -> bool { 213 | self.arena_id == rhs.arena_id && self.idx == rhs.idx 214 | } 215 | } 216 | 217 | impl Eq for Id {} 218 | 219 | impl Hash for Id { 220 | #[inline] 221 | fn hash(&self, h: &mut H) { 222 | self.arena_id.hash(h); 223 | self.idx.hash(h); 224 | } 225 | } 226 | 227 | impl PartialOrd for Id { 228 | fn partial_cmp(&self, rhs: &Self) -> Option { 229 | Some(self.cmp(rhs)) 230 | } 231 | } 232 | 233 | impl Ord for Id { 234 | fn cmp(&self, rhs: &Self) -> Ordering { 235 | self.arena_id 236 | .cmp(&rhs.arena_id) 237 | .then(self.idx.cmp(&rhs.idx)) 238 | } 239 | } 240 | 241 | impl Id { 242 | /// Get the index within the arena that this id refers to. 243 | #[inline] 244 | pub fn index(&self) -> usize { 245 | self.idx 246 | } 247 | } 248 | 249 | /// The default `ArenaBehavior` implementation. 250 | #[derive(Clone, Debug, PartialEq, Eq)] 251 | pub struct DefaultArenaBehavior { 252 | _phantom: PhantomData T>, 253 | } 254 | 255 | impl ArenaBehavior for DefaultArenaBehavior { 256 | type Id = Id; 257 | 258 | #[inline] 259 | fn new_id(arena_id: u32, idx: usize) -> Self::Id { 260 | Id { 261 | idx, 262 | arena_id, 263 | _ty: PhantomData, 264 | } 265 | } 266 | 267 | #[inline] 268 | fn index(id: Self::Id) -> usize { 269 | id.idx 270 | } 271 | 272 | #[inline] 273 | fn arena_id(id: Self::Id) -> u32 { 274 | id.arena_id 275 | } 276 | } 277 | 278 | /// An arena of objects of type `T`. 279 | /// 280 | /// ``` 281 | /// use id_arena::Arena; 282 | /// 283 | /// let mut arena = Arena::<&str>::new(); 284 | /// 285 | /// let a = arena.alloc("Albert"); 286 | /// assert_eq!(arena[a], "Albert"); 287 | /// 288 | /// arena[a] = "Alice"; 289 | /// assert_eq!(arena[a], "Alice"); 290 | /// ``` 291 | #[derive(Clone, Debug, PartialEq, Eq)] 292 | pub struct Arena> { 293 | arena_id: u32, 294 | items: Vec, 295 | _phantom: PhantomData A>, 296 | } 297 | 298 | impl Default for Arena 299 | where 300 | A: ArenaBehavior, 301 | { 302 | #[inline] 303 | fn default() -> Arena { 304 | Arena { 305 | arena_id: A::new_arena_id(), 306 | items: Vec::new(), 307 | _phantom: PhantomData, 308 | } 309 | } 310 | } 311 | 312 | impl Arena 313 | where 314 | A: ArenaBehavior, 315 | { 316 | /// Construct a new, empty `Arena`. 317 | /// 318 | /// ``` 319 | /// use id_arena::Arena; 320 | /// 321 | /// let mut arena = Arena::::new(); 322 | /// arena.alloc(42); 323 | /// ``` 324 | #[inline] 325 | pub fn new() -> Arena { 326 | Default::default() 327 | } 328 | 329 | /// Construct a new, empty `Arena` with capacity for the given number of 330 | /// elements. 331 | /// 332 | /// ``` 333 | /// use id_arena::Arena; 334 | /// 335 | /// let mut arena = Arena::::with_capacity(100); 336 | /// for x in 0..100 { 337 | /// arena.alloc(x * x); 338 | /// } 339 | /// ``` 340 | #[inline] 341 | pub fn with_capacity(capacity: usize) -> Arena { 342 | Arena { 343 | arena_id: A::new_arena_id(), 344 | items: Vec::with_capacity(capacity), 345 | _phantom: PhantomData, 346 | } 347 | } 348 | 349 | /// Allocate `item` within this arena and return its id. 350 | /// 351 | /// ``` 352 | /// use id_arena::Arena; 353 | /// 354 | /// let mut arena = Arena::::new(); 355 | /// let _id = arena.alloc(42); 356 | /// ``` 357 | /// 358 | /// ## Panics 359 | /// 360 | /// Panics if the number of elements in the arena overflows a `usize` or 361 | /// `Id`'s index storage representation. 362 | #[inline] 363 | pub fn alloc(&mut self, item: T) -> A::Id { 364 | let id = self.next_id(); 365 | self.items.push(item); 366 | id 367 | } 368 | 369 | /// Allocate an item with the id that it will be assigned. 370 | /// 371 | /// This is useful for structures that want to store their id as their own 372 | /// member. 373 | /// 374 | /// ``` 375 | /// use id_arena::{Arena, Id}; 376 | /// 377 | /// struct Cat { 378 | /// id: Id, 379 | /// } 380 | /// 381 | /// let mut arena = Arena::::new(); 382 | /// 383 | /// let kitty = arena.alloc_with_id(|id| Cat { id }); 384 | /// assert_eq!(arena[kitty].id, kitty); 385 | /// ``` 386 | #[inline] 387 | pub fn alloc_with_id(&mut self, f: impl FnOnce(A::Id) -> T) -> A::Id { 388 | let id = self.next_id(); 389 | let val = f(id); 390 | self.alloc(val) 391 | } 392 | 393 | /// Get the id that will be used for the next item allocated into this 394 | /// arena. 395 | /// 396 | /// If you are allocating a `struct` that wants to have its id as a member 397 | /// of itself, prefer the less error-prone `Arena::alloc_with_id` method. 398 | #[inline] 399 | pub fn next_id(&self) -> A::Id { 400 | let arena_id = self.arena_id; 401 | let idx = self.items.len(); 402 | A::new_id(arena_id, idx) 403 | } 404 | 405 | /// Get a shared reference to the object associated with the given `id` if 406 | /// it exists. 407 | /// 408 | /// If there is no object associated with `id` (for example, it might 409 | /// reference an object allocated within a different arena) then return 410 | /// `None`. 411 | /// 412 | /// ``` 413 | /// use id_arena::Arena; 414 | /// 415 | /// let mut arena = Arena::::new(); 416 | /// let id = arena.alloc(42); 417 | /// assert!(arena.get(id).is_some()); 418 | /// 419 | /// let other_arena = Arena::::new(); 420 | /// assert!(other_arena.get(id).is_none()); 421 | /// ``` 422 | #[inline] 423 | pub fn get(&self, id: A::Id) -> Option<&T> { 424 | if A::arena_id(id) != self.arena_id { 425 | None 426 | } else { 427 | self.items.get(A::index(id)) 428 | } 429 | } 430 | 431 | /// Get an exclusive reference to the object associated with the given `id` 432 | /// if it exists. 433 | /// 434 | /// If there is no object associated with `id` (for example, it might 435 | /// reference an object allocated within a different arena) then return 436 | /// `None`. 437 | /// 438 | /// ``` 439 | /// use id_arena::Arena; 440 | /// 441 | /// let mut arena = Arena::::new(); 442 | /// let id = arena.alloc(42); 443 | /// assert!(arena.get_mut(id).is_some()); 444 | /// 445 | /// let mut other_arena = Arena::::new(); 446 | /// assert!(other_arena.get_mut(id).is_none()); 447 | /// ``` 448 | #[inline] 449 | pub fn get_mut(&mut self, id: A::Id) -> Option<&mut T> { 450 | if A::arena_id(id) != self.arena_id { 451 | None 452 | } else { 453 | self.items.get_mut(A::index(id)) 454 | } 455 | } 456 | 457 | /// Iterate over this arena's items and their ids. 458 | /// 459 | /// ``` 460 | /// use id_arena::Arena; 461 | /// 462 | /// let mut arena = Arena::<&str>::new(); 463 | /// 464 | /// arena.alloc("hello"); 465 | /// arena.alloc("hi"); 466 | /// arena.alloc("yo"); 467 | /// 468 | /// for (id, s) in arena.iter() { 469 | /// assert_eq!(arena.get(id).unwrap(), s); 470 | /// println!("{:?} -> {}", id, s); 471 | /// } 472 | /// ``` 473 | #[inline] 474 | pub fn iter(&self) -> Iter { 475 | IntoIterator::into_iter(self) 476 | } 477 | 478 | /// Iterate over this arena's items and their ids, allowing mutation of each 479 | /// item. 480 | #[inline] 481 | pub fn iter_mut(&mut self) -> IterMut { 482 | IntoIterator::into_iter(self) 483 | } 484 | 485 | /// Get the number of objects allocated in this arena. 486 | /// 487 | /// ``` 488 | /// use id_arena::Arena; 489 | /// 490 | /// let mut arena = Arena::<&str>::new(); 491 | /// 492 | /// arena.alloc("hello"); 493 | /// arena.alloc("hi"); 494 | /// 495 | /// assert_eq!(arena.len(), 2); 496 | /// ``` 497 | #[inline] 498 | pub fn len(&self) -> usize { 499 | self.items.len() 500 | } 501 | } 502 | 503 | impl ops::Index for Arena 504 | where 505 | A: ArenaBehavior, 506 | { 507 | type Output = T; 508 | 509 | #[inline] 510 | fn index(&self, id: A::Id) -> &T { 511 | assert_eq!(self.arena_id, A::arena_id(id)); 512 | &self.items[A::index(id)] 513 | } 514 | } 515 | 516 | impl ops::IndexMut for Arena 517 | where 518 | A: ArenaBehavior, 519 | { 520 | #[inline] 521 | fn index_mut(&mut self, id: A::Id) -> &mut T { 522 | assert_eq!(self.arena_id, A::arena_id(id)); 523 | &mut self.items[A::index(id)] 524 | } 525 | } 526 | 527 | fn add_id(item: Option<(usize, T)>, arena_id: u32) -> Option<(A::Id, T)> 528 | where 529 | A: ArenaBehavior, 530 | { 531 | item.map(|(idx, item)| (A::new_id(arena_id, idx), item)) 532 | } 533 | 534 | /// An iterator over `(Id, &T)` pairs in an arena. 535 | /// 536 | /// See [the `Arena::iter()` method](./struct.Arena.html#method.iter) for details. 537 | #[derive(Debug)] 538 | pub struct Iter<'a, T: 'a, A: 'a> { 539 | arena_id: u32, 540 | iter: iter::Enumerate>, 541 | _phantom: PhantomData A>, 542 | } 543 | 544 | impl<'a, T: 'a, A: 'a> Iterator for Iter<'a, T, A> 545 | where 546 | A: ArenaBehavior, 547 | { 548 | type Item = (A::Id, &'a T); 549 | 550 | #[inline] 551 | fn next(&mut self) -> Option { 552 | add_id::(self.iter.next(), self.arena_id) 553 | } 554 | 555 | fn size_hint(&self) -> (usize, Option) { 556 | self.iter.size_hint() 557 | } 558 | } 559 | 560 | impl<'a, T: 'a, A: 'a> DoubleEndedIterator for Iter<'a, T, A> 561 | where 562 | A: ArenaBehavior, 563 | { 564 | fn next_back(&mut self) -> Option { 565 | add_id::(self.iter.next_back(), self.arena_id) 566 | } 567 | } 568 | 569 | impl<'a, T: 'a, A: 'a> ExactSizeIterator for Iter<'a, T, A> 570 | where 571 | A: ArenaBehavior, 572 | { 573 | fn len(&self) -> usize { 574 | self.iter.len() 575 | } 576 | } 577 | 578 | impl<'a, T, A> IntoIterator for &'a Arena 579 | where 580 | A: ArenaBehavior, 581 | { 582 | type Item = (A::Id, &'a T); 583 | type IntoIter = Iter<'a, T, A>; 584 | 585 | #[inline] 586 | fn into_iter(self) -> Iter<'a, T, A> { 587 | Iter { 588 | arena_id: self.arena_id, 589 | iter: self.items.iter().enumerate(), 590 | _phantom: PhantomData, 591 | } 592 | } 593 | } 594 | 595 | /// An iterator over `(Id, &mut T)` pairs in an arena. 596 | /// 597 | /// See [the `Arena::iter_mut()` method](./struct.Arena.html#method.iter_mut) 598 | /// for details. 599 | #[derive(Debug)] 600 | pub struct IterMut<'a, T: 'a, A: 'a> { 601 | arena_id: u32, 602 | iter: iter::Enumerate>, 603 | _phantom: PhantomData A>, 604 | } 605 | 606 | impl<'a, T: 'a, A: 'a> Iterator for IterMut<'a, T, A> 607 | where 608 | A: ArenaBehavior, 609 | { 610 | type Item = (A::Id, &'a mut T); 611 | 612 | #[inline] 613 | fn next(&mut self) -> Option { 614 | add_id::(self.iter.next(), self.arena_id) 615 | } 616 | 617 | fn size_hint(&self) -> (usize, Option) { 618 | self.iter.size_hint() 619 | } 620 | } 621 | 622 | impl<'a, T: 'a, A: 'a> DoubleEndedIterator for IterMut<'a, T, A> 623 | where 624 | A: ArenaBehavior, 625 | { 626 | fn next_back(&mut self) -> Option { 627 | add_id::(self.iter.next_back(), self.arena_id) 628 | } 629 | } 630 | 631 | impl<'a, T: 'a, A: 'a> ExactSizeIterator for IterMut<'a, T, A> 632 | where 633 | A: ArenaBehavior, 634 | { 635 | fn len(&self) -> usize { 636 | self.iter.len() 637 | } 638 | } 639 | 640 | impl<'a, T, A> IntoIterator for &'a mut Arena 641 | where 642 | A: ArenaBehavior, 643 | { 644 | type Item = (A::Id, &'a mut T); 645 | type IntoIter = IterMut<'a, T, A>; 646 | 647 | #[inline] 648 | fn into_iter(self) -> IterMut<'a, T, A> { 649 | IterMut { 650 | arena_id: self.arena_id, 651 | iter: self.items.iter_mut().enumerate(), 652 | _phantom: PhantomData, 653 | } 654 | } 655 | } 656 | 657 | /// An iterator over `(Id, T)` pairs in an arena. 658 | #[derive(Debug)] 659 | pub struct IntoIter { 660 | arena_id: u32, 661 | iter: iter::Enumerate>, 662 | _phantom: PhantomData A>, 663 | } 664 | 665 | impl Iterator for IntoIter 666 | where 667 | A: ArenaBehavior, 668 | { 669 | type Item = (A::Id, T); 670 | 671 | #[inline] 672 | fn next(&mut self) -> Option { 673 | add_id::(self.iter.next(), self.arena_id) 674 | } 675 | 676 | fn size_hint(&self) -> (usize, Option) { 677 | self.iter.size_hint() 678 | } 679 | } 680 | 681 | impl DoubleEndedIterator for IntoIter 682 | where 683 | A: ArenaBehavior, 684 | { 685 | fn next_back(&mut self) -> Option { 686 | add_id::(self.iter.next_back(), self.arena_id) 687 | } 688 | } 689 | 690 | impl ExactSizeIterator for IntoIter 691 | where 692 | A: ArenaBehavior, 693 | { 694 | fn len(&self) -> usize { 695 | self.iter.len() 696 | } 697 | } 698 | 699 | impl IntoIterator for Arena 700 | where 701 | A: ArenaBehavior, 702 | { 703 | type Item = (A::Id, T); 704 | type IntoIter = IntoIter; 705 | 706 | #[inline] 707 | fn into_iter(self) -> IntoIter { 708 | IntoIter { 709 | arena_id: self.arena_id, 710 | iter: self.items.into_iter().enumerate(), 711 | _phantom: PhantomData, 712 | } 713 | } 714 | } 715 | 716 | #[cfg(test)] 717 | mod tests { 718 | use super::*; 719 | 720 | #[test] 721 | fn ids_are_send_sync() { 722 | fn assert_send_sync() {} 723 | struct Foo; 724 | assert_send_sync::>(); 725 | } 726 | } 727 | -------------------------------------------------------------------------------- /src/rayon.rs: -------------------------------------------------------------------------------- 1 | extern crate rayon; 2 | 3 | use self::rayon::iter::plumbing::{Consumer, UnindexedConsumer}; 4 | use self::rayon::iter::plumbing::ProducerCallback; 5 | use self::rayon::prelude::*; 6 | use super::*; 7 | 8 | impl Arena 9 | where 10 | A: ArenaBehavior, 11 | { 12 | /// Returns an iterator of shared references which can be used to iterate 13 | /// over this arena in parallel with the `rayon` crate. 14 | /// 15 | /// # Features 16 | /// 17 | /// This API requires the `rayon` feature of this crate to be enabled. 18 | pub fn par_iter(&self) -> ParIter 19 | where 20 | T: Sync, 21 | A::Id: Send, 22 | { 23 | ParIter { 24 | arena_id: self.arena_id, 25 | iter: self.items.par_iter().enumerate(), 26 | _phantom: PhantomData, 27 | } 28 | } 29 | 30 | /// Returns an iterator of mutable references which can be used to iterate 31 | /// over this arena in parallel with the `rayon` crate. 32 | /// 33 | /// # Features 34 | /// 35 | /// This API requires the `rayon` feature of this crate to be enabled. 36 | pub fn par_iter_mut(&mut self) -> ParIterMut 37 | where 38 | T: Send + Sync, 39 | A::Id: Send, 40 | { 41 | ParIterMut { 42 | arena_id: self.arena_id, 43 | iter: self.items.par_iter_mut().enumerate(), 44 | _phantom: PhantomData, 45 | } 46 | } 47 | } 48 | 49 | /// A parallel iterator over shared references in an arena. 50 | /// 51 | /// See `Arena::par_iter` for more information. 52 | #[derive(Debug)] 53 | pub struct ParIter<'a, T, A> 54 | where 55 | T: Sync, 56 | { 57 | arena_id: u32, 58 | iter: rayon::iter::Enumerate>, 59 | _phantom: PhantomData A>, 60 | } 61 | 62 | impl<'a, T, A> ParallelIterator for ParIter<'a, T, A> 63 | where 64 | T: Sync, 65 | A: ArenaBehavior, 66 | A::Id: Send, 67 | { 68 | type Item = (A::Id, &'a T); 69 | 70 | fn drive_unindexed(self, consumer: C) -> C::Result 71 | where 72 | C: UnindexedConsumer, 73 | { 74 | let arena_id = self.arena_id; 75 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 76 | .drive_unindexed(consumer) 77 | } 78 | 79 | fn opt_len(&self) -> Option { 80 | self.iter.opt_len() 81 | } 82 | } 83 | 84 | impl<'a, T, A> IndexedParallelIterator for ParIter<'a, T, A> 85 | where 86 | T: Sync, 87 | A: ArenaBehavior, 88 | A::Id: Send, 89 | { 90 | fn drive(self, consumer: C) -> C::Result 91 | where 92 | C: Consumer, 93 | { 94 | let arena_id = self.arena_id; 95 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 96 | .drive(consumer) 97 | } 98 | 99 | fn len(&self) -> usize { 100 | self.iter.len() 101 | } 102 | 103 | fn with_producer(self, callback: CB) -> CB::Output 104 | where 105 | CB: ProducerCallback, 106 | { 107 | let arena_id = self.arena_id; 108 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 109 | .with_producer(callback) 110 | } 111 | } 112 | 113 | impl<'data, T, A> IntoParallelIterator for &'data Arena 114 | where A: ArenaBehavior, 115 | A::Id: Send, 116 | T: Sync, 117 | { 118 | type Item = (A::Id, &'data T); 119 | type Iter = ParIter<'data, T, A>; 120 | 121 | fn into_par_iter(self) -> Self::Iter { 122 | self.par_iter() 123 | } 124 | } 125 | 126 | /// A parallel iterator over mutable references in an arena. 127 | /// 128 | /// See `Arena::par_iter_mut` for more information. 129 | #[derive(Debug)] 130 | pub struct ParIterMut<'a, T, A> 131 | where 132 | T: Send + Sync, 133 | { 134 | arena_id: u32, 135 | iter: rayon::iter::Enumerate>, 136 | _phantom: PhantomData A>, 137 | } 138 | 139 | impl<'a, T, A> ParallelIterator for ParIterMut<'a, T, A> 140 | where 141 | T: Send + Sync, 142 | A: ArenaBehavior, 143 | A::Id: Send, 144 | { 145 | type Item = (A::Id, &'a mut T); 146 | 147 | fn drive_unindexed(self, consumer: C) -> C::Result 148 | where 149 | C: UnindexedConsumer, 150 | { 151 | let arena_id = self.arena_id; 152 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 153 | .drive_unindexed(consumer) 154 | } 155 | 156 | fn opt_len(&self) -> Option { 157 | self.iter.opt_len() 158 | } 159 | } 160 | 161 | impl<'a, T, A> IndexedParallelIterator for ParIterMut<'a, T, A> 162 | where 163 | T: Send + Sync, 164 | A: ArenaBehavior, 165 | A::Id: Send, 166 | { 167 | fn drive(self, consumer: C) -> C::Result 168 | where 169 | C: Consumer, 170 | { 171 | let arena_id = self.arena_id; 172 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 173 | .drive(consumer) 174 | } 175 | 176 | fn len(&self) -> usize { 177 | self.iter.len() 178 | } 179 | 180 | fn with_producer(self, callback: CB) -> CB::Output 181 | where 182 | CB: ProducerCallback, 183 | { 184 | let arena_id = self.arena_id; 185 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 186 | .with_producer(callback) 187 | } 188 | } 189 | 190 | impl<'data, T, A> IntoParallelIterator for &'data mut Arena 191 | where A: ArenaBehavior, 192 | A::Id: Send, 193 | T: Send + Sync, 194 | { 195 | type Item = (A::Id, &'data mut T); 196 | type Iter = ParIterMut<'data, T, A>; 197 | 198 | fn into_par_iter(self) -> Self::Iter { 199 | self.par_iter_mut() 200 | } 201 | } 202 | 203 | /// A parallel iterator over items in an arena. 204 | /// 205 | /// See `Arena::into_par_iter` for more information. 206 | #[derive(Debug)] 207 | pub struct IntoParIter 208 | where 209 | T: Send, 210 | { 211 | arena_id: u32, 212 | iter: rayon::iter::Enumerate>, 213 | _phantom: PhantomData A>, 214 | } 215 | 216 | impl ParallelIterator for IntoParIter 217 | where 218 | T: Send, 219 | A: ArenaBehavior, 220 | A::Id: Send, 221 | { 222 | type Item = (A::Id, T); 223 | 224 | fn drive_unindexed(self, consumer: C) -> C::Result 225 | where 226 | C: UnindexedConsumer, 227 | { 228 | let arena_id = self.arena_id; 229 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 230 | .drive_unindexed(consumer) 231 | } 232 | 233 | fn opt_len(&self) -> Option { 234 | self.iter.opt_len() 235 | } 236 | } 237 | 238 | impl IndexedParallelIterator for IntoParIter 239 | where 240 | T: Send, 241 | A: ArenaBehavior, 242 | A::Id: Send, 243 | { 244 | fn drive(self, consumer: C) -> C::Result 245 | where 246 | C: Consumer, 247 | { 248 | let arena_id = self.arena_id; 249 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 250 | .drive(consumer) 251 | } 252 | 253 | fn len(&self) -> usize { 254 | self.iter.len() 255 | } 256 | 257 | fn with_producer(self, callback: CB) -> CB::Output 258 | where 259 | CB: ProducerCallback, 260 | { 261 | let arena_id = self.arena_id; 262 | self.iter.map(|(i, item)| (A::new_id(arena_id, i), item)) 263 | .with_producer(callback) 264 | } 265 | } 266 | 267 | impl IntoParallelIterator for Arena 268 | where A: ArenaBehavior, 269 | A::Id: Send, 270 | T: Send, 271 | { 272 | type Item = (A::Id, T); 273 | type Iter = IntoParIter; 274 | 275 | fn into_par_iter(self) -> Self::Iter { 276 | IntoParIter { 277 | arena_id: self.arena_id, 278 | iter: self.items.into_par_iter().enumerate(), 279 | _phantom: PhantomData, 280 | } 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /tests/readme_up_to_date.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::process::Command; 3 | 4 | #[test] 5 | fn cargo_readme_up_to_date() { 6 | println!("Checking that `cargo readme > README.md` is up to date..."); 7 | 8 | let expected = Command::new("cargo") 9 | .arg("readme") 10 | .current_dir(env!("CARGO_MANIFEST_DIR")) 11 | .output() 12 | .expect("should run `cargo readme` OK") 13 | .stdout; 14 | let expected = String::from_utf8_lossy(&expected); 15 | 16 | let actual = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md")) 17 | .expect("should read README.md OK"); 18 | 19 | if actual != expected { 20 | panic!("Run `cargo readme > README.md` to update README.md"); 21 | } 22 | } 23 | --------------------------------------------------------------------------------