├── .github ├── FUNDING.yml └── workflows │ ├── ci.yml │ └── coverage.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benches ├── get.rs └── iter.rs └── src ├── iter.rs ├── lib.rs ├── param.rs ├── serde.rs ├── slice.rs └── vec.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: james7132 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | env: 6 | CARGO_TERM_COLOR: always 7 | 8 | jobs: 9 | build: 10 | strategy: 11 | matrix: 12 | os: [windows-latest, ubuntu-latest, macos-latest] 13 | std: ["std", "no-std"] 14 | toolchain: [nightly] 15 | runs-on: ${{ matrix.os }} 16 | steps: 17 | - uses: actions/checkout@v2 18 | 19 | - uses: actions-rs/toolchain@v1 20 | id: toolchain 21 | with: 22 | toolchain: ${{ matrix.toolchain }} 23 | profile: minimal 24 | components: rustfmt, clippy, miri 25 | override: true 26 | 27 | - name: Setup cache 28 | uses: actions/cache@v2 29 | with: 30 | path: | 31 | ~/.cargo/registry 32 | ~/.cargo/git 33 | target 34 | key: ${{ runner.os }}-test-rustc-${{ steps.toolchain.outputs.rustc_hash }}-${{ hashFiles('**/Cargo.lock') }} 35 | 36 | - uses: actions-rs/cargo@v1 37 | if: runner.os == 'linux' 38 | with: 39 | command: fmt 40 | args: --all -- --check 41 | 42 | - uses: actions-rs/clippy-check@v1 43 | if: runner.os == 'linux' 44 | with: 45 | token: ${{ secrets.GITHUB_TOKEN }} 46 | args: --all-features -- -D warnings 47 | 48 | - uses: actions-rs/cargo@v1 49 | if: matrix.std == 'no-std' 50 | with: 51 | command: build 52 | args: --no-default-features --features "serde" 53 | env: 54 | CARGO_INCREMENTAL: 0 55 | RUSTFLAGS: "-C debuginfo=0" 56 | 57 | - uses: actions-rs/cargo@v1 58 | if: matrix.std == 'std' 59 | with: 60 | command: miri 61 | args: test --all-features 62 | env: 63 | CARGO_INCREMENTAL: 0 64 | RUSTFLAGS: "-C debuginfo=0" -------------------------------------------------------------------------------- /.github/workflows/coverage.yml: -------------------------------------------------------------------------------- 1 | name: coverage 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | test: 6 | name: coverage 7 | runs-on: ubuntu-latest 8 | container: 9 | image: xd009642/tarpaulin:develop-nightly 10 | options: --security-opt seccomp=unconfined 11 | steps: 12 | - name: Checkout repository 13 | uses: actions/checkout@v2 14 | 15 | - name: Generate code coverage 16 | run: | 17 | cargo +nightly tarpaulin --verbose --all-features --workspace --timeout 120 --out Xml 18 | 19 | - name: Upload to codecov.io 20 | uses: codecov/codecov-action@v2 21 | with: 22 | fail_ci_if_error: true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "parallel_vec" 3 | version = "0.2.4" 4 | edition = "2021" 5 | authors = ["Hourai Teahouse Developers "] 6 | description = "A generic contiguous collection of heterogenous values." 7 | homepage = "https://github.com/HouraiTeahouse/parallel_vec" 8 | repository = "https://github.com/HouraiTeahouse/parallel_vec" 9 | readme = "README.md" 10 | keywords = ["ecs", "columnar", "struct-of-arrays", "vec"] 11 | categories = ["data-structures", "no-std"] 12 | license = "MIT OR Apache-2.0" 13 | 14 | [features] 15 | default = ["std"] 16 | std = [] 17 | 18 | [package.metadata.docs.rs] 19 | all-features = true 20 | rustdoc-args = ["--cfg", "docsrs"] 21 | 22 | [dependencies] 23 | serde = { version = "1.0", optional = true, default-features = false, features = ["alloc"]} 24 | 25 | [dev-dependencies] 26 | serde_test = "1.0" 27 | criterion = "0.3" 28 | rand = "0.8" 29 | 30 | [[bench]] 31 | name = "iter" 32 | harness = false 33 | 34 | [[bench]] 35 | name = "get" 36 | harness = false -------------------------------------------------------------------------------- /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 2022 James Liu 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ParallelVec 2 | 3 | [![crates.io](https://img.shields.io/crates/v/parallel-vec.svg)](https://crates.io/crates/parallel-vec) 4 | [![Documentation](https://docs.rs/parallel_vec/badge.svg)](https://docs.rs/parallel-vec) 5 | ![License](https://img.shields.io/crates/l/parallel-vec.svg) 6 | [![codecov](https://codecov.io/gh/HouraiTeahouse/parallel_vec/branch/main/graph/badge.svg?token=BEKDFDO5HW)](https://codecov.io/gh/HouraiTeahouse/parallel_vec) 7 | 8 | `ParallelVec` is a generic collection of contiguously stored heterogenous values with 9 | an API similar to that of a `Vec<(T1, T2, ...)>` but stores the data laid out as a 10 | separate slice per field, using a [structures of arrays](https://en.wikipedia.org/wiki/AoS_and_SoA#Structure_of_arrays) 11 | layout. The advantage of this layout is that cache utilization may be signifgantly improved 12 | when iterating over the data. 13 | 14 | This approach is common to game engines, and Entity-Component-Systems in particular but is 15 | applicable anywhere that cache coherency and memory bandwidth are important for performance. 16 | 17 | Unlike a struct of `Vec`s, only one length and capacity field is stored, and only one contiguous 18 | allocation is made for the entire data structs. Upon reallocation, a struct of `Vec` may apply 19 | additional allocation pressure. `ParallelVec` only allocates once per resize. 20 | 21 | ## Example 22 | ```rust 23 | use parallel_vec::ParallelVec; 24 | 25 | // #Some 'entity' data. 26 | struct Position { x: f64, y: f64 } 27 | struct Velocity { dx: f64, dy: f64 } 28 | struct ColdData { /* Potentially many fields omitted here */ } 29 | 30 | // Create a vec of entities 31 | let mut entities: ParallelVec<(Position, Velocity, ColdData)> = ParallelVec::new(); 32 | entities.push((Position {x: 1.0, y: 2.0}, Velocity { dx: 0.0, dy: 0.5 }, ColdData {})); 33 | entities.push((Position {x: 0.0, y: 2.0}, Velocity { dx: 0.5, dy: 0.5 }, ColdData {})); 34 | 35 | // Update entities. This loop only loads position and velocity data, while skipping over 36 | // the ColdData which is not necessary for the physics simulation. 37 | for (position, velocity, _) in entities.iter_mut() { 38 | *position = *position + *velocity; 39 | } 40 | 41 | // Remove an entity 42 | entities.swap_remove(0); 43 | ``` 44 | 45 | ## `no_std` Support 46 | By default, this crate requires the standard library. Disabling the default features 47 | enables this crate to compile in `#![no_std]` environments. There must be a set global 48 | allocator and heap support for this crate to work. 49 | 50 | ## `serde` Support 51 | `ParallelVec` can be serialized if it's parameters can be serialized. This is disabled by 52 | default. Use the `serde` feature to enable support for serialization and deserialization. 53 | 54 | ## Benchmarks 55 | To run benchmarks, use `cargo bench`. The benchmarks for this crate directly compares the 56 | iteration and `get` performance of `ParallelVec` and it's `Vec` equivalent on small structs, 57 | big structs, and a mix of both. 58 | 59 | Generally, `ParallelVec` achieves similar performance to `Vec` when the entire buffer can 60 | fit into cache. Once the backing store grows larger than cache, or if there are other 61 | operations competing for cache space, `ParallelVec` achieves higher iteration speeds than 62 | its `Vec` equivalent, particularly as the size of the elements increases. Conversely, 63 | `ParallelVec` performance falls off relative to it's `Vec` equivalent as the size of the 64 | overall buffer increases. 65 | -------------------------------------------------------------------------------- /benches/get.rs: -------------------------------------------------------------------------------- 1 | use criterion::{black_box, criterion_group, criterion_main, Criterion}; 2 | 3 | use parallel_vec::ParallelVec; 4 | use rand::*; 5 | 6 | #[derive(Clone, Copy, Default)] 7 | struct Small(u32); 8 | #[derive(Clone, Copy, Default)] 9 | struct Big([u64; 32]); 10 | 11 | trait Inc { 12 | fn inc(&mut self); 13 | } 14 | 15 | impl Inc for Small { 16 | fn inc(&mut self) { 17 | self.0 += 1; 18 | } 19 | } 20 | 21 | impl Inc for Big { 22 | fn inc(&mut self) { 23 | for i in 0..32 { 24 | self.0[i] += 1; 25 | } 26 | } 27 | } 28 | 29 | fn bench_get_2(c: &mut Criterion, size: usize) { 30 | let small = (Small(0), Small(1)); 31 | let mut rng = rand::thread_rng(); 32 | let mut vec = Vec::from(vec![small]).repeat(size); 33 | c.bench_function(&format!("get_vec_small_2x_{}", size), |b| { 34 | b.iter(|| { 35 | if let Some((a, b)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 36 | black_box(a).inc(); 37 | black_box(b).inc(); 38 | } 39 | }) 40 | }); 41 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 42 | c.bench_function(&format!("get_parallelvec_small_2x_{}", size), |b| { 43 | b.iter(|| { 44 | if let Some((a, b)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 45 | black_box(a).inc(); 46 | black_box(b).inc(); 47 | } 48 | }) 49 | }); 50 | let mixed = (Big::default(), Small(1)); 51 | let mut vec = Vec::from(vec![mixed]).repeat(size); 52 | c.bench_function(&format!("get_vec_mixed_2x_{}", size), |b| { 53 | b.iter(|| { 54 | if let Some((a, b)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 55 | black_box(a).inc(); 56 | black_box(b).inc(); 57 | } 58 | }) 59 | }); 60 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 61 | c.bench_function(&format!("get_parallelvec_mixed_2x_{}", size), |b| { 62 | b.iter(|| { 63 | if let Some((a, b)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 64 | black_box(a).inc(); 65 | black_box(b).inc(); 66 | } 67 | }) 68 | }); 69 | let big = (Big::default(), Big::default()); 70 | let mut vec = Vec::from(vec![big]).repeat(size); 71 | c.bench_function(&format!("get_vec_big_2x_{}", size), |b| { 72 | b.iter(|| { 73 | if let Some((a, b)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 74 | black_box(a).inc(); 75 | black_box(b).inc(); 76 | } 77 | }) 78 | }); 79 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 80 | c.bench_function(&format!("get_parallelvec_big_2x_{}", size), |b| { 81 | b.iter(|| { 82 | if let Some((a, b)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 83 | black_box(a).inc(); 84 | black_box(b).inc(); 85 | } 86 | }) 87 | }); 88 | } 89 | 90 | fn bench_get_3(c: &mut Criterion, size: usize) { 91 | let small = (Small(0), Small(1), Small(2)); 92 | let mut rng = rand::thread_rng(); 93 | let mut vec = Vec::from(vec![small]).repeat(size); 94 | c.bench_function(&format!("get_vec_small_3x_{}", size), |b| { 95 | b.iter(|| { 96 | if let Some((a, b, c)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 97 | black_box(a).inc(); 98 | black_box(b).inc(); 99 | black_box(c).inc(); 100 | } 101 | }) 102 | }); 103 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 104 | c.bench_function(&format!("get_parallelvec_small_3x_{}", size), |b| { 105 | b.iter(|| { 106 | if let Some((a, b, c)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 107 | black_box(a).inc(); 108 | black_box(b).inc(); 109 | black_box(c).inc(); 110 | } 111 | }) 112 | }); 113 | let mixed = (Big::default(), Small(1), Big::default()); 114 | let mut vec = Vec::from(vec![mixed]).repeat(size); 115 | c.bench_function(&format!("get_vec_mixed_3x_{}", size), |b| { 116 | b.iter(|| { 117 | if let Some((a, b, c)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 118 | black_box(a).inc(); 119 | black_box(b).inc(); 120 | black_box(c).inc(); 121 | } 122 | }) 123 | }); 124 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 125 | c.bench_function(&format!("get_parallelvec_mixed_3x_{}", size), |b| { 126 | b.iter(|| { 127 | if let Some((a, b, c)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 128 | black_box(a).inc(); 129 | black_box(b).inc(); 130 | black_box(c).inc(); 131 | } 132 | }) 133 | }); 134 | let big = (Big::default(), Big::default(), Big::default()); 135 | let mut vec = Vec::from(vec![big]).repeat(size); 136 | c.bench_function(&format!("get_vec_big_3x_{}", size), |b| { 137 | b.iter(|| { 138 | if let Some((a, b, c)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 139 | black_box(a).inc(); 140 | black_box(b).inc(); 141 | black_box(c).inc(); 142 | } 143 | }) 144 | }); 145 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 146 | c.bench_function(&format!("get_parallelvec_big_3x_{}", size), |b| { 147 | b.iter(|| { 148 | if let Some((a, b, c)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 149 | black_box(a).inc(); 150 | black_box(b).inc(); 151 | black_box(c).inc(); 152 | } 153 | }) 154 | }); 155 | } 156 | 157 | fn bench_get_4(c: &mut Criterion, size: usize) { 158 | let small = (Small(0), Small(1), Small(2), Small(3)); 159 | let mut rng = rand::thread_rng(); 160 | let mut vec = Vec::from(vec![small]).repeat(size); 161 | c.bench_function(&format!("get_vec_small_4x_{}", size), |b| { 162 | b.iter(|| { 163 | if let Some((a, b, c, d)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 164 | black_box(a).inc(); 165 | black_box(b).inc(); 166 | black_box(c).inc(); 167 | black_box(d).inc(); 168 | } 169 | }) 170 | }); 171 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 172 | c.bench_function(&format!("get_parallelvec_small_4x_{}", size), |b| { 173 | b.iter(|| { 174 | if let Some((a, b, c, d)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 175 | black_box(a).inc(); 176 | black_box(b).inc(); 177 | black_box(c).inc(); 178 | black_box(d).inc(); 179 | } 180 | }) 181 | }); 182 | let mixed = (Big::default(), Small(1), Big::default(), Small(2)); 183 | let mut vec = Vec::from(vec![mixed]).repeat(size); 184 | c.bench_function(&format!("get_vec_mixed_4x_{}", size), |b| { 185 | b.iter(|| { 186 | if let Some((a, b, c, d)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 187 | black_box(a).inc(); 188 | black_box(b).inc(); 189 | black_box(c).inc(); 190 | black_box(d).inc(); 191 | } 192 | }) 193 | }); 194 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 195 | c.bench_function(&format!("get_parallelvec_mixed_4x_{}", size), |b| { 196 | b.iter(|| { 197 | if let Some((a, b, c, d)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 198 | black_box(a).inc(); 199 | black_box(b).inc(); 200 | black_box(c).inc(); 201 | black_box(d).inc(); 202 | } 203 | }) 204 | }); 205 | let big = ( 206 | Big::default(), 207 | Big::default(), 208 | Big::default(), 209 | Big::default(), 210 | ); 211 | let mut vec = Vec::from(vec![big]).repeat(size); 212 | c.bench_function(&format!("get_vec_big_4x_{}", size), |b| { 213 | b.iter(|| { 214 | if let Some((a, b, c, d)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 215 | black_box(a).inc(); 216 | black_box(b).inc(); 217 | black_box(c).inc(); 218 | black_box(d).inc(); 219 | } 220 | }) 221 | }); 222 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 223 | c.bench_function(&format!("get_parallelvec_big_4x_{}", size), |b| { 224 | b.iter(|| { 225 | if let Some((a, b, c, d)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 226 | black_box(a).inc(); 227 | black_box(b).inc(); 228 | black_box(c).inc(); 229 | black_box(d).inc(); 230 | } 231 | }) 232 | }); 233 | } 234 | 235 | fn bench_get_5(c: &mut Criterion, size: usize) { 236 | let small = (Small(0), Small(1), Small(2), Small(3), Small(4)); 237 | let mut rng = rand::thread_rng(); 238 | let mut vec = Vec::from(vec![small]).repeat(size); 239 | c.bench_function(&format!("get_vec_small_5x_{}", size), |b| { 240 | b.iter(|| { 241 | if let Some((a, b, c, d, e)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 242 | black_box(a).inc(); 243 | black_box(b).inc(); 244 | black_box(c).inc(); 245 | black_box(d).inc(); 246 | black_box(e).inc(); 247 | } 248 | }) 249 | }); 250 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 251 | c.bench_function(&format!("get_parallelvec_small_5x_{}", size), |b| { 252 | b.iter(|| { 253 | if let Some((a, b, c, d, e)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 254 | black_box(a).inc(); 255 | black_box(b).inc(); 256 | black_box(c).inc(); 257 | black_box(d).inc(); 258 | black_box(e).inc(); 259 | } 260 | }) 261 | }); 262 | let mixed = ( 263 | Big::default(), 264 | Small(1), 265 | Big::default(), 266 | Small(2), 267 | Big::default(), 268 | ); 269 | let mut vec = Vec::from(vec![mixed]).repeat(size); 270 | c.bench_function(&format!("get_vec_mixed_5x_{}", size), |b| { 271 | b.iter(|| { 272 | if let Some((a, b, c, d, e)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 273 | black_box(a).inc(); 274 | black_box(b).inc(); 275 | black_box(c).inc(); 276 | black_box(d).inc(); 277 | black_box(e).inc(); 278 | } 279 | }) 280 | }); 281 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 282 | c.bench_function(&format!("get_parallelvec_mixed_5x_{}", size), |b| { 283 | b.iter(|| { 284 | if let Some((a, b, c, d, e)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 285 | black_box(a).inc(); 286 | black_box(b).inc(); 287 | black_box(c).inc(); 288 | black_box(d).inc(); 289 | black_box(e).inc(); 290 | } 291 | }) 292 | }); 293 | let big = ( 294 | Big::default(), 295 | Big::default(), 296 | Big::default(), 297 | Big::default(), 298 | Big::default(), 299 | ); 300 | let mut vec = Vec::from(vec![big]).repeat(size); 301 | c.bench_function(&format!("get_vec_big_5x_{}", size), |b| { 302 | b.iter(|| { 303 | if let Some((a, b, c, d, e)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 304 | black_box(a).inc(); 305 | black_box(b).inc(); 306 | black_box(c).inc(); 307 | black_box(d).inc(); 308 | black_box(e).inc(); 309 | } 310 | }) 311 | }); 312 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 313 | c.bench_function(&format!("get_parallelvec_big_5x_{}", size), |b| { 314 | b.iter(|| { 315 | if let Some((a, b, c, d, e)) = black_box(vec.get_mut(rng.next_u32() as usize % size)) { 316 | black_box(a).inc(); 317 | black_box(b).inc(); 318 | black_box(c).inc(); 319 | black_box(d).inc(); 320 | black_box(e).inc(); 321 | } 322 | }) 323 | }); 324 | } 325 | 326 | fn criterion_benchmark(c: &mut Criterion) { 327 | for size in [1000, 100000, 1000000] { 328 | bench_get_2(c, size); 329 | bench_get_3(c, size); 330 | bench_get_4(c, size); 331 | bench_get_5(c, size); 332 | } 333 | } 334 | 335 | criterion_group!(benches, criterion_benchmark); 336 | criterion_main!(benches); 337 | -------------------------------------------------------------------------------- /benches/iter.rs: -------------------------------------------------------------------------------- 1 | use criterion::{black_box, criterion_group, criterion_main, Criterion}; 2 | 3 | use parallel_vec::ParallelVec; 4 | 5 | #[derive(Clone, Copy, Default)] 6 | struct Small(u32); 7 | #[derive(Clone, Copy, Default)] 8 | struct Big([u64; 32]); 9 | 10 | trait Inc { 11 | fn inc(&mut self); 12 | } 13 | 14 | impl Inc for Small { 15 | fn inc(&mut self) { 16 | self.0 += 1; 17 | } 18 | } 19 | 20 | impl Inc for Big { 21 | fn inc(&mut self) { 22 | for i in 0..32 { 23 | self.0[i] += 1; 24 | } 25 | } 26 | } 27 | 28 | fn bench_iter_2(c: &mut Criterion, size: usize) { 29 | let small = (Small(0), Small(1)); 30 | let mut vec = Vec::from(vec![small]).repeat(size); 31 | c.bench_function(&format!("iter_vec_small_2x_{}", size), |b| { 32 | b.iter(|| { 33 | for (item_1, item_2) in vec.iter_mut() { 34 | black_box(item_1).inc(); 35 | black_box(item_2).inc(); 36 | } 37 | }) 38 | }); 39 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 40 | c.bench_function(&format!("iter_parallelvec_small_2x_{}", size), |b| { 41 | b.iter(|| { 42 | for (item_1, item_2) in vec.iter_mut() { 43 | black_box(item_1).inc(); 44 | black_box(item_2).inc(); 45 | } 46 | }) 47 | }); 48 | let mixed = (Big::default(), Small(1)); 49 | let mut vec = Vec::from(vec![mixed]).repeat(size); 50 | c.bench_function(&format!("iter_vec_mixed_2x_{}", size), |b| { 51 | b.iter(|| { 52 | for (item_1, item_2) in vec.iter_mut() { 53 | black_box(item_1).inc(); 54 | black_box(item_2).inc(); 55 | } 56 | }) 57 | }); 58 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 59 | c.bench_function(&format!("iter_parallelvec_mixed_2x_{}", size), |b| { 60 | b.iter(|| { 61 | for (item_1, item_2) in vec.iter_mut() { 62 | black_box(item_1).inc(); 63 | black_box(item_2).inc(); 64 | } 65 | }) 66 | }); 67 | let big = (Big::default(), Big::default()); 68 | let mut vec = Vec::from(vec![big]).repeat(size); 69 | c.bench_function(&format!("iter_vec_big_2x_{}", size), |b| { 70 | b.iter(|| { 71 | for (item_1, item_2) in vec.iter_mut() { 72 | black_box(item_1).inc(); 73 | black_box(item_2).inc(); 74 | } 75 | }) 76 | }); 77 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 78 | c.bench_function(&format!("iter_parallelvec_big_2x_{}", size), |b| { 79 | b.iter(|| { 80 | for (item_1, item_2) in vec.iter_mut() { 81 | black_box(item_1).inc(); 82 | black_box(item_2).inc(); 83 | } 84 | }) 85 | }); 86 | } 87 | 88 | fn bench_iter_3(c: &mut Criterion, size: usize) { 89 | let small = (Small(0), Small(1), Small(2)); 90 | let mut vec = Vec::from(vec![small]).repeat(size); 91 | c.bench_function(&format!("iter_vec_small_3x_{}", size), |b| { 92 | b.iter(|| { 93 | for (item_1, item_2, item_3) in vec.iter_mut() { 94 | black_box(item_1).inc(); 95 | black_box(item_2).inc(); 96 | black_box(item_3).inc(); 97 | } 98 | }) 99 | }); 100 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 101 | c.bench_function(&format!("iter_parallelvec_small_3x_{}", size), |b| { 102 | b.iter(|| { 103 | for (item_1, item_2, item_3) in vec.iter_mut() { 104 | black_box(item_1).inc(); 105 | black_box(item_2).inc(); 106 | black_box(item_3).inc(); 107 | } 108 | }) 109 | }); 110 | let mixed = (Big::default(), Small(1), Big::default()); 111 | let mut vec = Vec::from(vec![mixed]).repeat(size); 112 | c.bench_function(&format!("iter_vec_mixed_3x_{}", size), |b| { 113 | b.iter(|| { 114 | for (item_1, item_2, item_3) in vec.iter_mut() { 115 | black_box(item_1).inc(); 116 | black_box(item_2).inc(); 117 | black_box(item_3).inc(); 118 | } 119 | }) 120 | }); 121 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 122 | c.bench_function(&format!("iter_parallelvec_mixed_3x_{}", size), |b| { 123 | b.iter(|| { 124 | for (item_1, item_2, item_3) in vec.iter_mut() { 125 | black_box(item_1).inc(); 126 | black_box(item_2).inc(); 127 | black_box(item_3).inc(); 128 | } 129 | }) 130 | }); 131 | let big = (Big::default(), Big::default(), Big::default()); 132 | let mut vec = Vec::from(vec![big]).repeat(size); 133 | c.bench_function(&format!("iter_vec_big_3x_{}", size), |b| { 134 | b.iter(|| { 135 | for (item_1, item_2, item_3) in vec.iter_mut() { 136 | black_box(item_1).inc(); 137 | black_box(item_2).inc(); 138 | black_box(item_3).inc(); 139 | } 140 | }) 141 | }); 142 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 143 | c.bench_function(&format!("iter_parallelvec_big_3x_{}", size), |b| { 144 | b.iter(|| { 145 | for (item_1, item_2, item_3) in vec.iter_mut() { 146 | black_box(item_1).inc(); 147 | black_box(item_2).inc(); 148 | black_box(item_3).inc(); 149 | } 150 | }) 151 | }); 152 | } 153 | 154 | fn bench_iter_4(c: &mut Criterion, size: usize) { 155 | let small = (Small(0), Small(1), Small(2), Small(3)); 156 | let mut vec = Vec::from(vec![small]).repeat(size); 157 | c.bench_function(&format!("iter_vec_small_4x_{}", size), |b| { 158 | b.iter(|| { 159 | for (item_1, item_2, item_3, item_4) in vec.iter_mut() { 160 | black_box(item_1).inc(); 161 | black_box(item_2).inc(); 162 | black_box(item_3).inc(); 163 | black_box(item_4).inc(); 164 | } 165 | }) 166 | }); 167 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 168 | c.bench_function(&format!("iter_parallelvec_small_4x_{}", size), |b| { 169 | b.iter(|| { 170 | for (item_1, item_2, item_3, item_4) in vec.iter_mut() { 171 | black_box(item_1).inc(); 172 | black_box(item_2).inc(); 173 | black_box(item_3).inc(); 174 | black_box(item_4).inc(); 175 | } 176 | }) 177 | }); 178 | let mixed = (Big::default(), Small(1), Big::default(), Small(2)); 179 | let mut vec = Vec::from(vec![mixed]).repeat(size); 180 | c.bench_function(&format!("iter_vec_mixed_4x_{}", size), |b| { 181 | b.iter(|| { 182 | for (item_1, item_2, item_3, item_4) in vec.iter_mut() { 183 | black_box(item_1).inc(); 184 | black_box(item_2).inc(); 185 | black_box(item_3).inc(); 186 | black_box(item_4).inc(); 187 | } 188 | }) 189 | }); 190 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 191 | c.bench_function(&format!("iter_parallelvec_mixed_4x_{}", size), |b| { 192 | b.iter(|| { 193 | for (item_1, item_2, item_3, item_4) in vec.iter_mut() { 194 | black_box(item_1).inc(); 195 | black_box(item_2).inc(); 196 | black_box(item_3).inc(); 197 | black_box(item_4).inc(); 198 | } 199 | }) 200 | }); 201 | let big = ( 202 | Big::default(), 203 | Big::default(), 204 | Big::default(), 205 | Big::default(), 206 | ); 207 | let mut vec = Vec::from(vec![big]).repeat(size); 208 | c.bench_function(&format!("iter_vec_big_4x_{}", size), |b| { 209 | b.iter(|| { 210 | for (item_1, item_2, item_3, item_4) in vec.iter_mut() { 211 | black_box(item_1).inc(); 212 | black_box(item_2).inc(); 213 | black_box(item_3).inc(); 214 | black_box(item_4).inc(); 215 | } 216 | }) 217 | }); 218 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 219 | c.bench_function(&format!("iter_parallelvec_big_4x_{}", size), |b| { 220 | b.iter(|| { 221 | for (item_1, item_2, item_3, item_4) in vec.iter_mut() { 222 | black_box(item_1).inc(); 223 | black_box(item_2).inc(); 224 | black_box(item_3).inc(); 225 | black_box(item_4).inc(); 226 | } 227 | }) 228 | }); 229 | } 230 | 231 | fn bench_iter_5(c: &mut Criterion, size: usize) { 232 | let small = (Small(0), Small(1), Small(2), Small(3), Small(4)); 233 | let mut vec = Vec::from(vec![small]).repeat(size); 234 | c.bench_function(&format!("iter_vec_small_5x_{}", size), |b| { 235 | b.iter(|| { 236 | for (item_1, item_2, item_3, item_4, item_5) in vec.iter_mut() { 237 | black_box(item_1).inc(); 238 | black_box(item_2).inc(); 239 | black_box(item_3).inc(); 240 | black_box(item_4).inc(); 241 | black_box(item_5).inc(); 242 | } 243 | }) 244 | }); 245 | let mut vec = ParallelVec::from(vec![small]).repeat(size); 246 | c.bench_function(&format!("iter_parallelvec_small_5x_{}", size), |b| { 247 | b.iter(|| { 248 | for (item_1, item_2, item_3, item_4, item_5) in vec.iter_mut() { 249 | black_box(item_1).inc(); 250 | black_box(item_2).inc(); 251 | black_box(item_3).inc(); 252 | black_box(item_4).inc(); 253 | black_box(item_5).inc(); 254 | } 255 | }) 256 | }); 257 | let mixed = ( 258 | Big::default(), 259 | Small(1), 260 | Big::default(), 261 | Small(2), 262 | Big::default(), 263 | ); 264 | let mut vec = Vec::from(vec![mixed]).repeat(size); 265 | c.bench_function(&format!("iter_vec_mixed_5x_{}", size), |b| { 266 | b.iter(|| { 267 | for (item_1, item_2, item_3, item_4, item_5) in vec.iter_mut() { 268 | black_box(item_1).inc(); 269 | black_box(item_2).inc(); 270 | black_box(item_3).inc(); 271 | black_box(item_4).inc(); 272 | black_box(item_5).inc(); 273 | } 274 | }) 275 | }); 276 | let mut vec = ParallelVec::from(vec![mixed]).repeat(size); 277 | c.bench_function(&format!("iter_parallelvec_mixed_5x_{}", size), |b| { 278 | b.iter(|| { 279 | for (item_1, item_2, item_3, item_4, item_5) in vec.iter_mut() { 280 | black_box(item_1).inc(); 281 | black_box(item_2).inc(); 282 | black_box(item_3).inc(); 283 | black_box(item_4).inc(); 284 | black_box(item_5).inc(); 285 | } 286 | }) 287 | }); 288 | let big = ( 289 | Big::default(), 290 | Big::default(), 291 | Big::default(), 292 | Big::default(), 293 | Big::default(), 294 | ); 295 | let mut vec = Vec::from(vec![big]).repeat(size); 296 | c.bench_function(&format!("iter_vec_big_5x_{}", size), |b| { 297 | b.iter(|| { 298 | for (item_1, item_2, item_3, item_4, item_5) in vec.iter_mut() { 299 | black_box(item_1).inc(); 300 | black_box(item_2).inc(); 301 | black_box(item_3).inc(); 302 | black_box(item_4).inc(); 303 | black_box(item_5).inc(); 304 | } 305 | }) 306 | }); 307 | let mut vec = ParallelVec::from(vec![big]).repeat(size); 308 | c.bench_function(&format!("iter_parallelvec_big_5x_{}", size), |b| { 309 | b.iter(|| { 310 | for (item_1, item_2, item_3, item_4, item_5) in vec.iter_mut() { 311 | black_box(item_1).inc(); 312 | black_box(item_2).inc(); 313 | black_box(item_3).inc(); 314 | black_box(item_4).inc(); 315 | black_box(item_5).inc(); 316 | } 317 | }) 318 | }); 319 | } 320 | 321 | fn criterion_benchmark(c: &mut Criterion) { 322 | for size in [10, 100, 1000, 100000] { 323 | bench_iter_2(c, size); 324 | bench_iter_3(c, size); 325 | bench_iter_4(c, size); 326 | bench_iter_5(c, size); 327 | } 328 | } 329 | 330 | criterion_group!(benches, criterion_benchmark); 331 | criterion_main!(benches); 332 | -------------------------------------------------------------------------------- /src/iter.rs: -------------------------------------------------------------------------------- 1 | use crate::ParallelParam; 2 | use core::{ 3 | iter::{DoubleEndedIterator, ExactSizeIterator}, 4 | marker::PhantomData, 5 | }; 6 | 7 | /// An iterator over immutable references to values in a [`ParallelSlice`]. 8 | /// 9 | /// See [`ParallelSlice::iter`]. 10 | /// 11 | /// [`ParallelSlice`]: crate::ParallelSlice 12 | /// [`ParallelSlice::iter`]: crate::ParallelSlice::iter 13 | pub struct Iter<'a, Param: ParallelParam> { 14 | pub(crate) ptr: Param::Ptr, 15 | pub(crate) remaining: usize, 16 | pub(crate) _marker: PhantomData<&'a Param>, 17 | } 18 | 19 | impl<'a, Param: ParallelParam> Iterator for Iter<'a, Param> { 20 | type Item = Param::Ref<'a>; 21 | fn next(&mut self) -> Option> { 22 | unsafe { 23 | if self.remaining == 0 { 24 | return None; 25 | } 26 | let output = Param::as_ref(self.ptr); 27 | self.ptr = Param::add(self.ptr, 1); 28 | self.remaining -= 1; 29 | Some(output) 30 | } 31 | } 32 | 33 | fn size_hint(&self) -> (usize, Option) { 34 | (self.remaining, Some(self.remaining)) 35 | } 36 | } 37 | 38 | impl<'a, Param: ParallelParam> ExactSizeIterator for Iter<'a, Param> {} 39 | 40 | impl<'a, Param: ParallelParam> DoubleEndedIterator for Iter<'a, Param> { 41 | fn next_back(&mut self) -> Option> { 42 | unsafe { 43 | if self.remaining == 0 { 44 | return None; 45 | } 46 | self.remaining -= 1; 47 | let ptr = Param::add(self.ptr, self.remaining); 48 | Some(Param::as_ref(ptr)) 49 | } 50 | } 51 | } 52 | 53 | /// An iterator over mutable reference to values in a [`ParallelSliceMut`]. 54 | /// 55 | /// See [`ParallelSliceMut::iter_mut`]. 56 | /// 57 | /// [`ParallelSliceMut`]: crate::ParallelSliceMut 58 | /// [`ParallelSliceMut::iter_mut`]: crate::ParallelSliceMut::iter_mut 59 | pub struct IterMut<'a, Param: ParallelParam> { 60 | pub(crate) ptr: Param::Ptr, 61 | pub(crate) remaining: usize, 62 | pub(crate) _marker: PhantomData<&'a Param>, 63 | } 64 | 65 | impl<'a, Param: ParallelParam> Iterator for IterMut<'a, Param> { 66 | type Item = Param::RefMut<'a>; 67 | fn next(&mut self) -> Option { 68 | unsafe { 69 | if self.remaining == 0 { 70 | return None; 71 | } 72 | let output = Param::as_mut(self.ptr); 73 | self.ptr = Param::add(self.ptr, 1); 74 | self.remaining -= 1; 75 | Some(output) 76 | } 77 | } 78 | } 79 | 80 | impl<'a, Param: ParallelParam> ExactSizeIterator for IterMut<'a, Param> {} 81 | 82 | impl<'a, Param: ParallelParam> DoubleEndedIterator for IterMut<'a, Param> { 83 | fn next_back(&mut self) -> Option> { 84 | unsafe { 85 | if self.remaining == 0 { 86 | return None; 87 | } 88 | self.remaining -= 1; 89 | let ptr = Param::add(self.ptr, self.remaining); 90 | Some(Param::as_mut(ptr)) 91 | } 92 | } 93 | } 94 | 95 | /// An iterator over values from a [`ParallelVec`]. 96 | /// 97 | /// See [`ParallelVec::into_iter`]. 98 | /// 99 | /// [`ParallelVec`]: crate::ParallelVec 100 | /// [`ParallelVec::iter_mut`]: crate::ParallelVec::into_iter 101 | #[repr(C)] 102 | pub struct IntoIter { 103 | pub(crate) len: usize, 104 | pub(crate) storage: Param::Storage, 105 | pub(crate) capacity: usize, 106 | pub(crate) idx: usize, 107 | } 108 | 109 | impl Iterator for IntoIter { 110 | type Item = Param; 111 | fn next(&mut self) -> Option { 112 | unsafe { 113 | if self.idx >= self.len { 114 | return None; 115 | } 116 | let ptr = Param::ptr_at(self.storage, self.idx); 117 | let value = Param::read(ptr); 118 | self.idx += 1; 119 | Some(value) 120 | } 121 | } 122 | 123 | fn size_hint(&self) -> (usize, Option) { 124 | let remaining = self.len - self.idx; 125 | (remaining, Some(remaining)) 126 | } 127 | } 128 | 129 | impl ExactSizeIterator for IntoIter {} 130 | 131 | impl DoubleEndedIterator for IntoIter { 132 | fn next_back(&mut self) -> Option { 133 | unsafe { 134 | if self.len == 0 { 135 | return None; 136 | } 137 | self.len -= 1; 138 | let ptr = Param::ptr_at(self.storage, self.len); 139 | Some(Param::read(ptr)) 140 | } 141 | } 142 | } 143 | 144 | impl Drop for IntoIter { 145 | fn drop(&mut self) { 146 | unsafe { 147 | // Drop the unconsumed items. 148 | for idx in self.idx..self.len { 149 | Param::drop(Param::ptr_at(self.storage, idx)); 150 | } 151 | Param::dealloc(self.storage, self.capacity); 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | #![deny(missing_docs)] 3 | #![no_std] 4 | 5 | //! [`ParallelVec`] is a generic collection of contiguously stored heterogenous values with 6 | //! an API similar to that of a `Vec<(T1, T2, ...)>` but stores the data laid out as a 7 | //! separate slice per field, using a [structures of arrays](https://en.wikipedia.org/wiki/AoS_and_SoA#Structure_of_arrays) 8 | //! layout. The advantage of this layout is that cache utilization may be signifgantly improved 9 | //! when iterating over the data. 10 | //! 11 | //! This approach is common to game engines, and Entity-Component-Systems in particular but is 12 | //! applicable anywhere that cache coherency and memory bandwidth are important for performance. 13 | //! 14 | //! Unlike a struct of `Vec`s, only one length and capacity field is stored, and only one contiguous 15 | //! allocation is made for the entire data structs. Upon reallocation, a struct of `Vec` may apply 16 | //! additional allocation pressure. `ParallelVec` only allocates once per resize. 17 | //! 18 | //! ## Example 19 | //! ```rust 20 | //! use parallel_vec::ParallelVec; 21 | //! 22 | //! /// Some 'entity' data. 23 | //! # #[derive(Copy, Clone)] 24 | //! struct Position { x: f64, y: f64 } 25 | //! # #[derive(Copy, Clone)] 26 | //! struct Velocity { dx: f64, dy: f64 } 27 | //! struct ColdData { /* Potentially many fields omitted here */ } 28 | //! 29 | //! # use std::ops::Add; 30 | //! # impl Add for Position { type Output=Self; fn add(self, other: Velocity) -> Self { Self { x: self.x + other.dx, y: self.y + other.dy } } } 31 | //! // Create a vec of entities 32 | //! let mut entities: ParallelVec<(Position, Velocity, ColdData)> = ParallelVec::new(); 33 | //! entities.push((Position {x: 1.0, y: 2.0}, Velocity { dx: 0.0, dy: 0.5 }, ColdData {})); 34 | //! entities.push((Position {x: 0.0, y: 2.0}, Velocity { dx: 0.5, dy: 0.5 }, ColdData {})); 35 | //! 36 | //! // Update entities. This loop only loads position and velocity data, while skipping over 37 | //! // the ColdData which is not necessary for the physics simulation. 38 | //! for (position, velocity, _) in entities.iter_mut() { 39 | //! *position = *position + *velocity; 40 | //! } 41 | //! 42 | //! // Remove an entity 43 | //! entities.swap_remove(0); 44 | //! ``` 45 | //! 46 | //! ## Nightly 47 | //! This crate requires use of GATs and therefore requires the following nightly features: 48 | //! * `generic_associated_types` 49 | //! 50 | //! ## `no_std` Support 51 | //! By default, this crate requires the standard library. Disabling the default features 52 | //! enables this crate to compile in `#![no_std]` environments. There must be a set global 53 | //! allocator and heap support for this crate to work. 54 | //! 55 | //! ## `serde` Support 56 | //! `ParallelVec` can be serialized if it's parameters can be serialized. This is disabled by 57 | //! default. Use the `serde` feature to enable support for serialization and deserialization. 58 | 59 | extern crate alloc; 60 | 61 | #[cfg(any(test, feature = "std"))] 62 | #[macro_use] 63 | extern crate std; 64 | 65 | /// A collection of iterators types for [`ParallelVec`]. 66 | pub mod iter; 67 | /// Implementations for [`ParallelParam`]. 68 | pub mod param; 69 | #[cfg(feature = "serde")] 70 | #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] 71 | mod serde; 72 | mod slice; 73 | mod vec; 74 | 75 | #[cfg(feature = "serde")] 76 | pub use crate::serde::*; 77 | 78 | pub use param::ParallelParam; 79 | pub use slice::{ParallelSlice, ParallelSliceMut}; 80 | pub use vec::ParallelVec; 81 | 82 | /// Error when attempting to convert types to [`ParallelVec`]. 83 | #[derive(Debug, Clone, Hash, Eq, PartialEq)] 84 | pub enum ParallelVecConversionError { 85 | /// The provided inputs were not the same length. 86 | UnevenLengths, 87 | } 88 | 89 | #[inline(always)] 90 | pub(crate) fn assert_in_bounds(idx: usize, len: usize) { 91 | assert!(idx < len, "Index out of bounds: {} (len: {})", idx, len); 92 | } 93 | 94 | #[inline(always)] 95 | pub(crate) fn assert_in_bounds_inclusive(idx: usize, len: usize) { 96 | assert!(idx <= len, "Index out of bounds: {} (len: {})", idx, len); 97 | } 98 | 99 | #[inline(always)] 100 | pub(crate) fn out_of_bounds(idx: usize, len: usize) { 101 | panic!("Index out of bounds: {} (len: {})", idx, len); 102 | } 103 | -------------------------------------------------------------------------------- /src/param.rs: -------------------------------------------------------------------------------- 1 | use super::{ParallelVec, ParallelVecConversionError}; 2 | use alloc::{ 3 | alloc::{alloc, dealloc, handle_alloc_error, realloc, Layout}, 4 | vec::Vec, 5 | }; 6 | use core::ptr::NonNull; 7 | 8 | /// This trait contains the basic operations for creating variadic 9 | /// parallel vector implementations. 10 | /// 11 | /// This trait is sealed and cannot be implemented outside of 12 | /// `parallel_vec`. 13 | /// 14 | /// This trait has blanket implementations of all tuples of up 15 | /// to size 12 of all types that are `'static`. 16 | /// 17 | /// # Safety 18 | /// None of the associated functions can panic. 19 | pub unsafe trait ParallelParam: Sized + private::Sealed { 20 | /// A set of [`NonNull`] pointers of the parameter. 21 | /// This is the main backing storage pointers for [`ParallelVec`]. 22 | type Storage: Copy + Eq; 23 | /// A set of pointers of the parameter. 24 | type Ptr: Copy; 25 | /// A set of memory offsets of the parameter. 26 | type Offsets; 27 | /// A set of immutable references of the parameter. 28 | type Ref<'a>; 29 | /// A set of mutable references of the parameter. 30 | type RefMut<'a>; 31 | /// A set of [`Vec`]s of the parameter. 32 | type Vecs; 33 | /// A set of mutable slice references of the parameter. 34 | type Slices<'a>; 35 | /// A set of mutable slice references of the parameter. 36 | type SlicesMut<'a>; 37 | /// A set of iterators of immutable references of the parameter. 38 | type Iters<'a>; 39 | /// A set of iterators of mutable references of the parameter. 40 | type ItersMut<'a>; 41 | 42 | /// Creates a set of dangling pointers for the given types. 43 | fn dangling() -> Self::Storage; 44 | 45 | /// Converts a set of [`NonNull`]s into their associated 46 | /// pointer types. 47 | fn as_ptr(storage: Self::Storage) -> Self::Ptr; 48 | 49 | /// Allocates a buffer for a given capacity. 50 | /// 51 | /// # Safety 52 | /// Capacity should be non-zero. 53 | unsafe fn alloc(capacity: usize) -> Self::Storage; 54 | 55 | /// Realloc a buffer allocated from [`alloc`]. 56 | /// 57 | /// # Safety 58 | /// `storage` must have been allocated from [`alloc`] or [`realloc`] alongside 59 | /// the provided `current_capacity`. 60 | /// 61 | /// [`alloc`]: Self::alloc 62 | unsafe fn realloc( 63 | storage: Self::Storage, 64 | current_capacity: usize, 65 | new_capacity: usize, 66 | ) -> Self::Storage; 67 | 68 | /// Deallocates a buffer allocated from [`alloc`]. 69 | /// 70 | /// # Safety 71 | /// `storage` must have been allocated from [`alloc`] alongside 72 | /// the provided `capacity`. 73 | /// 74 | /// [`alloc`]: Self::alloc 75 | unsafe fn dealloc(storage: Self::Storage, capacity: usize); 76 | 77 | /// Gets the pointer at a given index. 78 | /// 79 | /// # Safety 80 | /// `storage` must be a set of valid pointers, and `idx` must be in 81 | /// bounds for the associated allocation. 82 | /// 83 | /// [`alloc`]: Self::alloc 84 | unsafe fn ptr_at(storage: Self::Storage, idx: usize) -> Self::Ptr { 85 | Self::add(Self::as_ptr(storage), idx) 86 | } 87 | 88 | /// Gets the legnth for the associated `Vec`s. 89 | /// 90 | /// Returns `None` if not all of the `Vec`s share the same 91 | /// length. 92 | fn get_vec_len(vecs: &Self::Vecs) -> Option; 93 | 94 | /// Gets the underlying pointers for the associated `Vec`s. 95 | /// 96 | /// # Safety 97 | /// The provided `Vec`s must be correctly allocated. 98 | unsafe fn get_vec_ptrs(vecs: &mut Self::Vecs) -> Self::Ptr; 99 | 100 | /// Adds `offset` to all of the pointers in `base`. 101 | /// 102 | /// # Safety 103 | /// `base` and `base + offset` must be valid non-null pointers for 104 | /// the associated types. 105 | unsafe fn add(base: Self::Ptr, offset: usize) -> Self::Ptr; 106 | 107 | /// Copies `size` elements from the continguous memory pointed to by `src` into 108 | /// `dst`. 109 | /// 110 | /// # Safety 111 | /// - `src` and `dst` must be a valid, non-null pointer for the associated types. 112 | /// - `size` must be approriately set for the allocation that both `src` and `dst` 113 | /// point to. 114 | unsafe fn copy_to(src: Self::Ptr, dst: Self::Ptr, size: usize); 115 | 116 | /// Copies `size` elements from the continguous memory pointed to by `src` into 117 | /// `dst`. 118 | /// 119 | /// # Safety 120 | /// - `src` and `dst` must be a valid, non-null pointer for the associated types. 121 | /// - `size` must be approriately set for the allocation that both `src` and `dst` 122 | /// point to. 123 | /// - `src..src + size` must not overlap with the memory range of `dst..dst + size`. 124 | unsafe fn copy_to_nonoverlapping(src: Self::Ptr, dst: Self::Ptr, size: usize); 125 | 126 | /// Creates a set of immutable slices from `ptr` and a provided length. 127 | /// 128 | /// # Safety 129 | /// `ptr` must be a valid, non-null pointer. `len` must be approriately set 130 | /// for the allocation that `ptr` points to. 131 | unsafe fn as_slices<'a>(ptr: Self::Ptr, len: usize) -> Self::Slices<'a>; 132 | 133 | /// Creates a set of mutable slices from `ptr` and a provided length. 134 | /// 135 | /// # Safety 136 | /// `ptr` must be a valid, non-null pointer. `len` must be approriately set 137 | /// for the allocation that `ptr` points to. 138 | unsafe fn as_slices_mut<'a>(ptr: Self::Ptr, len: usize) -> Self::SlicesMut<'a>; 139 | 140 | /// Creates a set of iterators from slices. 141 | #[allow(clippy::needless_lifetimes)] 142 | fn iters<'a>(slices: Self::Slices<'a>) -> Self::Iters<'a>; 143 | 144 | /// Creates a set of iterators of mutable references from slices. 145 | #[allow(clippy::needless_lifetimes)] 146 | fn iters_mut<'a>(slices: Self::SlicesMut<'a>) -> Self::ItersMut<'a>; 147 | 148 | /// Reverses the order of elements in the slice, in place. 149 | fn reverse(ptr: Self::SlicesMut<'_>); 150 | 151 | /// Converts `ptr` into a set of immutable references. 152 | /// 153 | /// # Safety 154 | /// `ptr` must be a valid, non-null pointer. 155 | unsafe fn as_ref<'a>(ptr: Self::Ptr) -> Self::Ref<'a>; 156 | 157 | /// Converts `ptr` into the storage type. 158 | /// 159 | /// # Safety 160 | /// `ptr` must be a valid, non-null pointer. 161 | unsafe fn as_storage(ptr: Self::Ptr) -> Self::Storage; 162 | 163 | /// Converts `ptr` into a set of mutable references. 164 | /// 165 | /// # Safety 166 | /// `ptr` must be a valid, non-null pointer. 167 | unsafe fn as_mut<'a>(ptr: Self::Ptr) -> Self::RefMut<'a>; 168 | 169 | /// Reads the values to pointed to by `ptr`. 170 | /// 171 | /// # Safety 172 | /// `ptr` must be a valid, non-null pointer. 173 | unsafe fn read(ptr: Self::Ptr) -> Self; 174 | 175 | /// Writes `value` to `ptr`. 176 | /// 177 | /// # Safety 178 | /// `ptr` must be a valid, non-null pointer. 179 | unsafe fn write(ptr: Self::Ptr, value: Self); 180 | 181 | /// Swaps the values pointed to by the provided pointers. 182 | /// 183 | /// # Safety 184 | /// Both `a` and `b` must be valid for all of it's consitutent member pointers. 185 | unsafe fn swap(a: Self::Ptr, other: Self::Ptr); 186 | 187 | /// Drops the values pointed to by the pointers. 188 | /// 189 | /// # Safety 190 | /// The caller must ensure that the values pointed to by the pointers have 191 | /// not already been dropped prior. 192 | unsafe fn drop(ptr: Self::Ptr); 193 | } 194 | 195 | mod private { 196 | pub trait Sealed {} 197 | 198 | macro_rules! impl_seal { 199 | ($($ts:ident),*) => { 200 | impl<$($ts,)*> Sealed for ($($ts,)*) {} 201 | } 202 | } 203 | 204 | impl_seal!(T1, T2); 205 | impl_seal!(T1, T2, T3); 206 | impl_seal!(T1, T2, T3, T4); 207 | impl_seal!(T1, T2, T3, T4, T5); 208 | impl_seal!(T1, T2, T3, T4, T5, T6); 209 | impl_seal!(T1, T2, T3, T4, T5, T6, T7); 210 | impl_seal!(T1, T2, T3, T4, T5, T6, T7, T8); 211 | impl_seal!(T1, T2, T3, T4, T5, T6, T7, T8, T9); 212 | impl_seal!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); 213 | impl_seal!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); 214 | impl_seal!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); 215 | } 216 | 217 | macro_rules! skip_first { 218 | ($first:ident, $second: ident) => { 219 | $second 220 | }; 221 | } 222 | 223 | macro_rules! impl_parallel_vec_param { 224 | ($t1: ident, $v1: ident, $($ts:ident, $vs:ident),*) => { 225 | unsafe impl<$t1: 'static $(, $ts: 'static)*> ParallelParam for ($t1 $(, $ts)*) { 226 | type Storage = (NonNull<$t1> $(, NonNull<$ts>)*); 227 | type Ref<'a> = (&'a $t1, $(&'a $ts,)*); 228 | type RefMut<'a> = (&'a mut $t1, $(&'a mut $ts,)*); 229 | type Slices<'a> = (&'a [$t1] $(, &'a [$ts])*); 230 | type SlicesMut<'a> = (&'a mut [$t1] $(, &'a mut [$ts])*); 231 | type Vecs = (Vec<$t1> $(, Vec<$ts>)*); 232 | type Ptr = (*mut $t1 $(, *mut $ts)*); 233 | type Offsets = (usize $(, skip_first!($ts, usize))*); 234 | type Iters<'a> = (core::slice::Iter<'a, $t1> $(, core::slice::Iter<'a, $ts>)*); 235 | type ItersMut<'a>= (core::slice::IterMut<'a, $t1> $(, core::slice::IterMut<'a, $ts>)*); 236 | 237 | #[inline(always)] 238 | fn dangling() -> Self::Storage { 239 | (NonNull::dangling(), $(NonNull::<$ts>::dangling()),*) 240 | } 241 | 242 | #[inline(always)] 243 | fn as_ptr(storage: Self::Storage) -> Self::Ptr { 244 | let ($t1$(, $ts)*) = storage; 245 | ($t1.as_ptr() $(, $ts.as_ptr())*) 246 | } 247 | 248 | unsafe fn alloc(capacity: usize) -> Self::Storage { 249 | debug_assert!(capacity != 0); 250 | let $t1 = if core::mem::size_of::<$t1>() != 0 { 251 | let layout = Layout::array::<$t1>(capacity).unwrap(); 252 | let ptr = alloc(layout).cast::<$t1>(); 253 | NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout)) 254 | } else { 255 | NonNull::dangling() 256 | }; 257 | $( 258 | let $ts = if core::mem::size_of::<$ts>() != 0 { 259 | let layout = Layout::array::<$ts>(capacity).unwrap(); 260 | let ptr = alloc(layout).cast::<$ts>(); 261 | NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout)) 262 | } else { 263 | NonNull::dangling() 264 | }; 265 | )* 266 | ($t1 $(, $ts)*) 267 | } 268 | 269 | unsafe fn realloc(storage: Self::Storage, current_capacity: usize, new_capacity: usize) -> Self::Storage { 270 | if new_capacity == 0 { 271 | Self::dealloc(storage, current_capacity); 272 | return Self::dangling(); 273 | } 274 | if current_capacity == 0 { 275 | return Self::alloc(new_capacity); 276 | } 277 | let ($t1 $(, $ts)*) = storage; 278 | let $t1 = if core::mem::size_of::<$t1>() != 0 { 279 | let layout = Layout::array::<$t1>(current_capacity).unwrap(); 280 | let new_size = core::mem::size_of::<$t1>().checked_mul(new_capacity).unwrap(); 281 | let ptr = realloc($t1.as_ptr().cast::(), layout, new_size).cast::<$t1>(); 282 | NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout)) 283 | } else { 284 | $t1 285 | }; 286 | $( 287 | let $ts = if core::mem::size_of::<$ts>() != 0 { 288 | let layout = Layout::array::<$ts>(current_capacity).unwrap(); 289 | let new_size = core::mem::size_of::<$ts>().checked_mul(new_capacity).unwrap(); 290 | let ptr = realloc($ts.as_ptr().cast::(), layout, new_size).cast::<$ts>(); 291 | NonNull::new(ptr).unwrap_or_else(|| handle_alloc_error(layout)) 292 | } else { 293 | $ts 294 | }; 295 | )* 296 | ($t1 $(, $ts)*) 297 | } 298 | 299 | unsafe fn dealloc(storage: Self::Storage, capacity: usize) { 300 | if capacity == 0 { 301 | return; 302 | } 303 | let ($t1 $(, $ts)*) = storage; 304 | if core::mem::size_of::<$t1>() != 0 { 305 | dealloc($t1.as_ptr().cast::(), Layout::array::<$t1>(capacity).unwrap_unchecked()); 306 | } 307 | $( 308 | if core::mem::size_of::<$ts>() != 0 { 309 | dealloc($ts.as_ptr().cast::(), Layout::array::<$ts>(capacity).unwrap_unchecked()); 310 | } 311 | )* 312 | } 313 | 314 | #[inline(always)] 315 | unsafe fn add(base: Self::Ptr, offset: usize) -> Self::Ptr { 316 | let ($t1, $($ts),*) = base; 317 | ($t1.add(offset), $($ts.add(offset)),*) 318 | } 319 | 320 | #[inline(always)] 321 | unsafe fn copy_to(src: Self::Ptr, dst: Self::Ptr, len: usize) { 322 | let ($t1, $($ts),*) = src; 323 | let ($v1, $($vs),*) = dst; 324 | $t1.copy_to($v1, len); 325 | $($ts.copy_to($vs, len);)* 326 | } 327 | 328 | #[inline(always)] 329 | unsafe fn copy_to_nonoverlapping(src: Self::Ptr, dst: Self::Ptr, len: usize) { 330 | let ($t1, $($ts),*) = src; 331 | let ($v1, $($vs),*) = dst; 332 | $t1.copy_to_nonoverlapping($v1, len); 333 | $( 334 | $ts.copy_to_nonoverlapping($vs, len); 335 | )* 336 | } 337 | 338 | #[inline(always)] 339 | unsafe fn as_slices<'a>(ptr: Self::Ptr, len: usize) -> Self::Slices<'a> { 340 | let ($t1, $($ts),*) = ptr; 341 | ( 342 | core::slice::from_raw_parts($t1, len) 343 | $( 344 | , core::slice::from_raw_parts($ts, len) 345 | )* 346 | ) 347 | } 348 | 349 | #[inline(always)] 350 | unsafe fn as_slices_mut<'a>(ptr: Self::Ptr, len: usize) -> Self::SlicesMut<'a> { 351 | let ($t1, $($ts),*) = ptr; 352 | ( 353 | core::slice::from_raw_parts_mut($t1, len) 354 | $( 355 | , core::slice::from_raw_parts_mut($ts, len) 356 | )* 357 | ) 358 | } 359 | 360 | #[inline(always)] 361 | fn iters<'a>(slices: Self::Slices<'a>) -> Self::Iters<'a> { 362 | let ($t1, $($ts),*) = slices; 363 | ($t1.iter() $(, $ts.iter())*) 364 | } 365 | 366 | #[inline(always)] 367 | fn iters_mut<'a>(slices: Self::SlicesMut<'a>) -> Self::ItersMut<'a> { 368 | let ($t1, $($ts),*) = slices; 369 | ($t1.iter_mut() $(, $ts.iter_mut())*) 370 | } 371 | 372 | #[inline(always)] 373 | fn reverse<'a>(slices: Self::SlicesMut<'a>) { 374 | let ($t1, $($ts),*) = slices; 375 | $t1.reverse(); 376 | $($ts.reverse();)* 377 | } 378 | 379 | #[inline(always)] 380 | unsafe fn as_storage<'a>(ptr: Self::Ptr) -> Self::Storage { 381 | let ($t1 $(, $ts)*) = ptr; 382 | ( 383 | NonNull::new_unchecked($t1) 384 | $(, NonNull::new_unchecked($ts))* 385 | ) 386 | } 387 | 388 | #[inline(always)] 389 | unsafe fn as_ref<'a>(ptr: Self::Ptr) -> Self::Ref<'a> { 390 | let ($t1, $($ts),*) = ptr; 391 | (&*$t1 $(, &*$ts)*) 392 | } 393 | 394 | #[inline(always)] 395 | unsafe fn as_mut<'a>(ptr: Self::Ptr) -> Self::RefMut<'a> { 396 | let ($t1, $($ts),*) = ptr; 397 | (&mut *$t1 $(, &mut *$ts)*) 398 | } 399 | 400 | #[inline(always)] 401 | unsafe fn read(ptr: Self::Ptr) -> Self { 402 | let ($t1, $($ts),*) = ptr; 403 | ($t1.read() $(, $ts.read())*) 404 | } 405 | 406 | #[inline(always)] 407 | unsafe fn write(ptr: Self::Ptr, value: Self) { 408 | let ($t1, $($ts),*) = ptr; 409 | let ($v1, $($vs),*) = value; 410 | $t1.write($v1); 411 | $($ts.write($vs);)* 412 | } 413 | 414 | #[inline(always)] 415 | unsafe fn swap(a: Self::Ptr, b: Self::Ptr) { 416 | let ($v1, $($vs),*) = a; 417 | let ($t1, $($ts),*) = b; 418 | core::ptr::swap($t1, $v1); 419 | $(core::ptr::swap($ts, $vs);)* 420 | } 421 | 422 | #[inline(always)] 423 | unsafe fn drop(ptr: Self::Ptr) { 424 | let ($t1, $($ts),*) = ptr; 425 | core::ptr::drop_in_place($t1); 426 | $(core::ptr::drop_in_place($ts);)* 427 | } 428 | 429 | fn get_vec_len(vecs: &Self::Vecs) -> Option { 430 | let ($t1, $($ts),*) = vecs; 431 | let len = $t1.len(); 432 | $( 433 | if $ts.len() != len { 434 | return None; 435 | } 436 | )* 437 | Some(len) 438 | } 439 | 440 | unsafe fn get_vec_ptrs(vecs: &mut Self::Vecs) -> Self::Ptr { 441 | let ($t1, $($ts),*) = vecs; 442 | ($t1.as_mut_ptr() $(, $ts.as_mut_ptr())*) 443 | } 444 | } 445 | 446 | impl<$t1: 'static $(, $ts: 'static)*> TryFrom<(Vec<$t1> $(, Vec<$ts>)*)> for ParallelVec<($t1 $(, $ts)*)> { 447 | type Error = ParallelVecConversionError; 448 | fn try_from(mut vecs: (Vec<$t1> $(, Vec<$ts>)*)) -> Result { 449 | let len = <($t1 $(, $ts)*) as ParallelParam>::get_vec_len(&vecs); 450 | if let Some(len) = len { 451 | let parallel_vec = Self::with_capacity(len); 452 | // SAFE: This is a move. Nothing should be dropped here. 453 | unsafe { 454 | let src = <($t1 $(, $ts)*) as ParallelParam>::get_vec_ptrs(&mut vecs); 455 | let dst = <($t1 $(, $ts)*) as ParallelParam>::as_ptr(parallel_vec.storage); 456 | <($t1 $(, $ts)*) as ParallelParam>::copy_to_nonoverlapping(src, dst, len); 457 | core::mem::forget(vecs); 458 | } 459 | Ok(parallel_vec) 460 | } else { 461 | Err(ParallelVecConversionError::UnevenLengths) 462 | } 463 | } 464 | } 465 | } 466 | } 467 | 468 | impl_parallel_vec_param!(T1, V1, T2, V2); 469 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, V3); 470 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, V3, T4, V4); 471 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, V3, T4, V4, T5, V5); 472 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, V3, T4, V4, T5, V5, T6, V6); 473 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, V3, T4, V4, T5, V5, T6, V6, T7, V7); 474 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, V3, T4, V4, T5, V5, T6, V6, T7, V7, T8, V8); 475 | impl_parallel_vec_param!(T1, V1, T2, V2, T3, T4, V3, V4, T5, V5, T6, V6, T7, V7, T8, V8, T9, V9); 476 | impl_parallel_vec_param!( 477 | T1, V1, T2, V2, T3, T4, V3, V4, T5, V5, T6, V6, T7, V7, T8, V8, T9, V9, T10, V10 478 | ); 479 | impl_parallel_vec_param!( 480 | T1, V1, T2, V2, T3, T4, V3, V4, T5, V5, T6, V6, T7, V7, T8, V8, T9, V9, T10, V10, T11, V11 481 | ); 482 | impl_parallel_vec_param!( 483 | T1, V1, T2, V2, T3, T4, V3, V4, T5, V5, T6, V6, T7, V7, T8, V8, T9, V9, T10, V10, T11, V11, 484 | T12, V12 485 | ); 486 | -------------------------------------------------------------------------------- /src/serde.rs: -------------------------------------------------------------------------------- 1 | use crate::{ParallelParam, ParallelVec}; 2 | use alloc::vec::Vec; 3 | use serde::{ 4 | de::DeserializeOwned, ser::SerializeSeq, Deserialize, Deserializer, Serialize, Serializer, 5 | }; 6 | 7 | impl<'a, Param> Serialize for ParallelVec 8 | where 9 | Param: ParallelParam + 'a, 10 | Param::Ref<'a>: Serialize, 11 | { 12 | fn serialize(&self, serializer: S) -> Result 13 | where 14 | S: Serializer, 15 | { 16 | let mut seq = serializer.serialize_seq(Some(self.len()))?; 17 | for item in self.iter() { 18 | seq.serialize_element(&item)?; 19 | } 20 | seq.end() 21 | } 22 | } 23 | 24 | impl<'de, Param> Deserialize<'de> for ParallelVec 25 | where 26 | Param: ParallelParam + DeserializeOwned, 27 | { 28 | fn deserialize(deserializer: D) -> Result 29 | where 30 | D: Deserializer<'de>, 31 | { 32 | Ok(Self::from( as Deserialize<'de>>::deserialize( 33 | deserializer, 34 | )?)) 35 | } 36 | } 37 | 38 | #[cfg(test)] 39 | mod test { 40 | use crate::ParallelVec; 41 | use serde_test::{assert_tokens, Token}; 42 | 43 | #[test] 44 | fn test_serde_empty() { 45 | let vec: ParallelVec<(u64, i32)> = ParallelVec::new(); 46 | assert_tokens(&vec, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); 47 | } 48 | 49 | #[test] 50 | fn test_serde_2() { 51 | let vec: ParallelVec<(i32, u64)> = ParallelVec::from(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 52 | assert_tokens( 53 | &vec, 54 | &[ 55 | Token::Seq { len: Some(4) }, 56 | Token::Tuple { len: 2 }, 57 | Token::I32(1), 58 | Token::U64(2), 59 | Token::TupleEnd, 60 | Token::Tuple { len: 2 }, 61 | Token::I32(3), 62 | Token::U64(4), 63 | Token::TupleEnd, 64 | Token::Tuple { len: 2 }, 65 | Token::I32(5), 66 | Token::U64(6), 67 | Token::TupleEnd, 68 | Token::Tuple { len: 2 }, 69 | Token::I32(7), 70 | Token::U64(8), 71 | Token::TupleEnd, 72 | Token::SeqEnd, 73 | ], 74 | ); 75 | } 76 | 77 | #[test] 78 | fn test_serde_3() { 79 | let vec: ParallelVec<(i32, u64, f32)> = 80 | ParallelVec::from(vec![(1, 2, 0.0), (3, 4, -1.0), (5, 6, -2.0), (7, 8, -3.0)]); 81 | assert_tokens( 82 | &vec, 83 | &[ 84 | Token::Seq { len: Some(4) }, 85 | Token::Tuple { len: 3 }, 86 | Token::I32(1), 87 | Token::U64(2), 88 | Token::F32(0.0), 89 | Token::TupleEnd, 90 | Token::Tuple { len: 3 }, 91 | Token::I32(3), 92 | Token::U64(4), 93 | Token::F32(-1.0), 94 | Token::TupleEnd, 95 | Token::Tuple { len: 3 }, 96 | Token::I32(5), 97 | Token::U64(6), 98 | Token::F32(-2.0), 99 | Token::TupleEnd, 100 | Token::Tuple { len: 3 }, 101 | Token::I32(7), 102 | Token::U64(8), 103 | Token::F32(-3.0), 104 | Token::TupleEnd, 105 | Token::SeqEnd, 106 | ], 107 | ); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/slice.rs: -------------------------------------------------------------------------------- 1 | use crate::iter::{Iter, IterMut}; 2 | use crate::ParallelParam; 3 | use crate::{assert_in_bounds, assert_in_bounds_inclusive}; 4 | use alloc::vec::Vec; 5 | use core::{ 6 | cmp::Ordering, 7 | hash::{Hash, Hasher}, 8 | marker::PhantomData, 9 | ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo}, 10 | }; 11 | 12 | /// A immutable dynamically-sized view into a contiguous heterogeneous sequence. 13 | /// Contiguous here means that elements are laid out so that every element is 14 | /// the same distance from its neighbors. 15 | /// 16 | /// Unlike a struct of slices, this type only stores one length instead 17 | /// of duplicating the values across multiple slice fields. 18 | #[repr(C)] 19 | pub struct ParallelSlice<'a, Param: ParallelParam> { 20 | // Do not reorder these fields. These must be in the same order as 21 | // ParallelVec for Deref and DerefMut to work properly. 22 | len: usize, 23 | storage: Param::Storage, 24 | _marker: PhantomData<&'a usize>, 25 | } 26 | 27 | impl<'a, Param: ParallelParam> ParallelSlice<'a, Param> { 28 | /// Forms a slice from a pointer and a length. 29 | /// 30 | /// The `len` argument is the number of elements, not the number of bytes. 31 | /// 32 | /// # Safety 33 | /// 34 | /// Behavior is undefined if any of the following conditions are violated: 35 | /// 36 | /// * `data` must be valid for both reads and writes for `len * mem::size_of::()` many bytes, 37 | /// and it must be properly aligned. This means in particular: 38 | /// 39 | /// * The entire memory range of this slice must be contained within a single allocated object! 40 | /// Slices can never span across multiple allocated objects. 41 | /// * `data` must be non-null and aligned even for zero-length slices. One 42 | /// reason for this is that enum layout optimizations may rely on references 43 | /// (including slices of any length) being aligned and non-null to distinguish 44 | /// them from other data. You can obtain a pointer that is usable as `data` 45 | /// for zero-length slices using [`ParallelParam::dangling()`]. 46 | /// * `data` must point to `len` consecutive properly initialized values of type `Param`. 47 | /// * The memory referenced by the returned slice must not be accessed through any other pointer 48 | /// (not derived from the return value) for the duration of lifetime `'a`. 49 | /// Both read and write accesses are forbidden. 50 | /// * The total size `len * mem::size_of::()` of the slice must be no larger than `isize::MAX`. 51 | /// 52 | /// [`ParallelParam::dangling()`]: ParallelParam::dangling 53 | pub unsafe fn from_raw_parts(data: Param::Storage, len: usize) -> Self { 54 | Self { 55 | len, 56 | storage: data, 57 | _marker: PhantomData, 58 | } 59 | } 60 | 61 | /// Returns the number of elements in the vector, also referred to as its ‘length’. 62 | pub fn len(&self) -> usize { 63 | self.len 64 | } 65 | 66 | /// Returns `true` if the vector contains no elements. 67 | pub fn is_empty(&self) -> bool { 68 | self.len == 0 69 | } 70 | 71 | /// Returns a immutable reference to the element at `index`, if available, or 72 | /// [`None`] if it is out of bounds. 73 | /// 74 | /// [`None`]: Option::None 75 | #[inline] 76 | pub fn get<'b: 'a, I: ParallelSliceIndex>(&'b self, index: I) -> Option { 77 | index.get(self) 78 | } 79 | 80 | /// Returns the first element of the slice, or `None` if it is empty. 81 | #[inline(always)] 82 | pub fn first(&self) -> Option> { 83 | self.get(0) 84 | } 85 | 86 | /// Returns the last element of the slice, or `None` if it is empty. 87 | #[inline] 88 | pub fn last(&self) -> Option> { 89 | if self.len == 0 { 90 | None 91 | } else { 92 | unsafe { Some(self.get_unchecked(self.len - 1)) } 93 | } 94 | } 95 | 96 | /// Gets a immutable reference to the elements at `index`. 97 | /// 98 | /// # Panics 99 | /// This function will panic if `index` is >= `self.len`. 100 | #[inline] 101 | pub fn index(&self, index: I) -> I::Output 102 | where 103 | I: ParallelSliceIndex, 104 | { 105 | index.index(self) 106 | } 107 | 108 | /// Returns references to elements, without doing bounds checking. 109 | /// 110 | /// For a safe alternative see [`get`]. 111 | /// 112 | /// # Safety 113 | /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used. 114 | /// 115 | /// [`get`]: Self::get 116 | #[inline] 117 | pub unsafe fn get_unchecked(&self, index: usize) -> Param::Ref<'_> { 118 | Param::as_ref(Param::ptr_at(self.storage, index)) 119 | } 120 | 121 | /// Gets the individual slices for every sub-slice. 122 | #[inline] 123 | pub fn as_slices(&self) -> Param::Slices<'_> { 124 | unsafe { Param::as_slices(Param::as_ptr(self.storage), self.len) } 125 | } 126 | 127 | /// Returns an iterator over the [`ParallelSlice`]. 128 | pub fn iter(&self) -> Iter<'a, Param> { 129 | Iter { 130 | ptr: Param::as_ptr(self.storage), 131 | remaining: self.len, 132 | _marker: PhantomData, 133 | } 134 | } 135 | 136 | /// Returns an iterator over the [`ParallelSlice`]. 137 | pub fn iters(&self) -> Param::Iters<'_> { 138 | unsafe { 139 | let ptr = Param::as_ptr(self.storage); 140 | let slices = Param::as_slices(ptr, self.len); 141 | Param::iters(slices) 142 | } 143 | } 144 | } 145 | 146 | impl<'s, 'r, Param> Hash for ParallelSlice<'s, Param> 147 | where 148 | Param: ParallelParam + 's, 149 | Param::Ref<'s>: Hash, 150 | 'r: 's, 151 | { 152 | fn hash(&self, hasher: &mut H) 153 | where 154 | H: Hasher, 155 | { 156 | self.len.hash(hasher); 157 | for item in self.iter() { 158 | item.hash(hasher); 159 | } 160 | } 161 | } 162 | 163 | /// A mutable dynamically-sized view into a contiguous heterogeneous sequence. 164 | /// Contiguous here means that elements are laid out so that every element is 165 | /// the same distance from its neighbors. 166 | /// 167 | /// Unlike a struct of slices, this type only stores one length instead 168 | /// of duplicating the values across multiple slice fields. 169 | #[repr(C)] 170 | pub struct ParallelSliceMut<'a, Param: ParallelParam> { 171 | // Do not reorder these fields. These must be in the same order as 172 | // ParallelVec for Deref and DerefMut to work properly. 173 | len: usize, 174 | storage: Param::Storage, 175 | _marker: PhantomData<&'a usize>, 176 | } 177 | 178 | impl<'a, Param: ParallelParam> ParallelSliceMut<'a, Param> { 179 | /// Forms a slice from a pointer and a length. 180 | /// 181 | /// The `len` argument is the number of elements, not the number of bytes. 182 | /// 183 | /// # Safety 184 | /// 185 | /// Behavior is undefined if any of the following conditions are violated: 186 | /// 187 | /// * `data` must be valid for both reads and writes for `len * mem::size_of::()` many bytes, 188 | /// and it must be properly aligned. This means in particular: 189 | /// 190 | /// * The entire memory range of this slice must be contained within a single allocated object! 191 | /// Slices can never span across multiple allocated objects. 192 | /// * `data` must be non-null and aligned even for zero-length slices. One 193 | /// reason for this is that enum layout optimizations may rely on references 194 | /// (including slices of any length) being aligned and non-null to distinguish 195 | /// them from other data. You can obtain a pointer that is usable as `data` 196 | /// for zero-length slices using [`ParallelParam::dangling()`]. 197 | /// * `data` must point to `len` consecutive properly initialized values of type `Param`. 198 | /// * The memory referenced by the returned slice must not be accessed through any other pointer 199 | /// (not derived from the return value) for the duration of lifetime `'a`. 200 | /// Both read and write accesses are forbidden. 201 | /// * The total size `len * mem::size_of::()` of the slice must be no larger than `isize::MAX`. 202 | /// 203 | /// [`ParallelParam::dangling()`]: ParallelParam::dangling 204 | pub unsafe fn from_raw_parts(data: Param::Storage, len: usize) -> Self { 205 | Self { 206 | len, 207 | storage: data, 208 | _marker: PhantomData, 209 | } 210 | } 211 | 212 | /// Returns the number of elements in the vector, also referred to as its ‘length’. 213 | pub fn len(&self) -> usize { 214 | self.len 215 | } 216 | 217 | /// Returns `true` if the vector contains no elements. 218 | pub fn is_empty(&self) -> bool { 219 | self.len == 0 220 | } 221 | 222 | /// Returns a immutable reference to the element at `index`, if available, or 223 | /// [`None`] if it is out of bounds. 224 | /// 225 | /// [`None`]: Option::None 226 | #[inline] 227 | pub fn get<'b: 'a, I>(&'b self, index: I) -> Option 228 | where 229 | I: ParallelSliceIndex, 230 | { 231 | index.get(self) 232 | } 233 | 234 | /// Returns a mutable reference to the element at `index`, if available, or 235 | /// [`None`] if it is out of bounds. 236 | /// 237 | /// [`None`]: Option::None 238 | #[inline] 239 | pub fn get_mut(&mut self, index: I) -> Option 240 | where 241 | I: ParallelSliceIndexMut, 242 | { 243 | index.get_mut(self) 244 | } 245 | 246 | /// Returns the first element of the slice, or `None` if it is empty. 247 | #[inline(always)] 248 | pub fn first(&self) -> Option> { 249 | self.get(0) 250 | } 251 | 252 | /// Returns the mutable pointer first element of the slice, or `None` if it is empty. 253 | #[inline(always)] 254 | pub fn first_mut(&mut self) -> Option> { 255 | self.get_mut(0) 256 | } 257 | 258 | /// Returns the last element of the slice, or `None` if it is empty. 259 | #[inline] 260 | pub fn last(&self) -> Option> { 261 | if self.len == 0 { 262 | None 263 | } else { 264 | unsafe { Some(self.get_unchecked(self.len - 1)) } 265 | } 266 | } 267 | 268 | /// Returns the mutable pointer last element of the slice, or `None` if it is empty. 269 | #[inline] 270 | pub fn last_mut(&mut self) -> Option> { 271 | if self.len == 0 { 272 | None 273 | } else { 274 | unsafe { Some(self.get_unchecked_mut(self.len - 1)) } 275 | } 276 | } 277 | 278 | /// Gets a immutable reference to the elements at `index`. 279 | /// 280 | /// # Panics 281 | /// This function will panic if `index >= self.len`. 282 | #[inline] 283 | pub fn index(&self, index: I) -> I::Output 284 | where 285 | I: ParallelSliceIndex, 286 | { 287 | index.index(self) 288 | } 289 | 290 | /// Gets a mutable reference to the elements at `index`. 291 | /// 292 | /// # Panics 293 | /// This function will panic if `index >= self.len`. 294 | #[inline] 295 | pub fn index_mut(&mut self, index: I) -> I::Output 296 | where 297 | I: ParallelSliceIndexMut, 298 | { 299 | index.index_mut(self) 300 | } 301 | 302 | /// Sets a value at an valid index in the slice. 303 | /// 304 | /// # Panics 305 | /// This function will panic if `index >= self.len`. 306 | #[inline] 307 | pub fn set(&mut self, index: usize, value: Param) { 308 | assert_in_bounds(index, self.len); 309 | unsafe { 310 | self.set_unchecked(index, value); 311 | } 312 | } 313 | 314 | /// Sets a value at an valid index in the slice without 315 | /// checking bounds. 316 | /// 317 | /// # Safety 318 | /// The set is only safe if `index >= self.len`. 319 | #[inline] 320 | pub unsafe fn set_unchecked(&mut self, index: usize, value: Param) { 321 | let ptr = Param::ptr_at(self.storage, index); 322 | Param::drop(ptr); 323 | Param::write(ptr, value); 324 | } 325 | 326 | /// Returns references to elements, without doing bounds checking. 327 | /// 328 | /// For a safe alternative see [`get`]. 329 | /// 330 | /// # Safety 331 | /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used. 332 | /// 333 | /// [`get`]: Self::get 334 | #[inline] 335 | pub unsafe fn get_unchecked(&self, index: usize) -> Param::Ref<'_> { 336 | Param::as_ref(Param::ptr_at(self.storage, index)) 337 | } 338 | 339 | /// Returns mutable references to elements, without doing bounds checking. 340 | /// 341 | /// For a safe alternative see [`get_mut`]. 342 | /// 343 | /// # Safety 344 | /// Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used. 345 | /// 346 | /// [`get_mut`]: Self::get_mut 347 | #[inline] 348 | pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> Param::RefMut<'_> { 349 | Param::as_mut(Param::ptr_at(self.storage, index)) 350 | } 351 | 352 | /// Sorts the slice with a comparator function. 353 | /// 354 | /// This function will allocate `sizeof(usize) * self.len` bytes as an intermediate sorting 355 | /// buffer. 356 | /// 357 | /// This defers to the `core` implemenation of [`slice::sort_by`], so any properties it 358 | /// has will also hold for this function. 359 | /// 360 | /// [`slice::sort_by`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by 361 | pub fn sort_by(&mut self, f: F) 362 | where 363 | F: Fn(Param::Ref<'a>, Param::Ref<'a>) -> Ordering, 364 | { 365 | let base = Param::as_ptr(self.storage); 366 | self.sort_via(|indices| { 367 | indices.sort_by(|a, b| unsafe { 368 | f( 369 | Param::as_ref(Param::add(base, *a)), 370 | Param::as_ref(Param::add(base, *b)), 371 | ) 372 | }); 373 | }); 374 | } 375 | 376 | /// Sorts the slice with a key extraction function. 377 | /// 378 | /// This function will allocate `sizeof(usize) * self.len` bytes as an intermediate sorting 379 | /// buffer. 380 | /// 381 | /// This defers to the `core` implemenation of [`slice::sort_by_key`], so any properties it 382 | /// has will also hold for this function. 383 | /// 384 | /// [`slice::sort_by`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_key 385 | pub fn sort_by_key(&mut self, f: F) 386 | where 387 | F: Fn(Param::Ref<'a>) -> K, 388 | K: Ord, 389 | { 390 | let base = Param::as_ptr(self.storage); 391 | self.sort_via(|indices| { 392 | indices.sort_by_key(|idx| unsafe { f(Param::as_ref(Param::add(base, *idx))) }); 393 | }); 394 | } 395 | 396 | /// Sorts the slice with a comparator function, but might not preserve the order of equal 397 | /// elements. 398 | /// 399 | /// This function will allocate `sizeof(usize) * self.len` bytes as an intermediate sorting 400 | /// buffer. 401 | /// 402 | /// This defers to the `core` implemenation of [`slice::sort_unstable_by`], so any properties it 403 | /// has will also hold for this function. 404 | /// 405 | /// [`slice::sort_unstable_by`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by 406 | pub fn sort_unstable_by(&mut self, f: F) 407 | where 408 | F: Fn(Param::Ref<'a>, Param::Ref<'a>) -> Ordering, 409 | { 410 | let base = Param::as_ptr(self.storage); 411 | self.sort_via(|indices| { 412 | indices.sort_unstable_by(|a, b| unsafe { 413 | f( 414 | Param::as_ref(Param::add(base, *a)), 415 | Param::as_ref(Param::add(base, *b)), 416 | ) 417 | }); 418 | }); 419 | } 420 | 421 | /// Sorts the slice with a key extraction function, but might not preserve the order of equal 422 | /// elements. 423 | /// 424 | /// This function will allocate `sizeof(usize) * self.len` bytes as an intermediate sorting 425 | /// buffer. 426 | /// 427 | /// This defers to the `core` implemenation of [`slice::sort_unstable_by_key`], so any properties 428 | /// it has will also hold this function. 429 | /// 430 | /// [`slice::sort_unstable_by_key`]: https://doc.rust-lang.org/std/primitive.slice.html#method.sort_unstable_by_key 431 | pub fn sort_unstable_by_key(&mut self, f: F) 432 | where 433 | F: Fn(Param::Ref<'a>) -> K, 434 | K: Ord, 435 | { 436 | let base = Param::as_ptr(self.storage); 437 | self.sort_via(|indices| { 438 | indices.sort_unstable_by_key(|idx| unsafe { f(Param::as_ref(Param::add(base, *idx))) }); 439 | }); 440 | } 441 | 442 | #[inline(always)] 443 | fn sort_via(&mut self, f: F) 444 | where 445 | F: FnOnce(&mut Vec), 446 | { 447 | if self.len < 2 { 448 | return; 449 | } 450 | 451 | let mut indices: Vec = (0..self.len).collect(); 452 | f(&mut indices); 453 | 454 | // SAFE: All of the indices used here are valid. 455 | unsafe { 456 | for src in 0..self.len { 457 | let dst = *indices.get_unchecked(src); 458 | if src == dst { 459 | continue; 460 | } 461 | self.swap_unchecked(src, dst); 462 | // TODO: Use swap_unchecked here when stablized. 463 | indices.swap(src, dst); 464 | } 465 | } 466 | } 467 | 468 | /// Returns a raw pointer to the slice’s buffer. 469 | /// 470 | /// The caller must ensure that the slice outlives the pointer this function returns, or else it will end up pointing 471 | /// to garbage. 472 | /// 473 | /// Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any 474 | /// pointers to it invalid. 475 | #[inline] 476 | pub fn as_mut_ptrs(&mut self) -> Param::Ptr { 477 | Param::as_ptr(self.storage) 478 | } 479 | 480 | /// Gets the individual slices for every sub-slice. 481 | #[inline] 482 | pub fn as_slices(&self) -> Param::Slices<'_> { 483 | unsafe { Param::as_slices(Param::as_ptr(self.storage), self.len) } 484 | } 485 | 486 | /// Gets mutable individual slices for every sub-slice. 487 | #[inline] 488 | pub fn as_slices_mut(&mut self) -> Param::SlicesMut<'_> { 489 | unsafe { Param::as_slices_mut(self.as_mut_ptrs(), self.len) } 490 | } 491 | 492 | /// Swaps two elements. 493 | /// 494 | /// # Arguments 495 | /// - `a` - The index of the first element 496 | /// - `b` - The index of the second element 497 | /// 498 | /// # Panics 499 | /// Panics if a or b are out of bounds. 500 | pub fn swap(&mut self, a: usize, b: usize) { 501 | assert_in_bounds(a, self.len); 502 | assert_in_bounds(b, self.len); 503 | unsafe { self.swap_unchecked(a, b) } 504 | } 505 | 506 | /// Swaps two elements in the slice, without doing bounds checking. 507 | /// 508 | /// For a safe alternative see [`swap`]. 509 | /// 510 | /// # Arguments 511 | /// - `a` - The index of the first element 512 | /// - `b` - The index of the second element 513 | /// 514 | /// # Safety 515 | /// Calling this method with an out-of-bounds index is undefined behavior. 516 | /// The caller has to ensure that `a < self.len()` and `b < self.len()`. 517 | /// 518 | /// [`swap`]: Self::swap 519 | #[inline] 520 | pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize) { 521 | let base = Param::as_ptr(self.storage); 522 | Param::swap(Param::add(base, a), Param::add(base, b)); 523 | } 524 | 525 | /// Reverses the order of elements in the [`ParallelSliceMut`], in place. 526 | /// 527 | /// This is a `O(n)` operation. 528 | pub fn reverse(&mut self) { 529 | if self.len == 0 { 530 | return; 531 | } 532 | Param::reverse(self.as_slices_mut()) 533 | } 534 | 535 | /// Swaps all elements in `self` with those in `other`. 536 | /// 537 | /// The length of other must be the same as `self`. 538 | /// 539 | /// # Panics 540 | /// 541 | /// This function will panic if the two slices have different lengths. 542 | pub fn swap_with(&mut self, other: &mut Self) { 543 | if self.len != other.len { 544 | panic!( 545 | "Attempted to use swap_with with slices of different lenghths: {} vs {}", 546 | self.len, other.len 547 | ) 548 | } 549 | unsafe { 550 | let mut a = self.as_mut_ptrs(); 551 | let mut b = other.as_mut_ptrs(); 552 | for _ in 0..self.len { 553 | Param::swap(a, b); 554 | a = Param::add(a, 1); 555 | b = Param::add(b, 1); 556 | } 557 | } 558 | } 559 | 560 | /// Returns an iterator over the [`ParallelSliceMut`]. 561 | pub fn iter(&self) -> Iter<'a, Param> { 562 | Iter { 563 | ptr: Param::as_ptr(self.storage), 564 | remaining: self.len, 565 | _marker: PhantomData, 566 | } 567 | } 568 | 569 | /// Returns an iterator that allows modifying each value. 570 | pub fn iter_mut(&mut self) -> IterMut<'a, Param> { 571 | IterMut { 572 | ptr: self.as_mut_ptrs(), 573 | remaining: self.len, 574 | _marker: PhantomData, 575 | } 576 | } 577 | 578 | /// Returns an iterator over the [`ParallelSliceMut`]. 579 | pub fn iters(&self) -> Param::Iters<'_> { 580 | unsafe { 581 | let ptr = Param::as_ptr(self.storage); 582 | let slices = Param::as_slices(ptr, self.len); 583 | Param::iters(slices) 584 | } 585 | } 586 | 587 | /// Gets individual iterators. 588 | pub fn iters_mut(&mut self) -> Param::ItersMut<'_> { 589 | unsafe { 590 | let ptr = Param::as_ptr(self.storage); 591 | let slices = Param::as_slices_mut(ptr, self.len); 592 | Param::iters_mut(slices) 593 | } 594 | } 595 | } 596 | 597 | impl<'a, Param: ParallelParam + Clone> ParallelSliceMut<'a, Param> { 598 | /// Fills self with elements by cloning value. 599 | #[inline(always)] 600 | pub fn fill(&mut self, value: Param) { 601 | self.fill_with(|| value.clone()); 602 | } 603 | } 604 | 605 | impl<'a, Param: ParallelParam> ParallelSliceMut<'a, Param> { 606 | /// Fills self with elements returned by calling a closure repeatedly. 607 | /// 608 | /// This method uses a closure to create new values. If you’d rather [`Clone`] 609 | /// a given value, use fill. If you want to use the [`Default`] trait to generate 610 | /// values, you can pass `Default::default` as the argument. 611 | pub fn fill_with Param>(&mut self, mut f: F) { 612 | unsafe { 613 | let base = self.as_mut_ptrs(); 614 | for idx in 0..self.len { 615 | Param::write(Param::add(base, idx), f()); 616 | } 617 | } 618 | } 619 | } 620 | 621 | impl<'s, 'r, Param> Hash for ParallelSliceMut<'s, Param> 622 | where 623 | Param: ParallelParam + 's, 624 | Param::Ref<'s>: Hash, 625 | 'r: 's, 626 | { 627 | fn hash(&self, hasher: &mut H) 628 | where 629 | H: Hasher, 630 | { 631 | self.len.hash(hasher); 632 | for item in self.iter() { 633 | item.hash(hasher); 634 | } 635 | } 636 | } 637 | 638 | pub trait ParallelSliceIndex { 639 | type Output; 640 | fn get(self, slice: &T) -> Option; 641 | fn index(self, slice: &T) -> Self::Output; 642 | } 643 | 644 | pub trait ParallelSliceIndexMut { 645 | type Output; 646 | fn get_mut(self, slice: &mut T) -> Option; 647 | fn index_mut(self, slice: &mut T) -> Self::Output; 648 | } 649 | 650 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for usize { 651 | type Output = Param::Ref<'s>; 652 | fn get(self, slice: &ParallelSlice<'s, Param>) -> Option { 653 | if self >= slice.len { 654 | return None; 655 | } 656 | 657 | unsafe { Some(Param::as_ref(Param::ptr_at(slice.storage, self))) } 658 | } 659 | 660 | fn index(self, slice: &ParallelSlice<'s, Param>) -> Self::Output { 661 | assert_in_bounds(self, slice.len); 662 | unsafe { Param::as_ref(Param::ptr_at(slice.storage, self)) } 663 | } 664 | } 665 | 666 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for usize { 667 | type Output = Param::Ref<'s>; 668 | fn get(self, slice: &ParallelSliceMut<'s, Param>) -> Option { 669 | if self >= slice.len { 670 | return None; 671 | } 672 | 673 | unsafe { Some(Param::as_ref(Param::ptr_at(slice.storage, self))) } 674 | } 675 | 676 | fn index(self, slice: &ParallelSliceMut<'s, Param>) -> Self::Output { 677 | assert_in_bounds(self, slice.len); 678 | unsafe { Param::as_ref(Param::ptr_at(slice.storage, self)) } 679 | } 680 | } 681 | 682 | impl<'s, Param: ParallelParam> ParallelSliceIndexMut> for usize { 683 | type Output = Param::RefMut<'s>; 684 | fn get_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Option { 685 | if self >= slice.len { 686 | return None; 687 | } 688 | 689 | unsafe { Some(Param::as_mut(Param::ptr_at(slice.storage, self))) } 690 | } 691 | 692 | fn index_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Self::Output { 693 | assert_in_bounds(self, slice.len); 694 | unsafe { Param::as_mut(Param::ptr_at(slice.storage, self)) } 695 | } 696 | } 697 | 698 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for Range { 699 | type Output = ParallelSlice<'s, Param>; 700 | fn get(self, slice: &ParallelSlice<'s, Param>) -> Option { 701 | if self.start >= slice.len || self.end > slice.len { 702 | return None; 703 | } 704 | 705 | unsafe { 706 | let ptr = Param::ptr_at(slice.storage, self.start); 707 | Some(ParallelSlice::from_raw_parts( 708 | Param::as_storage(ptr), 709 | self.end - self.start, 710 | )) 711 | } 712 | } 713 | 714 | fn index(self, slice: &ParallelSlice<'s, Param>) -> Self::Output { 715 | assert_in_bounds(self.start, slice.len); 716 | assert_in_bounds_inclusive(self.end, slice.len); 717 | unsafe { 718 | let ptr = Param::ptr_at(slice.storage, self.start); 719 | ParallelSlice::from_raw_parts(Param::as_storage(ptr), self.end - self.start) 720 | } 721 | } 722 | } 723 | 724 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for Range { 725 | type Output = ParallelSlice<'s, Param>; 726 | fn get(self, slice: &ParallelSliceMut<'s, Param>) -> Option { 727 | if self.start >= slice.len || self.end > slice.len { 728 | return None; 729 | } 730 | 731 | unsafe { 732 | let ptr = Param::ptr_at(slice.storage, self.start); 733 | Some(ParallelSlice::from_raw_parts( 734 | Param::as_storage(ptr), 735 | self.end - self.start, 736 | )) 737 | } 738 | } 739 | 740 | fn index(self, slice: &ParallelSliceMut<'s, Param>) -> Self::Output { 741 | assert_in_bounds(self.start, slice.len); 742 | assert_in_bounds_inclusive(self.end, slice.len); 743 | unsafe { 744 | let ptr = Param::ptr_at(slice.storage, self.start); 745 | ParallelSlice::from_raw_parts(Param::as_storage(ptr), self.end - self.start) 746 | } 747 | } 748 | } 749 | 750 | impl<'s, Param: ParallelParam> ParallelSliceIndexMut> for Range { 751 | type Output = ParallelSliceMut<'s, Param>; 752 | fn get_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Option { 753 | if self.start >= slice.len || self.end > slice.len { 754 | return None; 755 | } 756 | 757 | unsafe { 758 | let ptr = Param::ptr_at(slice.storage, self.start); 759 | Some(ParallelSliceMut::from_raw_parts( 760 | Param::as_storage(ptr), 761 | self.end - self.start, 762 | )) 763 | } 764 | } 765 | 766 | fn index_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Self::Output { 767 | assert_in_bounds(self.start, slice.len); 768 | assert_in_bounds_inclusive(self.end, slice.len); 769 | unsafe { 770 | let ptr = Param::ptr_at(slice.storage, self.start); 771 | ParallelSliceMut::from_raw_parts(Param::as_storage(ptr), self.end - self.start) 772 | } 773 | } 774 | } 775 | 776 | impl<'s, Param: ParallelParam> ParallelSliceIndex> 777 | for RangeInclusive 778 | { 779 | type Output = ParallelSlice<'s, Param>; 780 | fn get(self, slice: &ParallelSlice<'s, Param>) -> Option { 781 | let range = Range { 782 | start: *self.start(), 783 | end: *self.end() + 1, 784 | }; 785 | range.get(slice) 786 | } 787 | 788 | fn index(self, slice: &ParallelSlice<'s, Param>) -> Self::Output { 789 | let range = Range { 790 | start: *self.start(), 791 | end: *self.end() + 1, 792 | }; 793 | range.index(slice) 794 | } 795 | } 796 | 797 | impl<'s, Param: ParallelParam> ParallelSliceIndex> 798 | for RangeInclusive 799 | { 800 | type Output = ParallelSlice<'s, Param>; 801 | fn get(self, slice: &ParallelSliceMut<'s, Param>) -> Option { 802 | let range = Range { 803 | start: *self.start(), 804 | end: *self.end() + 1, 805 | }; 806 | range.get(slice) 807 | } 808 | 809 | fn index(self, slice: &ParallelSliceMut<'s, Param>) -> Self::Output { 810 | let range = Range { 811 | start: *self.start(), 812 | end: *self.end() + 1, 813 | }; 814 | range.index(slice) 815 | } 816 | } 817 | 818 | impl<'s, Param: ParallelParam> ParallelSliceIndexMut> 819 | for RangeInclusive 820 | { 821 | type Output = ParallelSliceMut<'s, Param>; 822 | fn get_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Option { 823 | let range = Range { 824 | start: *self.start(), 825 | end: *self.end() + 1, 826 | }; 827 | 828 | range.get_mut(slice) 829 | } 830 | 831 | fn index_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Self::Output { 832 | let range = Range { 833 | start: *self.start(), 834 | end: *self.end() + 1, 835 | }; 836 | range.index_mut(slice) 837 | } 838 | } 839 | 840 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for RangeTo { 841 | type Output = ParallelSlice<'s, Param>; 842 | fn get(self, slice: &ParallelSlice<'s, Param>) -> Option { 843 | Range { 844 | start: 0, 845 | end: self.end, 846 | } 847 | .get(slice) 848 | } 849 | 850 | fn index(self, slice: &ParallelSlice<'s, Param>) -> Self::Output { 851 | Range { 852 | start: 0, 853 | end: self.end, 854 | } 855 | .index(slice) 856 | } 857 | } 858 | 859 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for RangeTo { 860 | type Output = ParallelSlice<'s, Param>; 861 | fn get(self, slice: &ParallelSliceMut<'s, Param>) -> Option { 862 | Range { 863 | start: 0, 864 | end: self.end, 865 | } 866 | .get(slice) 867 | } 868 | 869 | fn index(self, slice: &ParallelSliceMut<'s, Param>) -> Self::Output { 870 | Range { 871 | start: 0, 872 | end: self.end, 873 | } 874 | .index(slice) 875 | } 876 | } 877 | 878 | impl<'s, Param: ParallelParam> ParallelSliceIndexMut> 879 | for RangeTo 880 | { 881 | type Output = ParallelSliceMut<'s, Param>; 882 | fn get_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Option { 883 | Range { 884 | start: 0, 885 | end: self.end, 886 | } 887 | .get_mut(slice) 888 | } 889 | 890 | fn index_mut<'a>(self, slice: &mut ParallelSliceMut<'s, Param>) -> Self::Output { 891 | Range { 892 | start: 0, 893 | end: self.end, 894 | } 895 | .index_mut(slice) 896 | } 897 | } 898 | 899 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for RangeFrom { 900 | type Output = ParallelSlice<'s, Param>; 901 | fn get(self, slice: &ParallelSlice<'s, Param>) -> Option { 902 | Range { 903 | start: self.start, 904 | end: slice.len, 905 | } 906 | .get(slice) 907 | } 908 | 909 | fn index(self, slice: &ParallelSlice<'s, Param>) -> Self::Output { 910 | Range { 911 | start: self.start, 912 | end: slice.len, 913 | } 914 | .index(slice) 915 | } 916 | } 917 | 918 | impl<'s, Param: ParallelParam> ParallelSliceIndex> 919 | for RangeFrom 920 | { 921 | type Output = ParallelSlice<'s, Param>; 922 | fn get(self, slice: &ParallelSliceMut<'s, Param>) -> Option { 923 | Range { 924 | start: self.start, 925 | end: slice.len, 926 | } 927 | .get(slice) 928 | } 929 | 930 | fn index(self, slice: &ParallelSliceMut<'s, Param>) -> Self::Output { 931 | Range { 932 | start: self.start, 933 | end: slice.len, 934 | } 935 | .index(slice) 936 | } 937 | } 938 | 939 | impl<'s, Param: ParallelParam> ParallelSliceIndexMut> 940 | for RangeFrom 941 | { 942 | type Output = ParallelSliceMut<'s, Param>; 943 | fn get_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Option { 944 | Range { 945 | start: self.start, 946 | end: slice.len, 947 | } 948 | .get_mut(slice) 949 | } 950 | 951 | fn index_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Self::Output { 952 | Range { 953 | start: self.start, 954 | end: slice.len, 955 | } 956 | .index_mut(slice) 957 | } 958 | } 959 | 960 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for RangeFull { 961 | type Output = ParallelSlice<'s, Param>; 962 | fn get(self, slice: &ParallelSlice<'s, Param>) -> Option { 963 | Range { 964 | start: 0, 965 | end: slice.len, 966 | } 967 | .get(slice) 968 | } 969 | 970 | fn index(self, slice: &ParallelSlice<'s, Param>) -> Self::Output { 971 | Range { 972 | start: 0, 973 | end: slice.len, 974 | } 975 | .index(slice) 976 | } 977 | } 978 | 979 | impl<'s, Param: ParallelParam> ParallelSliceIndex> for RangeFull { 980 | type Output = ParallelSlice<'s, Param>; 981 | fn get(self, slice: &ParallelSliceMut<'s, Param>) -> Option { 982 | Range { 983 | start: 0, 984 | end: slice.len, 985 | } 986 | .get(slice) 987 | } 988 | 989 | fn index(self, slice: &ParallelSliceMut<'s, Param>) -> Self::Output { 990 | Range { 991 | start: 0, 992 | end: slice.len, 993 | } 994 | .index(slice) 995 | } 996 | } 997 | 998 | impl<'s, Param: ParallelParam> ParallelSliceIndexMut> for RangeFull { 999 | type Output = ParallelSliceMut<'s, Param>; 1000 | fn get_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Option { 1001 | Range { 1002 | start: 0, 1003 | end: slice.len, 1004 | } 1005 | .get_mut(slice) 1006 | } 1007 | 1008 | fn index_mut(self, slice: &mut ParallelSliceMut<'s, Param>) -> Self::Output { 1009 | Range { 1010 | start: 0, 1011 | end: slice.len, 1012 | } 1013 | .index_mut(slice) 1014 | } 1015 | } 1016 | -------------------------------------------------------------------------------- /src/vec.rs: -------------------------------------------------------------------------------- 1 | use crate::{assert_in_bounds, iter::IntoIter, out_of_bounds, ParallelParam, ParallelSliceMut}; 2 | use alloc::vec::Vec; 3 | use core::{ 4 | fmt::{Debug, Formatter}, 5 | hash::{Hash, Hasher}, 6 | ops::{Deref, DerefMut}, 7 | }; 8 | 9 | /// A contiguously growable heterogenous array type. 10 | /// 11 | /// This type stores the values [structure of arrays] layout. This layout 12 | /// may improve cache utilizatoin in specific use cases. 13 | /// 14 | /// Unlike a struct of `Vec`s, this type allocates memory for the all individual 15 | /// fields simultaneously. This may minimize memory fragmentation and decrease 16 | /// allocation pressure. It also only stores one length and capacity instead 17 | /// of duplicating the values across multiple `Vec` fields. 18 | /// 19 | /// [structures of arrays]: https://en.wikipedia.org/wiki/AoS_and_SoA#Structure_of_arrays 20 | #[repr(C)] 21 | pub struct ParallelVec { 22 | pub(crate) len: usize, 23 | pub(crate) storage: Param::Storage, 24 | pub(crate) capacity: usize, 25 | } 26 | 27 | impl ParallelVec { 28 | /// Constructs a new, empty `ParallelVec`. 29 | /// 30 | /// The vector will not allocate until elements are pushed onto it. 31 | pub fn new() -> Self { 32 | Self::with_capacity(0) 33 | } 34 | 35 | /// Constructs a new, empty [`ParallelVec`] with the specified capacity. 36 | /// 37 | /// The vector will be able to hold exactly capacity elements without reallocating. 38 | /// If capacity is 0, the vector will not allocate. 39 | /// 40 | /// It is important to note that although the returned vector has the capacity specified, 41 | /// the vector will have a zero length. 42 | pub fn with_capacity(capacity: usize) -> Self { 43 | unsafe { 44 | Self { 45 | len: 0, 46 | capacity, 47 | storage: if capacity == 0 { 48 | Param::dangling() 49 | } else { 50 | Param::alloc(capacity) 51 | }, 52 | } 53 | } 54 | } 55 | 56 | /// Returns the number of elements the vector can hold without reallocating. 57 | pub fn capacity(&self) -> usize { 58 | self.capacity 59 | } 60 | 61 | /// Clears the vector, removing all values. 62 | /// 63 | /// Note that this method has no effect on the allocated capacity of the vector. 64 | pub fn clear(&mut self) { 65 | self.truncate(0); 66 | } 67 | 68 | /// Shortens the vector, keeping the first `len` elements and dropping the rest. 69 | /// 70 | /// If `len` is greater than the vector’s current length, this has no effect. 71 | /// 72 | /// Note that this method has no effect on the allocated capacity of the vector. 73 | pub fn truncate(&mut self, len: usize) { 74 | if self.len <= len { 75 | return; 76 | } 77 | unsafe { 78 | self.drop_range(len, self.len); 79 | self.len = len; 80 | } 81 | } 82 | 83 | pub(crate) unsafe fn drop_range(&mut self, start: usize, end: usize) { 84 | let base = Param::as_ptr(self.storage); 85 | for idx in start..end { 86 | Param::drop(Param::add(base, idx)); 87 | } 88 | } 89 | 90 | /// Shrinks the capacity of the vector with a lower bound. 91 | /// 92 | /// The capacity will remain at least as large as both the length and 93 | /// the supplied value. 94 | /// 95 | /// If the current capacity is less than the lower limit, this is a no-op. 96 | pub fn shrink_to(&mut self, min_capacity: usize) { 97 | if min_capacity > self.capacity { 98 | return; 99 | } 100 | let capacity = core::cmp::max(self.len, min_capacity); 101 | unsafe { 102 | self.storage = Param::realloc(self.storage, self.capacity, capacity); 103 | } 104 | self.capacity = capacity; 105 | } 106 | 107 | /// Shrinks the capacity of the vector as much as possible. 108 | /// 109 | /// It will drop down as close as possible to the length but the allocator may 110 | /// still inform the vector that there is space for a few more elements. 111 | pub fn shrink_to_fit(&mut self) { 112 | self.shrink_to(self.len); 113 | } 114 | 115 | /// Moves all the elements of `other` into `Self`, leaving `other` empty. 116 | pub fn append(&mut self, other: &mut ParallelVec) { 117 | self.reserve(other.len); 118 | unsafe { 119 | let src = Param::as_ptr(other.storage); 120 | let dst = Param::ptr_at(self.storage, self.len); 121 | Param::copy_to_nonoverlapping(src, dst, other.len); 122 | self.len += other.len; 123 | // No need to drop from the other vec, data has been moved to 124 | // the current one. Just set the length here. 125 | other.len = 0; 126 | } 127 | } 128 | 129 | /// Appends an element to the back of a collection. 130 | pub fn push(&mut self, value: Param) { 131 | unsafe { 132 | self.reserve(1); 133 | let ptr = Param::ptr_at(self.storage, self.len); 134 | Param::write(ptr, value); 135 | self.len += 1; 136 | } 137 | } 138 | 139 | /// Removes the last element from the vector and returns it, 140 | /// or [`None`] if it is empty. 141 | /// 142 | /// [`None`]: Option::None 143 | pub fn pop(&mut self) -> Option { 144 | if self.len == 0 { 145 | None 146 | } else { 147 | unsafe { 148 | let ptr = Param::ptr_at(self.storage, self.len - 1); 149 | let value = Param::read(ptr); 150 | self.len -= 1; 151 | Some(value) 152 | } 153 | } 154 | } 155 | 156 | /// Removes an element from the vector and returns it. 157 | /// 158 | /// The removed element is replaced by the last element of the vector. 159 | /// 160 | /// This does not preserve ordering, but is `O(1)`. If you need to 161 | /// preserve the element order, use [`remove`] instead. 162 | /// 163 | /// [`remove`]: Self::remove 164 | pub fn swap_remove(&mut self, index: usize) -> Param { 165 | assert_in_bounds(index, self.len); 166 | 167 | unsafe { 168 | let target_ptr = Param::ptr_at(self.storage, index); 169 | let value = Param::read(target_ptr); 170 | self.len -= 1; 171 | 172 | if self.len != index { 173 | let end = Param::ptr_at(self.storage, self.len); 174 | Param::copy_to_nonoverlapping(end, target_ptr, 1); 175 | } 176 | 177 | value 178 | } 179 | } 180 | 181 | /// Inserts a value at `index`. Moves all of the elements above 182 | /// `index` up one index. This is a `O(N)` operation. 183 | /// 184 | /// # Panics 185 | /// This function will panic if `index` is greater than or equal to 186 | /// `len()`. 187 | pub fn insert(&mut self, index: usize, value: Param) { 188 | if index > self.len { 189 | out_of_bounds(index, self.len); 190 | } 191 | unsafe { 192 | // TODO: (Performance) In the case where we do grow, this can result in redundant copying. 193 | self.reserve(1); 194 | let ptr = Param::ptr_at(self.storage, index); 195 | Param::copy_to(ptr, Param::add(ptr, 1), self.len - index); 196 | Param::write(ptr, value); 197 | self.len += 1; 198 | } 199 | } 200 | 201 | /// Removes a value at `index`. Moves all of the elements above 202 | /// `index` down one index. This is a `O(N)` operation. 203 | /// 204 | /// Returns `None` if `index` is is greater than or equal to `len()`. 205 | pub fn remove(&mut self, index: usize) -> Option { 206 | if index >= self.len { 207 | return None; 208 | } 209 | unsafe { 210 | let ptr = Param::ptr_at(self.storage, index); 211 | let value = Param::read(ptr); 212 | Param::copy_to(Param::add(ptr, 1), ptr, self.len - index - 1); 213 | self.len -= 1; 214 | Some(value) 215 | } 216 | } 217 | 218 | /// Reserves capacity for at least `additional` more elements to be inserted in the 219 | /// given [`ParallelVec`]. The collection may reserve more space to avoid frequent 220 | /// reallocations. After calling reserve, capacity will be greater than or 221 | /// equal to `self.len() + additional`. Does nothing if capacity is already 222 | /// sufficient. 223 | pub fn reserve(&mut self, additional: usize) { 224 | unsafe { 225 | let new_capacity = self.len.checked_add(additional).expect("capacity overflow"); 226 | if new_capacity > self.capacity { 227 | let capacity = new_capacity.next_power_of_two().max(4); 228 | debug_assert!(capacity > self.len, "capacity overflow"); 229 | self.storage = Param::realloc(self.storage, self.capacity, capacity); 230 | self.capacity = capacity; 231 | } 232 | } 233 | } 234 | } 235 | 236 | impl ParallelVec { 237 | /// Creates a [`ParallelVec`] by repeating `self` `n` times. 238 | pub fn repeat(&self, n: usize) -> ParallelVec { 239 | let mut new = ParallelVec::with_capacity(n * self.len); 240 | let mut dst = Param::as_ptr(new.storage); 241 | new.len = n * self.len; 242 | unsafe { 243 | let base = Param::as_ptr(self.storage); 244 | for _ in 0..n { 245 | for idx in 0..self.len { 246 | let value = Param::read(Param::add(base, idx)); 247 | Param::write(dst, value); 248 | dst = Param::add(dst, 1); 249 | } 250 | } 251 | } 252 | new 253 | } 254 | } 255 | 256 | impl Drop for ParallelVec { 257 | fn drop(&mut self) { 258 | let end = self.len; 259 | // Set len to 0 first in case one of the Drop impls panics 260 | self.len = 0; 261 | unsafe { 262 | self.drop_range(0, end); 263 | Param::dealloc(self.storage, self.capacity); 264 | } 265 | } 266 | } 267 | 268 | impl From> for ParallelVec { 269 | fn from(value: Vec) -> Self { 270 | Self::from_iter(value.into_iter()) 271 | } 272 | } 273 | 274 | impl<'a, Param: ParallelParam> PartialEq for ParallelVec 275 | where 276 | Param: 'a, 277 | Param::Ref<'a>: PartialEq, 278 | { 279 | fn eq(&self, other: &Self) -> bool { 280 | if self.len != other.len { 281 | return false; 282 | } 283 | if self.storage == other.storage { 284 | // Pointing to the same storage. Shortcut out. 285 | return true; 286 | } 287 | self.iter().zip(other.iter()).all(|(a, b)| a.eq(&b)) 288 | } 289 | } 290 | 291 | impl<'a, Param: ParallelParam> Eq for ParallelVec 292 | where 293 | Param: 'a, 294 | Param::Ref<'a>: Eq, 295 | { 296 | } 297 | 298 | impl<'a, Param: ParallelParam> Debug for ParallelVec 299 | where 300 | Param: 'a, 301 | Param::Ref<'a>: Debug, 302 | { 303 | fn fmt(&self, fmt: &mut Formatter<'_>) -> core::fmt::Result { 304 | fmt.write_str("ParallelVec")?; 305 | fmt.debug_list().entries(self.iter()).finish() 306 | } 307 | } 308 | 309 | impl<'a, Param: ParallelParam> Hash for ParallelVec 310 | where 311 | Param: 'a, 312 | Param::Ref<'a>: Hash, 313 | { 314 | fn hash(&self, hasher: &mut H) 315 | where 316 | H: Hasher, 317 | { 318 | self.deref().hash(hasher); 319 | } 320 | } 321 | 322 | impl FromIterator for ParallelVec { 323 | fn from_iter(iter: T) -> Self 324 | where 325 | T: IntoIterator, 326 | { 327 | let iter = iter.into_iter(); 328 | let (min, _) = iter.size_hint(); 329 | let mut parallel_vec = Self::with_capacity(min); 330 | for item in iter { 331 | parallel_vec.push(item); 332 | } 333 | parallel_vec 334 | } 335 | } 336 | 337 | impl IntoIterator for ParallelVec { 338 | type Item = Param; 339 | type IntoIter = IntoIter; 340 | fn into_iter(self) -> Self::IntoIter { 341 | let iter = IntoIter { 342 | storage: self.storage, 343 | capacity: self.capacity, 344 | len: self.len, 345 | idx: 0, 346 | }; 347 | core::mem::forget(self); 348 | iter 349 | } 350 | } 351 | 352 | impl Extend for ParallelVec { 353 | fn extend(&mut self, iter: T) 354 | where 355 | T: IntoIterator, 356 | { 357 | let iterator = iter.into_iter(); 358 | let (min, _) = iterator.size_hint(); 359 | self.reserve(min); 360 | for param in iterator { 361 | self.push(param); 362 | } 363 | } 364 | } 365 | 366 | impl Clone for ParallelVec { 367 | fn clone(&self) -> Self { 368 | let mut clone = Self::with_capacity(self.len); 369 | unsafe { 370 | let base = Param::as_ptr(self.storage); 371 | for idx in 0..self.len { 372 | let value = Param::read(Param::add(base, idx)); 373 | clone.push(value.clone()); 374 | } 375 | } 376 | clone 377 | } 378 | } 379 | 380 | impl Default for ParallelVec { 381 | fn default() -> Self { 382 | Self::new() 383 | } 384 | } 385 | 386 | impl Deref for ParallelVec { 387 | type Target = ParallelSliceMut<'static, Param>; 388 | fn deref(&self) -> &Self::Target { 389 | // SAFE: Both ParallelVec and ParallelSliceMut have the same 390 | // layout in memory due to #[repr(C)] 391 | unsafe { 392 | let ptr: *const Self = self; 393 | &*(ptr.cast::()) 394 | } 395 | } 396 | } 397 | 398 | impl DerefMut for ParallelVec { 399 | fn deref_mut(&mut self) -> &mut Self::Target { 400 | // SAFE: Both ParallelVec and ParallelSliceMut have the same 401 | // layout in memory due to #[repr(C)] 402 | unsafe { 403 | let ptr: *mut Self = self; 404 | &mut *(ptr.cast::()) 405 | } 406 | } 407 | } 408 | 409 | #[cfg(test)] 410 | mod tests { 411 | use super::ParallelVec; 412 | use std::convert::From; 413 | use std::rc::Rc; 414 | use std::vec::Vec; 415 | 416 | #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] 417 | struct ZST; 418 | 419 | #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] 420 | struct ZST2; 421 | 422 | #[test] 423 | fn layouts_do_not_overlap() { 424 | // Trying with both (small, large) and (large, small) to ensure nothing bleeds into anything else. 425 | // This verifies we correctly chunk the slices from the larger allocations. 426 | let mut vec_ab = ParallelVec::new(); 427 | let mut vec_ba = ParallelVec::new(); 428 | 429 | fn ab(v: usize) -> (u8, f64) { 430 | (v as u8, 200.0 + ((v as f64) / 200.0)) 431 | } 432 | 433 | fn ba(v: usize) -> (f64, u8) { 434 | (15.0 + ((v as f64) / 16.0), (200 - v) as u8) 435 | } 436 | 437 | // Combined with the tests inside, also verifies that we are copying the data on grow correctly. 438 | for i in 0..100 { 439 | vec_ab.push(ab(i)); 440 | let (a, b) = vec_ab.as_slices(); 441 | assert_eq!(i + 1, a.len()); 442 | assert_eq!(i + 1, b.len()); 443 | assert_eq!(ab(0).0, a[0]); 444 | assert_eq!(ab(0).1, b[0]); 445 | assert_eq!(ab(i).0, a[i]); 446 | assert_eq!(ab(i).1, b[i]); 447 | 448 | vec_ba.push(ba(i)); 449 | let (b, a) = vec_ba.as_slices(); 450 | assert_eq!(i + 1, a.len()); 451 | assert_eq!(i + 1, b.len()); 452 | assert_eq!(ba(0).0, b[0]); 453 | assert_eq!(ba(0).1, a[0]); 454 | assert_eq!(ba(i).0, b[i]); 455 | assert_eq!(ba(i).1, a[i]); 456 | } 457 | } 458 | 459 | #[test] 460 | fn test_new() { 461 | let src: ParallelVec<(i32, i32, u64)> = ParallelVec::new(); 462 | assert_eq!(src.len(), 0); 463 | assert_eq!(src.capacity(), 0); 464 | assert!(src.is_empty()); 465 | } 466 | 467 | #[test] 468 | fn test_default() { 469 | let src: ParallelVec<(i32, i32, u64)> = Default::default(); 470 | assert_eq!(src.len(), 0); 471 | assert_eq!(src.capacity(), 0); 472 | assert!(src.is_empty()); 473 | } 474 | 475 | #[test] 476 | fn test_with_capacity() { 477 | let src: ParallelVec<(i32, i32, u64)> = ParallelVec::with_capacity(1000); 478 | assert_eq!(src.len(), 0); 479 | assert!(src.capacity() >= 1000); 480 | assert!(src.is_empty()); 481 | } 482 | 483 | #[test] 484 | fn test_reserve() { 485 | let mut src = ParallelVec::new(); 486 | src.push((0, 0, 0, 0)); 487 | assert_eq!(src.len(), 1); 488 | assert!(src.capacity() >= 1); 489 | src.reserve(10); 490 | assert_eq!(src.len(), 1); 491 | assert!(src.capacity() >= 10); 492 | src.reserve(100); 493 | assert_eq!(src.len(), 1); 494 | assert!(src.capacity() >= 100); 495 | src.reserve(1000); 496 | assert_eq!(src.len(), 1); 497 | assert!(src.capacity() >= 1000); 498 | src.reserve(100000); 499 | assert_eq!(src.len(), 1); 500 | assert!(src.capacity() >= 10000); 501 | } 502 | 503 | #[test] 504 | fn test_clone() { 505 | let mut src = ParallelVec::new(); 506 | src.push((1.0, 2.0)); 507 | src.push((3.0, 4.0)); 508 | 509 | let dst = src.clone(); 510 | assert_eq!(dst.len(), 2); 511 | assert_eq!(dst.index(0), (&1.0, &2.0)); 512 | assert_eq!(dst.index(1), (&3.0, &4.0)); 513 | } 514 | 515 | #[test] 516 | fn test_works_with_zsts() { 517 | let mut src = ParallelVec::new(); 518 | src.push((1, ZST, 20u64, ZST2)); 519 | src.push((1, ZST, 21u64, ZST2)); 520 | src.push((1, ZST, 22u64, ZST2)); 521 | src.push((1, ZST, 23u64, ZST2)); 522 | assert_eq!(src.index(0), (&1, &ZST, &20u64, &ZST2)); 523 | assert_eq!(src.index(1), (&1, &ZST, &21u64, &ZST2)); 524 | assert_eq!(src.index(2), (&1, &ZST, &22u64, &ZST2)); 525 | assert_eq!(src.index(3), (&1, &ZST, &23u64, &ZST2)); 526 | assert_eq!(src.len(), 4); 527 | } 528 | 529 | #[test] 530 | fn test_push() { 531 | let mut src = ParallelVec::new(); 532 | src.push((1, 2)); 533 | assert_eq!(src.index(0), (&1, &2)); 534 | assert_eq!(src.len(), 1); 535 | } 536 | 537 | #[test] 538 | fn test_pop() { 539 | let mut src = ParallelVec::new(); 540 | src.push((1, 2)); 541 | src.push((3, 4)); 542 | src.push((5, 6)); 543 | src.push((7, 8)); 544 | assert_eq!(src.len(), 4); 545 | let value = src.pop(); 546 | assert_eq!(value, Some((7, 8))); 547 | assert_eq!(src.len(), 3); 548 | let value = src.pop(); 549 | assert_eq!(value, Some((5, 6))); 550 | assert_eq!(src.len(), 2); 551 | let value = src.pop(); 552 | assert_eq!(value, Some((3, 4))); 553 | assert_eq!(src.len(), 1); 554 | let value = src.pop(); 555 | assert_eq!(value, Some((1, 2))); 556 | assert_eq!(src.len(), 0); 557 | let value = src.pop(); 558 | assert_eq!(value, None); 559 | assert_eq!(src.len(), 0); 560 | let value = src.pop(); 561 | assert_eq!(value, None); 562 | assert_eq!(src.len(), 0); 563 | } 564 | 565 | #[test] 566 | fn test_insert() { 567 | let mut src = ParallelVec::new(); 568 | src.insert(0, (1, 2)); 569 | src.insert(0, (3, 4)); 570 | src.insert(1, (4, 5)); 571 | assert_eq!(src.index(0), (&3, &4)); 572 | assert_eq!(src.index(1), (&4, &5)); 573 | assert_eq!(src.index(2), (&1, &2)); 574 | } 575 | 576 | #[test] 577 | #[should_panic] 578 | fn test_insert_panics() { 579 | let mut src = ParallelVec::new(); 580 | src.insert(0, (1, 2)); 581 | src.insert(0, (3, 4)); 582 | src.insert(1, (4, 5)); 583 | src.insert(20, (4, 5)); 584 | } 585 | 586 | #[test] 587 | fn test_remove() { 588 | let mut src = ParallelVec::new(); 589 | src.push((1, 2)); 590 | src.push((3, 4)); 591 | assert_eq!(src.remove(1), Some((3, 4))); 592 | assert_eq!(src.remove(0), Some((1, 2))); 593 | assert_eq!(src.len(), 0); 594 | assert_eq!(src.remove(5), None); 595 | } 596 | 597 | #[test] 598 | fn test_iter() { 599 | let mut src = ParallelVec::new(); 600 | src.push((1, 2)); 601 | src.push((3, 4)); 602 | src.push((5, 6)); 603 | src.push((7, 8)); 604 | let mut iter = src.iter(); 605 | assert_eq!(iter.next(), Some((&1, &2))); 606 | assert_eq!(iter.next(), Some((&3, &4))); 607 | assert_eq!(iter.next(), Some((&5, &6))); 608 | assert_eq!(iter.next(), Some((&7, &8))); 609 | assert_eq!(iter.next(), None); 610 | assert_eq!(iter.next(), None); 611 | assert_eq!(iter.next(), None); 612 | // Shouldn't have removed any of them 613 | assert_eq!(src.len(), 4); 614 | } 615 | 616 | #[test] 617 | fn test_iters() { 618 | let mut src = ParallelVec::new(); 619 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 620 | let (mut a, mut b) = src.iters(); 621 | assert_eq!(a.next(), Some(&1)); 622 | assert_eq!(a.next(), Some(&3)); 623 | assert_eq!(a.next(), Some(&5)); 624 | assert_eq!(a.next(), Some(&7)); 625 | assert_eq!(a.next(), Some(&9)); 626 | assert_eq!(a.next(), Some(&11)); 627 | assert_eq!(a.next(), None); 628 | assert_eq!(a.next(), None); 629 | assert_eq!(b.next(), Some(&2)); 630 | assert_eq!(b.next(), Some(&4)); 631 | assert_eq!(b.next(), Some(&6)); 632 | assert_eq!(b.next(), Some(&8)); 633 | assert_eq!(b.next(), Some(&10)); 634 | assert_eq!(b.next(), Some(&12)); 635 | assert_eq!(b.next(), None); 636 | assert_eq!(b.next(), None); 637 | } 638 | 639 | #[test] 640 | fn test_iter_mut() { 641 | let mut src = ParallelVec::new(); 642 | src.push((1, 2)); 643 | src.push((3, 4)); 644 | src.push((5, 6)); 645 | src.push((7, 8)); 646 | let mut iter = src.iter_mut(); 647 | assert_eq!(iter.next(), Some((&mut 1, &mut 2))); 648 | assert_eq!(iter.next(), Some((&mut 3, &mut 4))); 649 | assert_eq!(iter.next(), Some((&mut 5, &mut 6))); 650 | assert_eq!(iter.next(), Some((&mut 7, &mut 8))); 651 | assert_eq!(iter.next(), None); 652 | assert_eq!(iter.next(), None); 653 | assert_eq!(iter.next(), None); 654 | // Shouldn't have removed any of them 655 | assert_eq!(src.len(), 4); 656 | } 657 | 658 | #[test] 659 | fn test_shrink_to() { 660 | let mut src = ParallelVec::new(); 661 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 662 | src.reserve(1000); 663 | assert_eq!(src.len(), 4); 664 | assert!(src.capacity() >= 1000); 665 | src.shrink_to(200); 666 | assert_eq!(src.len(), 4); 667 | assert!(src.capacity() <= 200); 668 | src.shrink_to(100); 669 | assert_eq!(src.len(), 4); 670 | assert!(src.capacity() <= 100); 671 | src.shrink_to(10); 672 | assert_eq!(src.len(), 4); 673 | assert!(src.capacity() <= 10); 674 | src.shrink_to(1); 675 | assert_eq!(src.len(), 4); 676 | assert!(src.capacity() >= 4); 677 | let (a, b) = src.as_slices(); 678 | assert_eq!(a, &[1, 3, 5, 7]); 679 | assert_eq!(b, &[2, 4, 6, 8]); 680 | } 681 | 682 | #[test] 683 | fn test_shrink_to_fit() { 684 | let mut src = ParallelVec::new(); 685 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 686 | src.reserve(1000); 687 | assert_eq!(src.len(), 4); 688 | assert!(src.capacity() >= 1000); 689 | src.shrink_to_fit(); 690 | assert_eq!(src.len(), 4); 691 | assert!(src.capacity() <= src.len()); 692 | let (a, b) = src.as_slices(); 693 | assert_eq!(a, &[1, 3, 5, 7]); 694 | assert_eq!(b, &[2, 4, 6, 8]); 695 | } 696 | 697 | #[test] 698 | fn test_truncate() { 699 | let mut src = ParallelVec::new(); 700 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 701 | { 702 | let (a, b) = src.as_slices(); 703 | assert_eq!(a, &[1, 3, 5, 7]); 704 | assert_eq!(b, &[2, 4, 6, 8]); 705 | } 706 | src.truncate(2); 707 | { 708 | let (a, b) = src.as_slices(); 709 | assert_eq!(a, &[1, 3]); 710 | assert_eq!(b, &[2, 4]); 711 | assert_eq!(src.len(), 2); 712 | assert!(src.capacity() >= 4); 713 | } 714 | } 715 | 716 | #[test] 717 | fn test_truncate_drops() { 718 | let rc = Rc::new(0); 719 | let mut src = ParallelVec::new(); 720 | src.extend(vec![ 721 | (rc.clone(), rc.clone()), 722 | (rc.clone(), rc.clone()), 723 | (rc.clone(), rc.clone()), 724 | (rc.clone(), rc.clone()), 725 | ]); 726 | assert_eq!(Rc::strong_count(&rc), 9); 727 | src.truncate(1); 728 | assert_eq!(Rc::strong_count(&rc), 3); 729 | } 730 | 731 | #[test] 732 | fn test_reverse() { 733 | let mut src = ParallelVec::new(); 734 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 735 | { 736 | let (a, b) = src.as_slices(); 737 | assert_eq!(a, &[1, 3, 5, 7]); 738 | assert_eq!(b, &[2, 4, 6, 8]); 739 | } 740 | src.reverse(); 741 | { 742 | let (a, b) = src.as_slices(); 743 | assert_eq!(a, &[7, 5, 3, 1]); 744 | assert_eq!(b, &[8, 6, 4, 2]); 745 | } 746 | } 747 | 748 | #[test] 749 | fn test_clear() { 750 | let mut src = ParallelVec::new(); 751 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 752 | src.clear(); 753 | assert_eq!(src.len(), 0); 754 | assert!(src.capacity() > 0); 755 | let (a, b) = src.as_slices(); 756 | assert_eq!(a, &[]); 757 | assert_eq!(b, &[]); 758 | } 759 | 760 | #[test] 761 | fn test_repeat() { 762 | let mut src = ParallelVec::new(); 763 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 764 | let repeated = src.repeat(3); 765 | let (a, b) = repeated.as_slices(); 766 | assert_eq!(a, &[1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]); 767 | assert_eq!(b, &[2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8]); 768 | let (a, b) = src.as_slices(); 769 | assert_eq!(src.len(), 4); 770 | assert_eq!(a, &[1, 3, 5, 7]); 771 | assert_eq!(b, &[2, 4, 6, 8]); 772 | assert_eq!(repeated.len(), 12); 773 | } 774 | 775 | #[test] 776 | fn test_eq() { 777 | let a = ParallelVec::from(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 778 | let b = ParallelVec::from(vec![(1, 2), (3, 4), (9, 6), (7, 8)]); 779 | let c = ParallelVec::from(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 780 | assert!(a == a); 781 | assert!(a != b); 782 | assert!(a == c); 783 | assert!(b != a); 784 | assert!(b == b); 785 | assert!(b != c); 786 | assert!(c == a); 787 | assert!(c != b); 788 | assert!(c == c); 789 | } 790 | 791 | #[test] 792 | fn test_extend() { 793 | let mut src = ParallelVec::new(); 794 | src.push((0, 0)); 795 | src.push((-1, -1)); 796 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 797 | src.push((10, 10)); 798 | src.push((11, 11)); 799 | let (a, b) = src.as_slices(); 800 | assert_eq!(a, &[0, -1, 1, 3, 5, 7, 10, 11]); 801 | assert_eq!(b, &[0, -1, 2, 4, 6, 8, 10, 11]); 802 | assert_eq!(src.len(), 8); 803 | } 804 | 805 | #[test] 806 | fn test_swap_remove() { 807 | let mut src = ParallelVec::new(); 808 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 809 | src.swap_remove(1); 810 | let (a, b) = src.as_slices(); 811 | assert_eq!(a, &[1, 7, 5]); 812 | assert_eq!(b, &[2, 8, 6]); 813 | assert_eq!(src.len(), 3); 814 | } 815 | 816 | #[test] 817 | #[should_panic] 818 | fn test_swap_remove_panics() { 819 | let mut src = ParallelVec::new(); 820 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 821 | src.swap_remove(12); 822 | } 823 | 824 | #[test] 825 | fn test_swap() { 826 | let mut src = ParallelVec::new(); 827 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 828 | src.swap(1, 2); 829 | let (a, b) = src.as_slices(); 830 | assert_eq!(a, &[1, 5, 3, 7]); 831 | assert_eq!(b, &[2, 6, 4, 8]); 832 | assert_eq!(src.len(), 4); 833 | src.swap(0, 3); 834 | let (a, b) = src.as_slices(); 835 | assert_eq!(a, &[7, 5, 3, 1]); 836 | assert_eq!(b, &[8, 6, 4, 2]); 837 | assert_eq!(src.len(), 4); 838 | src.swap(3, 0); 839 | let (a, b) = src.as_slices(); 840 | assert_eq!(a, &[1, 5, 3, 7]); 841 | assert_eq!(b, &[2, 6, 4, 8]); 842 | assert_eq!(src.len(), 4); 843 | } 844 | 845 | #[test] 846 | #[should_panic] 847 | fn test_swap_panics() { 848 | let mut src = ParallelVec::new(); 849 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 850 | src.swap(20, 2); 851 | } 852 | 853 | #[test] 854 | fn test_swap_with() { 855 | let mut src_a = ParallelVec::new(); 856 | src_a.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 857 | let mut src_b = ParallelVec::new(); 858 | src_b.extend(vec![(9, 9), (2, 2), (4, 4), (7, 7)]); 859 | let (a, b) = src_a.as_slices(); 860 | assert_eq!(a, &[1, 3, 5, 7]); 861 | assert_eq!(b, &[2, 4, 6, 8]); 862 | assert_eq!(src_a.len(), 4); 863 | let (a, b) = src_b.as_slices(); 864 | assert_eq!(a, &[9, 2, 4, 7]); 865 | assert_eq!(b, &[9, 2, 4, 7]); 866 | assert_eq!(src_b.len(), 4); 867 | src_a.swap_with(&mut src_b); 868 | let (a, b) = src_a.as_slices(); 869 | assert_eq!(a, &[9, 2, 4, 7]); 870 | assert_eq!(b, &[9, 2, 4, 7]); 871 | assert_eq!(src_a.len(), 4); 872 | let (a, b) = src_b.as_slices(); 873 | assert_eq!(a, &[1, 3, 5, 7]); 874 | assert_eq!(b, &[2, 4, 6, 8]); 875 | assert_eq!(src_b.len(), 4); 876 | } 877 | 878 | #[test] 879 | fn test_drop() { 880 | let rc = Rc::new(0); 881 | let mut src_a = ParallelVec::new(); 882 | src_a.extend(vec![ 883 | (rc.clone(), rc.clone()), 884 | (rc.clone(), rc.clone()), 885 | (rc.clone(), rc.clone()), 886 | (rc.clone(), rc.clone()), 887 | ]); 888 | assert_eq!(Rc::strong_count(&rc), 9); 889 | core::mem::drop(src_a); 890 | assert_eq!(Rc::strong_count(&rc), 1); 891 | } 892 | 893 | #[test] 894 | fn test_append() { 895 | let mut src_a = ParallelVec::new(); 896 | src_a.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 897 | let mut src_b = ParallelVec::new(); 898 | src_b.extend(vec![(9, 9), (2, 2), (4, 4), (7, 7)]); 899 | src_a.append(&mut src_b); 900 | let (a, b) = src_a.as_slices(); 901 | assert_eq!(a, &[1, 3, 5, 7, 9, 2, 4, 7]); 902 | assert_eq!(b, &[2, 4, 6, 8, 9, 2, 4, 7]); 903 | assert_eq!(src_a.len(), 8); 904 | let (a, b) = src_b.as_slices(); 905 | assert_eq!(a, &[]); 906 | assert_eq!(b, &[]); 907 | assert_eq!(src_b.len(), 0); 908 | } 909 | 910 | #[test] 911 | #[should_panic] 912 | fn test_swap_with_panics() { 913 | let mut src_a = ParallelVec::new(); 914 | src_a.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 915 | let mut src_b = ParallelVec::new(); 916 | src_b.extend(vec![(9, 9), (2, 2), (7, 7)]); 917 | src_a.swap_with(&mut src_b); 918 | } 919 | 920 | #[test] 921 | fn test_set() { 922 | let mut src = ParallelVec::new(); 923 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 924 | src.set(2, (0, 0)); 925 | let (a, b) = src.as_slices(); 926 | assert_eq!(a, &[1, 3, 0, 7]); 927 | assert_eq!(b, &[2, 4, 0, 8]); 928 | assert_eq!(src.len(), 4); 929 | } 930 | 931 | #[test] 932 | #[should_panic] 933 | fn test_set_panics() { 934 | let mut src = ParallelVec::new(); 935 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 936 | src.set(10, (0, 0)); 937 | } 938 | 939 | #[test] 940 | fn test_get_single() { 941 | let mut src = ParallelVec::new(); 942 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 943 | assert_eq!(src.get(0), Some((&1, &2))); 944 | assert_eq!(src.get(1), Some((&3, &4))); 945 | assert_eq!(src.get(2), Some((&5, &6))); 946 | assert_eq!(src.get(3), Some((&7, &8))); 947 | assert_eq!(src.get(4), None); 948 | assert_eq!(src.get(5), None); 949 | } 950 | 951 | #[test] 952 | fn test_get_mut_single() { 953 | let mut src = ParallelVec::new(); 954 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 955 | assert_eq!(src.get_mut(0), Some((&mut 1, &mut 2))); 956 | assert_eq!(src.get_mut(1), Some((&mut 3, &mut 4))); 957 | assert_eq!(src.get_mut(2), Some((&mut 5, &mut 6))); 958 | assert_eq!(src.get_mut(3), Some((&mut 7, &mut 8))); 959 | assert_eq!(src.get_mut(4), None); 960 | assert_eq!(src.get_mut(5), None); 961 | } 962 | 963 | #[test] 964 | fn test_first() { 965 | let mut src = ParallelVec::new(); 966 | assert_eq!(src.first(), None); 967 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 968 | assert_eq!(src.first(), Some((&1, &2))); 969 | } 970 | 971 | #[test] 972 | fn test_first_mut() { 973 | let mut src = ParallelVec::new(); 974 | assert_eq!(src.first_mut(), None); 975 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 976 | assert_eq!(src.first_mut(), Some((&mut 1, &mut 2))); 977 | } 978 | 979 | #[test] 980 | fn test_last() { 981 | let mut src = ParallelVec::new(); 982 | assert_eq!(src.last(), None); 983 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 984 | assert_eq!(src.last(), Some((&7, &8))); 985 | } 986 | 987 | #[test] 988 | fn test_last_mut() { 989 | let mut src = ParallelVec::new(); 990 | assert_eq!(src.last_mut(), None); 991 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 992 | assert_eq!(src.last_mut(), Some((&mut 7, &mut 8))); 993 | } 994 | 995 | #[test] 996 | fn test_get_slice() { 997 | let mut src = ParallelVec::new(); 998 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 999 | let slice = src.get(1..3); 1000 | assert!(slice.is_some()); 1001 | let slice = slice.unwrap(); 1002 | assert_eq!(slice.len(), 2); 1003 | let (a, b) = slice.as_slices(); 1004 | assert_eq!(a, &[3, 5]); 1005 | assert_eq!(b, &[4, 6]); 1006 | let slice = src.get(1..5); 1007 | assert!(slice.is_none()); 1008 | } 1009 | 1010 | #[test] 1011 | fn test_get_mut_slice() { 1012 | let mut src = ParallelVec::new(); 1013 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1014 | let slice = src.get_mut(1..3); 1015 | assert!(slice.is_some()); 1016 | let mut slice = slice.unwrap(); 1017 | assert_eq!(slice.len(), 2); 1018 | let (a, b) = slice.as_slices_mut(); 1019 | assert_eq!(a, &mut [3, 5]); 1020 | assert_eq!(b, &mut [4, 6]); 1021 | let slice = src.get(1..5); 1022 | assert!(slice.is_none()); 1023 | } 1024 | 1025 | #[test] 1026 | fn test_index_single() { 1027 | let mut src = ParallelVec::new(); 1028 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1029 | assert_eq!(src.index(0), (&1, &2)); 1030 | assert_eq!(src.index(1), (&3, &4)); 1031 | assert_eq!(src.index(2), (&5, &6)); 1032 | assert_eq!(src.index(3), (&7, &8)); 1033 | } 1034 | 1035 | #[test] 1036 | #[should_panic] 1037 | fn test_index_single_panics() { 1038 | let mut src = ParallelVec::new(); 1039 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1040 | src.index(4); 1041 | } 1042 | 1043 | #[test] 1044 | fn test_index_mut_single() { 1045 | let mut src = ParallelVec::new(); 1046 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1047 | assert_eq!(src.index_mut(0), (&mut 1, &mut 2)); 1048 | assert_eq!(src.index_mut(1), (&mut 3, &mut 4)); 1049 | assert_eq!(src.index_mut(2), (&mut 5, &mut 6)); 1050 | assert_eq!(src.index_mut(3), (&mut 7, &mut 8)); 1051 | } 1052 | 1053 | #[test] 1054 | #[should_panic] 1055 | fn test_index_mut_panics() { 1056 | let mut src = ParallelVec::new(); 1057 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1058 | src.index_mut(4); 1059 | } 1060 | 1061 | #[test] 1062 | fn test_index_slice() { 1063 | let mut src = ParallelVec::new(); 1064 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1065 | let slice = src.index(1..3); 1066 | let (a, b) = slice.as_slices(); 1067 | assert_eq!(a, &[3, 5]); 1068 | assert_eq!(b, &[4, 6]); 1069 | } 1070 | 1071 | #[test] 1072 | #[should_panic] 1073 | fn test_index_slice_panics() { 1074 | let mut src = ParallelVec::new(); 1075 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1076 | src.index(1..9); 1077 | } 1078 | 1079 | #[test] 1080 | fn test_index_mut_slice() { 1081 | let mut src = ParallelVec::new(); 1082 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1083 | let slice = src.index_mut(1..3); 1084 | let (a, b) = slice.as_slices(); 1085 | assert_eq!(a, &mut [3, 5]); 1086 | assert_eq!(b, &mut [4, 6]); 1087 | } 1088 | 1089 | #[test] 1090 | #[should_panic] 1091 | fn test_index_mut_slice_panics() { 1092 | let mut src = ParallelVec::new(); 1093 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1094 | src.index_mut(1..9); 1095 | } 1096 | 1097 | #[test] 1098 | fn test_into_iter() { 1099 | let mut src = ParallelVec::new(); 1100 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1101 | let vec: Vec<_> = src.into_iter().collect(); 1102 | assert_eq!(vec, vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1103 | } 1104 | 1105 | #[test] 1106 | fn test_slice_is_empty() { 1107 | let mut src = ParallelVec::new(); 1108 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8)]); 1109 | let slice = src.index(1..1); 1110 | assert!(slice.is_empty()); 1111 | } 1112 | 1113 | #[test] 1114 | fn test_slice_first() { 1115 | let mut src = ParallelVec::new(); 1116 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1117 | let slice = src.index(1..4); 1118 | assert_eq!(slice.first(), Some((&3, &4))); 1119 | } 1120 | 1121 | #[test] 1122 | fn test_slice_last() { 1123 | let mut src = ParallelVec::new(); 1124 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1125 | let slice = src.index(1..4); 1126 | assert_eq!(slice.last(), Some((&7, &8))); 1127 | } 1128 | 1129 | #[test] 1130 | fn test_slice_get() { 1131 | let mut src = ParallelVec::new(); 1132 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1133 | let slice = src.index(1..4); 1134 | assert_eq!(slice.len(), 3); 1135 | assert_eq!(slice.get(0), Some((&3, &4))); 1136 | assert_eq!(slice.get(1), Some((&5, &6))); 1137 | assert_eq!(slice.get(2), Some((&7, &8))); 1138 | assert_eq!(slice.get(3), None); 1139 | assert_eq!(slice.get(4), None); 1140 | } 1141 | 1142 | #[test] 1143 | fn test_slice_index() { 1144 | let mut src = ParallelVec::new(); 1145 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1146 | let slice = src.index(1..4); 1147 | assert_eq!(slice.len(), 3); 1148 | assert_eq!(slice.index(0), (&3, &4)); 1149 | assert_eq!(slice.index(1), (&5, &6)); 1150 | assert_eq!(slice.index(2), (&7, &8)); 1151 | } 1152 | 1153 | #[test] 1154 | #[should_panic] 1155 | fn test_slice_index_panics() { 1156 | let mut src = ParallelVec::new(); 1157 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1158 | let slice = src.index(1..4); 1159 | slice.index(3); 1160 | } 1161 | 1162 | #[test] 1163 | fn test_slice_iter() { 1164 | let mut src = ParallelVec::new(); 1165 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1166 | let slice = src.index(1..4); 1167 | let mut iter = slice.iter(); 1168 | assert_eq!(iter.next(), Some((&3, &4))); 1169 | assert_eq!(iter.next(), Some((&5, &6))); 1170 | assert_eq!(iter.next(), Some((&7, &8))); 1171 | assert_eq!(iter.next(), None); 1172 | assert_eq!(iter.next(), None); 1173 | } 1174 | 1175 | #[test] 1176 | fn test_slice_iters() { 1177 | let mut src = ParallelVec::new(); 1178 | src.extend(vec![(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]); 1179 | let slice = src.index(1..4); 1180 | let (mut a, mut b) = slice.iters(); 1181 | assert_eq!(a.next(), Some(&3)); 1182 | assert_eq!(a.next(), Some(&5)); 1183 | assert_eq!(a.next(), Some(&7)); 1184 | assert_eq!(a.next(), None); 1185 | assert_eq!(a.next(), None); 1186 | assert_eq!(b.next(), Some(&4)); 1187 | assert_eq!(b.next(), Some(&6)); 1188 | assert_eq!(b.next(), Some(&8)); 1189 | assert_eq!(b.next(), None); 1190 | assert_eq!(b.next(), None); 1191 | } 1192 | 1193 | #[test] 1194 | #[should_panic] 1195 | fn reserve_overflow_negative() { 1196 | let mut v = ParallelVec::new(); 1197 | (1..8).for_each(|i| v.push((i, i))); 1198 | v.reserve(usize::MAX - 8); 1199 | } 1200 | 1201 | #[test] 1202 | #[should_panic] 1203 | fn reserve_overflow() { 1204 | let mut v = ParallelVec::new(); 1205 | (1..8).for_each(|i| v.push((i, i))); 1206 | v.reserve(usize::MAX); 1207 | } 1208 | } 1209 | --------------------------------------------------------------------------------