├── .gitignore ├── Cargo.toml ├── README.md ├── LICENSE-MIT ├── .github └── workflows │ └── rust.yml ├── LICENSE-APACHE ├── benches └── bench.rs └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "append-only-vec" 3 | version = "0.1.8" 4 | authors = ["David Roundy "] 5 | 6 | edition = "2021" 7 | 8 | description = "Append-only, concurrent vector" 9 | license = "MIT OR Apache-2.0" 10 | repository = "https://github.com/droundy/append-only-vec" 11 | 12 | readme = "README.md" 13 | categories = ["data-structures", "concurrency"] 14 | keywords = ["frozen", "data-structure"] 15 | 16 | 17 | [dependencies] 18 | 19 | [dev-dependencies] 20 | 21 | scaling = "0.1.3" 22 | parking_lot = "0.12" 23 | 24 | [[bench]] 25 | name = "bench" 26 | harness = false 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Append-only-vec 2 |   [![Latest version](https://img.shields.io/crates/v/append-only-vec.svg)](https://crates.io/crates/append-only-vec) [![Documentation](https://docs.rs/append-only-vec/badge.svg)](https://docs.rs/append-only-vec) 3 | [![Build Status](https://github.com/droundy/append-only-vec/actions/workflows/rust.yml/badge.svg)](https://github.com/droundy/append-only-vec/actions) 4 | 5 | **Note: currently there are frequent CI failures above, which are simply due to failure to install miri to run the test. The tests do pass when run locally.** 6 | 7 | This crate defines a single data simple structure, which is a vector to which you can only append data. It allows you to push new data values even when there are outstanding references to elements of the `AppendOnlyVec`. Reading from a `AppendOnlyVec` is much faster than if it had been protected by a `std::sync::RwLock`. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Continuous integration 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | rust: 12 | - stable 13 | - 1.57 14 | target: 15 | - x86_64-unknown-linux-gnu 16 | - i686-unknown-linux-gnu 17 | - aarch64-unknown-linux-gnu 18 | steps: 19 | - uses: actions/checkout@v2 20 | - uses: actions-rs/toolchain@v1 21 | with: 22 | profile: minimal 23 | toolchain: ${{ matrix.rust }} 24 | target: ${{ matrix.target }} 25 | override: true 26 | - uses: actions-rs/cargo@v1 27 | with: 28 | command: check 29 | args: --all-features 30 | 31 | test: 32 | name: Test Suite 33 | runs-on: ubuntu-latest 34 | strategy: 35 | matrix: 36 | rust: 37 | - stable 38 | target: 39 | - x86_64-unknown-linux-gnu 40 | - i686-unknown-linux-gnu 41 | steps: 42 | - uses: actions/checkout@v2 43 | - uses: actions-rs/toolchain@v1 44 | with: 45 | profile: minimal 46 | toolchain: ${{ matrix.rust }} 47 | target: ${{ matrix.target }} 48 | override: true 49 | - uses: actions-rs/cargo@v1 50 | with: 51 | command: test 52 | args: --all-features 53 | # docsrs: 54 | # name: Generate docs.rs 55 | # runs-on: ubuntu-latest 56 | # strategy: 57 | # matrix: 58 | # rust: 59 | # - nightly 60 | # steps: 61 | # - uses: actions/checkout@v2 62 | # - uses: actions-rs/toolchain@v1 63 | # with: 64 | # profile: minimal 65 | # toolchain: ${{ matrix.rust }} 66 | # override: true 67 | # - uses: actions-rs/cargo@v1 68 | # with: 69 | # command: doc 70 | # args: --all-features 71 | # env: 72 | # RUSTFLAGS: --cfg docsrs 73 | # RUSTDOCFLAGS: --cfg docsrs -Dwarnings 74 | msrv: 75 | name: Minimum supported rust version 76 | runs-on: ubuntu-latest 77 | strategy: 78 | matrix: 79 | rust: 80 | - 1.56 81 | steps: 82 | - uses: actions/checkout@v2 83 | - uses: actions-rs/toolchain@v1 84 | with: 85 | profile: minimal 86 | toolchain: ${{ matrix.rust }} 87 | override: true 88 | - uses: actions-rs/cargo@v1 89 | with: 90 | command: test 91 | miri-test: 92 | runs-on: ubuntu-latest 93 | strategy: 94 | matrix: 95 | rust: 96 | - nightly 97 | steps: 98 | - uses: actions/checkout@v2 99 | - uses: actions-rs/toolchain@v1 100 | with: 101 | profile: minimal 102 | toolchain: ${{ matrix.rust }} 103 | override: true 104 | components: miri 105 | - name: miri test 106 | run: cargo miri test 107 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /benches/bench.rs: -------------------------------------------------------------------------------- 1 | use std::{ops::Index, sync::RwLock}; 2 | 3 | use append_only_vec::AppendOnlyVec; 4 | use scaling::{bench, bench_scaling_gen}; 5 | 6 | struct RwVec { 7 | data: RwLock>, 8 | } 9 | 10 | impl RwVec { 11 | fn new() -> Self { 12 | RwVec { 13 | data: RwLock::new(Vec::new()), 14 | } 15 | } 16 | fn push(&self, val: T) { 17 | self.data.write().unwrap().push(val) 18 | } 19 | fn get(&self, index: usize) -> T { 20 | self.data.read().unwrap().index(index).clone() 21 | } 22 | fn len(&self) -> usize { 23 | self.data.read().unwrap().len() 24 | } 25 | } 26 | 27 | struct ParkVec { 28 | data: parking_lot::RwLock>, 29 | } 30 | 31 | impl ParkVec { 32 | fn new() -> Self { 33 | ParkVec { 34 | data: parking_lot::RwLock::new(Vec::new()), 35 | } 36 | } 37 | fn push(&self, val: T) { 38 | self.data.write().push(val) 39 | } 40 | fn get(&self, index: usize) -> T { 41 | self.data.read().index(index).clone() 42 | } 43 | fn len(&self) -> usize { 44 | self.data.read().len() 45 | } 46 | } 47 | 48 | fn main() { 49 | { 50 | println!( 51 | "AOV: Filling 10 strings: {}", 52 | bench(|| { 53 | let v = AppendOnlyVec::new(); 54 | for i in 0..10 { 55 | v.push(format!("{}", i)); 56 | } 57 | v 58 | }) 59 | ); 60 | println!( 61 | "RWV: Filling 10 strings: {}", 62 | bench(|| { 63 | let v = RwVec::new(); 64 | for i in 0..10 { 65 | v.push(format!("{}", i)); 66 | } 67 | v 68 | }) 69 | ); 70 | println!( 71 | "plV: Filling 10 strings: {}", 72 | bench(|| { 73 | let v = ParkVec::new(); 74 | for i in 0..10 { 75 | v.push(format!("{}", i)); 76 | } 77 | v 78 | }) 79 | ); 80 | println!( 81 | "Vec: Filling 10 strings: {}", 82 | bench(|| { 83 | let mut v = Vec::new(); 84 | for i in 0..10 { 85 | v.push(format!("{}", i)); 86 | } 87 | v 88 | }) 89 | ); 90 | 91 | println!(); 92 | 93 | println!( 94 | "AOV: Filling 100 strings: {}", 95 | bench(|| { 96 | let v = AppendOnlyVec::new(); 97 | for i in 0..100 { 98 | v.push(format!("{}", i)); 99 | } 100 | v 101 | }) 102 | ); 103 | println!( 104 | "RWV: Filling 100 strings: {}", 105 | bench(|| { 106 | let v = RwVec::new(); 107 | for i in 0..100 { 108 | v.push(format!("{}", i)); 109 | } 110 | v 111 | }) 112 | ); 113 | println!( 114 | "plV: Filling 100 strings: {}", 115 | bench(|| { 116 | let v = ParkVec::new(); 117 | for i in 0..100 { 118 | v.push(format!("{}", i)); 119 | } 120 | v 121 | }) 122 | ); 123 | println!( 124 | "Vec: Filling 100 strings: {}", 125 | bench(|| { 126 | let mut v = Vec::new(); 127 | for i in 0..100 { 128 | v.push(format!("{}", i)); 129 | } 130 | v 131 | }) 132 | ); 133 | } 134 | println!(); 135 | { 136 | let min_n = 1000; 137 | println!( 138 | "AOV: sum: {}", 139 | bench_scaling_gen( 140 | |n: usize| { 141 | let vec = AppendOnlyVec::new(); 142 | for i in 0..n { 143 | vec.push(i); 144 | } 145 | vec 146 | }, 147 | |vec| { vec.iter().copied().sum::() }, 148 | min_n 149 | ) 150 | ); 151 | println!( 152 | "AOV: reversed sum: {}", 153 | bench_scaling_gen( 154 | |n: usize| { 155 | let vec = AppendOnlyVec::new(); 156 | for i in 0..n { 157 | vec.push(i); 158 | } 159 | vec 160 | }, 161 | |vec| { vec.iter().copied().rev().sum::() }, 162 | min_n 163 | ) 164 | ); 165 | println!( 166 | "Vec: sum: {}", 167 | bench_scaling_gen( 168 | |n: usize| { 169 | let mut vec = Vec::new(); 170 | for i in 0..n { 171 | vec.push(i); 172 | } 173 | vec 174 | }, 175 | |vec| { vec.iter().copied().sum::() }, 176 | min_n 177 | ) 178 | ); 179 | 180 | println!(); 181 | 182 | println!( 183 | "AOV: loop sum: {}", 184 | bench_scaling_gen( 185 | |n: usize| { 186 | let vec = AppendOnlyVec::new(); 187 | for i in 0..n { 188 | vec.push(i); 189 | } 190 | vec 191 | }, 192 | |vec| { 193 | let mut sum = 0; 194 | for i in 0..vec.len() { 195 | sum += vec[i]; 196 | } 197 | sum 198 | }, 199 | min_n 200 | ) 201 | ); 202 | println!( 203 | "RWV: loop sum: {}", 204 | bench_scaling_gen( 205 | |n: usize| { 206 | let vec = RwVec::new(); 207 | for i in 0..n { 208 | vec.push(i); 209 | } 210 | vec 211 | }, 212 | |vec| { 213 | let mut sum = 0; 214 | for i in 0..vec.len() { 215 | sum += vec.get(i); 216 | } 217 | sum 218 | }, 219 | min_n 220 | ) 221 | ); 222 | println!( 223 | "plV: loop sum: {}", 224 | bench_scaling_gen( 225 | |n: usize| { 226 | let vec = ParkVec::new(); 227 | for i in 0..n { 228 | vec.push(i); 229 | } 230 | vec 231 | }, 232 | |vec| { 233 | let mut sum = 0; 234 | for i in 0..vec.len() { 235 | sum += vec.get(i); 236 | } 237 | sum 238 | }, 239 | min_n 240 | ) 241 | ); 242 | println!( 243 | "Vec: loop sum: {}", 244 | bench_scaling_gen( 245 | |n: usize| { 246 | let mut vec = Vec::new(); 247 | for i in 0..n { 248 | vec.push(i); 249 | } 250 | vec 251 | }, 252 | |vec| { 253 | let mut sum = 0; 254 | for i in 0..vec.len() { 255 | sum += vec[i]; 256 | } 257 | sum 258 | }, 259 | min_n 260 | ) 261 | ); 262 | 263 | println!(); 264 | 265 | println!( 266 | "AOV: back loop sum: {}", 267 | bench_scaling_gen( 268 | |n: usize| { 269 | let vec = AppendOnlyVec::new(); 270 | for i in 0..n { 271 | vec.push(i); 272 | } 273 | vec 274 | }, 275 | |vec| { 276 | let mut sum = 0; 277 | let n = vec.len(); 278 | for i in 0..n { 279 | sum += vec[n - 1 - i]; 280 | } 281 | sum 282 | }, 283 | min_n 284 | ) 285 | ); 286 | println!( 287 | "RWV: back loop sum: {}", 288 | bench_scaling_gen( 289 | |n: usize| { 290 | let vec = RwVec::new(); 291 | for i in 0..n { 292 | vec.push(i); 293 | } 294 | vec 295 | }, 296 | |vec| { 297 | let mut sum = 0; 298 | let n = vec.len(); 299 | for i in 0..n { 300 | sum += vec.get(n - 1 - i); 301 | } 302 | sum 303 | }, 304 | min_n 305 | ) 306 | ); 307 | println!( 308 | "plV: back loop sum: {}", 309 | bench_scaling_gen( 310 | |n: usize| { 311 | let vec = ParkVec::new(); 312 | for i in 0..n { 313 | vec.push(i); 314 | } 315 | vec 316 | }, 317 | |vec| { 318 | let mut sum = 0; 319 | let n = vec.len(); 320 | for i in 0..n { 321 | sum += vec.get(n - 1 - i); 322 | } 323 | sum 324 | }, 325 | min_n 326 | ) 327 | ); 328 | println!( 329 | "Vec: back loop sum: {}", 330 | bench_scaling_gen( 331 | |n: usize| { 332 | let mut vec = Vec::new(); 333 | for i in 0..n { 334 | vec.push(i); 335 | } 336 | vec 337 | }, 338 | |vec| { 339 | let mut sum = 0; 340 | let n = vec.len(); 341 | for i in 0..n { 342 | sum += vec[n - 1 - i]; 343 | } 344 | sum 345 | }, 346 | min_n 347 | ) 348 | ); 349 | } 350 | println!(); 351 | } 352 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! AppendOnlyVec 2 | //! 3 | //! This is a pretty simple type, which is a vector that you can push into, but 4 | //! cannot modify the elements of. The data structure never moves an element 5 | //! once allocated, so you can push to the vec even while holding references to 6 | //! elements that have already been pushed. 7 | //! 8 | //! ### Scaling 9 | //! 10 | //! 1. Accessing an element is O(1), but slightly more expensive than for a 11 | //! standard `Vec`. 12 | //! 13 | //! 2. Pushing a new element amortizes to O(1), but may require allocation of a 14 | //! new chunk. 15 | //! 16 | //! ### Example 17 | //! 18 | //! ``` 19 | //! use append_only_vec::AppendOnlyVec; 20 | //! static V: AppendOnlyVec = AppendOnlyVec::::new(); 21 | //! let mut threads = Vec::new(); 22 | //! for thread_num in 0..10 { 23 | //! threads.push(std::thread::spawn(move || { 24 | //! for n in 0..100 { 25 | //! let s = format!("thread {} says {}", thread_num, n); 26 | //! let which = V.push(s.clone()); 27 | //! assert_eq!(&V[which], &s); 28 | //! } 29 | //! })); 30 | //! } 31 | //! for t in threads { 32 | //! t.join(); 33 | //! } 34 | //! assert_eq!(V.len(), 1000); 35 | //! ``` 36 | 37 | use std::cell::UnsafeCell; 38 | use std::ops::{Index, IndexMut}; 39 | use std::sync::atomic::AtomicUsize; 40 | use std::sync::atomic::Ordering; 41 | pub struct AppendOnlyVec { 42 | count: AtomicUsize, 43 | reserved: AtomicUsize, 44 | data: [UnsafeCell<*mut T>; BITS_USED - 1 - 3], 45 | } 46 | 47 | unsafe impl Send for AppendOnlyVec {} 48 | unsafe impl Sync for AppendOnlyVec {} 49 | 50 | const BITS: usize = std::mem::size_of::() * 8; 51 | 52 | #[cfg(target_arch = "x86_64")] 53 | const BITS_USED: usize = 48; 54 | #[cfg(all(not(target_arch = "x86_64"), target_pointer_width = "64"))] 55 | const BITS_USED: usize = 64; 56 | #[cfg(target_pointer_width = "32")] 57 | const BITS_USED: usize = 32; 58 | 59 | // This takes an index into a vec, and determines which data array will hold it 60 | // (the first return value), and what the index will be into that data array 61 | // (second return value) 62 | // 63 | // The ith data array holds 1< (u32, usize) { 65 | let i = i + 8; 66 | let bin = BITS as u32 - 1 - i.leading_zeros(); 67 | let bin = bin - 3; 68 | let offset = i - bin_size(bin); 69 | (bin, offset) 70 | } 71 | const fn bin_size(array: u32) -> usize { 72 | (1 << 3) << array 73 | } 74 | 75 | fn spin_wait(failures: &mut usize) { 76 | *failures += 1; 77 | if *failures <= 3 { 78 | // If there haven't been many failures yet, then we optimistically 79 | // spinloop. 80 | for _ in 0..(1 << *failures) { 81 | std::hint::spin_loop(); 82 | } 83 | } else { 84 | // If there have been many failures, then continuing to spinloop will 85 | // probably just waste CPU, and whoever we are waiting for has been 86 | // preempted then spinning could actively delay completion of the task. 87 | // So instead, we cooperatively yield to the OS scheduler. 88 | std::thread::yield_now(); 89 | } 90 | } 91 | 92 | #[test] 93 | fn test_indices() { 94 | for i in 0..32 { 95 | println!("{:3}: {} {}", i, indices(i).0, indices(i).1); 96 | } 97 | let mut array = 0; 98 | let mut offset = 0; 99 | let mut index = 0; 100 | while index < 1000 { 101 | index += 1; 102 | offset += 1; 103 | if offset >= bin_size(array) { 104 | offset = 0; 105 | array += 1; 106 | } 107 | assert_eq!(indices(index), (array, offset)); 108 | } 109 | } 110 | 111 | impl Default for AppendOnlyVec { 112 | fn default() -> Self { 113 | Self::new() 114 | } 115 | } 116 | 117 | impl AppendOnlyVec { 118 | /// Return an `Iterator` over the elements of the vec. 119 | pub fn iter(&self) -> impl DoubleEndedIterator + ExactSizeIterator { 120 | // FIXME this could be written to be a little more efficient probably, 121 | // if we made it read each pointer only once. On the other hand, that 122 | // could make a reversed iterator less efficient? 123 | (0..self.len()).map(|i| unsafe { self.get_unchecked(i) }) 124 | } 125 | /// Find the length of the array. 126 | #[inline] 127 | pub fn len(&self) -> usize { 128 | self.count.load(Ordering::Acquire) 129 | } 130 | 131 | fn layout(&self, array: u32) -> std::alloc::Layout { 132 | std::alloc::Layout::array::(bin_size(array)).unwrap() 133 | } 134 | /// Internal-only function requests a slot and puts data into it. 135 | /// 136 | /// However this does not update the size of the vec, which *must* be done 137 | /// in order for either the value to be readable *or* for future pushes to 138 | /// actually terminate. 139 | fn pre_push(&self, val: T) -> usize { 140 | let idx = self.reserved.fetch_add(1, Ordering::Relaxed); 141 | let (array, offset) = indices(idx); 142 | let ptr = if self.len() < 1 + idx - offset { 143 | // We are working on a new array, which may not have been allocated... 144 | if offset == 0 { 145 | // It is our job to allocate the array! The size of the array 146 | // is determined in the self.layout method, which needs to be 147 | // consistent with the indices function. 148 | let layout = self.layout(array); 149 | let ptr = unsafe { std::alloc::alloc(layout) } as *mut T; 150 | unsafe { 151 | *self.data[array as usize].get() = ptr; 152 | } 153 | ptr 154 | } else { 155 | // We need to wait for the array to be allocated. 156 | let mut failures = 0; 157 | while self.len() < 1 + idx - offset { 158 | spin_wait(&mut failures); 159 | } 160 | // The Ordering::Acquire semantics of self.len() ensures that 161 | // this pointer read will get the non-null pointer allocated 162 | // above. 163 | unsafe { *self.data[array as usize].get() } 164 | } 165 | } else { 166 | // The Ordering::Acquire semantics of self.len() ensures that 167 | // this pointer read will get the non-null pointer allocated 168 | // above. 169 | unsafe { *self.data[array as usize].get() } 170 | }; 171 | 172 | // The contents of this offset are guaranteed to be unused (so far) 173 | // because we got the idx from our fetch_add above, and ptr is 174 | // guaranteed to be valid because of the loop we used above, which used 175 | // self.len() which has Ordering::Acquire semantics. 176 | unsafe { (ptr.add(offset)).write(val) }; 177 | idx 178 | } 179 | /// Append an element to the array 180 | /// 181 | /// This is notable in that it doesn't require a `&mut self`, because it 182 | /// does appropriate atomic synchronization. 183 | /// 184 | /// The return value is the index tha was pushed to. 185 | pub fn push(&self, val: T) -> usize { 186 | let idx = self.pre_push(val); 187 | 188 | // Now we need to increase the size of the vec, so it can get read. We 189 | // use Release upon success, to ensure that the value which we wrote is 190 | // visible to any thread that has confirmed that the count is big enough 191 | // to read that element. In case of failure, we can be relaxed, since 192 | // we don't do anything with the result other than try again. 193 | let mut failures = 0; 194 | while self 195 | .count 196 | .compare_exchange(idx, idx + 1, Ordering::Release, Ordering::Relaxed) 197 | .is_err() 198 | { 199 | // This means that someone else *started* pushing before we started, 200 | // but hasn't yet finished. We have to wait for them to finish 201 | // pushing before we can update the count. 202 | spin_wait(&mut failures); 203 | } 204 | idx 205 | } 206 | /// Extend the vec with the contents of an iterator. 207 | /// 208 | /// Note: this is currently no more efficient than calling `push` for each 209 | /// element of the iterator. 210 | pub fn extend(&self, iter: impl IntoIterator) { 211 | for val in iter { 212 | self.push(val); 213 | } 214 | } 215 | /// Append an element to the array with exclusive access 216 | /// 217 | /// This is slightly more efficient than [`AppendOnlyVec::push`] since it 218 | /// doesn't need to worry about concurrent access. 219 | /// 220 | /// The return value is the new size of the array. 221 | pub fn push_mut(&mut self, val: T) -> usize { 222 | let idx = self.pre_push(val); 223 | // We do not need synchronization here because no one else has access to 224 | // this data, and if it is passed to another thread that will involve 225 | // the appropriate memory barrier. 226 | self.count.store(idx + 1, Ordering::Relaxed); 227 | idx 228 | } 229 | const EMPTY: UnsafeCell<*mut T> = UnsafeCell::new(std::ptr::null_mut()); 230 | /// Allocate a new empty array 231 | pub const fn new() -> Self { 232 | AppendOnlyVec { 233 | count: AtomicUsize::new(0), 234 | reserved: AtomicUsize::new(0), 235 | data: [Self::EMPTY; BITS_USED - 1 - 3], 236 | } 237 | } 238 | 239 | /// Index the vec without checking the bounds. 240 | /// 241 | /// To use this correctly, you *must* first ensure that the `idx < 242 | /// self.len()`. This not only prevents overwriting the bounds, but also 243 | /// creates the memory barriers to ensure that the data is visible to the 244 | /// current thread. In single-threaded code, however, it is not needed to 245 | /// call `self.len()` explicitly (if e.g. you have counted the number of 246 | /// elements pushed). 247 | unsafe fn get_unchecked(&self, idx: usize) -> &T { 248 | let (array, offset) = indices(idx); 249 | // We use a Relaxed load of the pointer, because the length check (which 250 | // was supposed to be performed) should ensure that the data we want is 251 | // already visible, since self.len() used Ordering::Acquire on 252 | // `self.count` which synchronizes with the Ordering::Release write in 253 | // `self.push`. 254 | let ptr = *self.data[array as usize].get(); 255 | &*ptr.add(offset) 256 | } 257 | 258 | /// Convert into a standard `Vec` 259 | pub fn into_vec(self) -> Vec { 260 | let mut vec = Vec::with_capacity(self.len()); 261 | 262 | for idx in 0..self.len() { 263 | let (array, offset) = indices(idx); 264 | // We use a Relaxed load of the pointer, because the loop above (which 265 | // ends before `self.len()`) should ensure that the data we want is 266 | // already visible, since it Acquired `self.count` which synchronizes 267 | // with the write in `self.push`. 268 | let ptr = unsafe { *self.data[array as usize].get() }; 269 | 270 | // Copy the element value. The copy remaining in the array must not 271 | // be used again (i.e. make sure we do not drop it) 272 | let value = unsafe { ptr.add(offset).read() }; 273 | 274 | vec.push(value); 275 | } 276 | 277 | // Prevent dropping the copied-out values by marking the count as 0 before 278 | // our own drop is run 279 | self.count.store(0, Ordering::Relaxed); 280 | 281 | vec 282 | } 283 | } 284 | impl std::fmt::Debug for AppendOnlyVec 285 | where 286 | T: std::fmt::Debug, 287 | { 288 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 289 | f.debug_list().entries(self.iter()).finish() 290 | } 291 | } 292 | 293 | impl Index for AppendOnlyVec { 294 | type Output = T; 295 | 296 | fn index(&self, idx: usize) -> &Self::Output { 297 | assert!(idx < self.len()); // this includes the required ordering memory barrier 298 | let (array, offset) = indices(idx); 299 | // The ptr value below is safe, because the length check above will 300 | // ensure that the data we want is already visible, since it used 301 | // Ordering::Acquire on `self.count` which synchronizes with the 302 | // Ordering::Release write in `self.push`. 303 | let ptr = unsafe { *self.data[array as usize].get() }; 304 | unsafe { &*ptr.add(offset) } 305 | } 306 | } 307 | 308 | impl IndexMut for AppendOnlyVec { 309 | fn index_mut(&mut self, idx: usize) -> &mut Self::Output { 310 | assert!(idx < self.len()); // this includes the required ordering memory barrier 311 | let (array, offset) = indices(idx); 312 | // The ptr value below is safe, because the length check above will 313 | // ensure that the data we want is already visible, since it used 314 | // Ordering::Acquire on `self.count` which synchronizes with the 315 | // Ordering::Release write in `self.push`. 316 | let ptr = unsafe { *self.data[array as usize].get() }; 317 | 318 | // `&mut` is safe because there can be no access to data owned by 319 | // `self` except via `self`, and we have `&mut` on `self` 320 | unsafe { &mut *ptr.add(offset) } 321 | } 322 | } 323 | 324 | impl Drop for AppendOnlyVec { 325 | fn drop(&mut self) { 326 | // First we'll drop all the `T` in a slightly sloppy way. FIXME this 327 | // could be optimized to avoid reloading the `ptr`. 328 | for idx in 0..self.len() { 329 | let (array, offset) = indices(idx); 330 | // We use a Relaxed load of the pointer, because the loop above (which 331 | // ends before `self.len()`) should ensure that the data we want is 332 | // already visible, since it Acquired `self.count` which synchronizes 333 | // with the write in `self.push`. 334 | let ptr = unsafe { *self.data[array as usize].get() }; 335 | unsafe { 336 | std::ptr::drop_in_place(ptr.add(offset)); 337 | } 338 | } 339 | // Now we will free all the arrays. 340 | for array in 0..self.data.len() as u32 { 341 | // This load is relaxed because no other thread can have a reference 342 | // to Self because we have a &mut self. 343 | let ptr = unsafe { *self.data[array as usize].get() }; 344 | if !ptr.is_null() { 345 | let layout = self.layout(array); 346 | unsafe { std::alloc::dealloc(ptr as *mut u8, layout) }; 347 | } else { 348 | break; 349 | } 350 | } 351 | } 352 | } 353 | 354 | impl Clone for AppendOnlyVec 355 | where 356 | T: Clone, 357 | { 358 | fn clone(&self) -> Self { 359 | // FIXME this could be optimized to avoid reloading pointers. 360 | self.iter().cloned().collect() 361 | } 362 | } 363 | 364 | /// An `Iterator` for the values contained in the `AppendOnlyVec` 365 | #[derive(Debug)] 366 | pub struct IntoIter(std::vec::IntoIter); 367 | 368 | impl Iterator for IntoIter { 369 | type Item = T; 370 | 371 | fn next(&mut self) -> Option { 372 | self.0.next() 373 | } 374 | 375 | fn size_hint(&self) -> (usize, Option) { 376 | self.0.size_hint() 377 | } 378 | } 379 | 380 | impl DoubleEndedIterator for IntoIter { 381 | fn next_back(&mut self) -> Option { 382 | self.0.next_back() 383 | } 384 | } 385 | 386 | impl ExactSizeIterator for IntoIter { 387 | fn len(&self) -> usize { 388 | self.0.len() 389 | } 390 | } 391 | 392 | impl IntoIterator for AppendOnlyVec { 393 | type Item = T; 394 | 395 | type IntoIter = IntoIter; 396 | 397 | fn into_iter(self) -> Self::IntoIter { 398 | IntoIter(self.into_vec().into_iter()) 399 | } 400 | } 401 | 402 | impl FromIterator for AppendOnlyVec { 403 | fn from_iter>(iter: I) -> Self { 404 | let out = Self::new(); 405 | for x in iter { 406 | let idx = out.pre_push(x); 407 | // We can be relaxed here because no one else has access to 408 | // this data, and if it is passed to another thread that will involve 409 | // the appropriate memory barrier. 410 | out.count.store(idx + 1, Ordering::Relaxed); 411 | } 412 | out 413 | } 414 | } 415 | 416 | impl From> for AppendOnlyVec { 417 | fn from(value: Vec) -> Self { 418 | value.into_iter().collect() 419 | } 420 | } 421 | 422 | #[test] 423 | fn test_pushing_and_indexing() { 424 | let v = AppendOnlyVec::::new(); 425 | 426 | for n in 0..50 { 427 | v.push(n); 428 | assert_eq!(v.len(), n + 1); 429 | for i in 0..(n + 1) { 430 | assert_eq!(v[i], i); 431 | } 432 | } 433 | 434 | let vec: Vec = v.iter().copied().collect(); 435 | let ve2: Vec = (0..50).collect(); 436 | assert_eq!(vec, ve2); 437 | } 438 | 439 | #[test] 440 | fn test_parallel_pushing() { 441 | use std::sync::Arc; 442 | let v = Arc::new(AppendOnlyVec::::new()); 443 | let mut threads = Vec::new(); 444 | const N: u64 = 100; 445 | for thread_num in 0..N { 446 | let v = v.clone(); 447 | threads.push(std::thread::spawn(move || { 448 | let which1 = v.push(thread_num); 449 | let which2 = v.push(thread_num); 450 | assert_eq!(v[which1 as usize], thread_num); 451 | assert_eq!(v[which2 as usize], thread_num); 452 | })); 453 | } 454 | for t in threads { 455 | t.join().ok(); 456 | } 457 | for thread_num in 0..N { 458 | assert_eq!(2, v.iter().copied().filter(|&x| x == thread_num).count()); 459 | } 460 | } 461 | 462 | #[test] 463 | fn test_into_vec() { 464 | struct SafeToDrop(bool); 465 | 466 | impl Drop for SafeToDrop { 467 | fn drop(&mut self) { 468 | assert!(self.0); 469 | } 470 | } 471 | 472 | let v = AppendOnlyVec::new(); 473 | 474 | for _ in 0..50 { 475 | v.push(SafeToDrop(false)); 476 | } 477 | 478 | let mut v = v.into_vec(); 479 | 480 | for i in v.iter_mut() { 481 | i.0 = true; 482 | } 483 | } 484 | 485 | #[test] 486 | fn test_push_then_index_mut() { 487 | let mut v = AppendOnlyVec::::new(); 488 | for i in 0..1024 { 489 | v.push(i); 490 | } 491 | for i in 0..1024 { 492 | v[i] += i; 493 | } 494 | for i in 0..1024 { 495 | assert_eq!(v[i], 2 * i); 496 | } 497 | } 498 | 499 | #[test] 500 | fn test_from_vec() { 501 | for v in [vec![5_i32, 4, 3, 2, 1], Vec::new(), vec![1]] { 502 | let aov: AppendOnlyVec = v.clone().into(); 503 | assert_eq!(v, aov.into_vec()); 504 | } 505 | } 506 | 507 | #[test] 508 | fn test_clone() { 509 | let v = AppendOnlyVec::::new(); 510 | for i in 0..1024 { 511 | v.push(format!("{}", i)); 512 | } 513 | let v2 = v.clone(); 514 | 515 | assert_eq!(v.len(), v2.len()); 516 | for i in 0..1024 { 517 | assert_eq!(v[i], v2[i]); 518 | } 519 | } 520 | 521 | #[test] 522 | fn test_push_mut() { 523 | let mut v = AppendOnlyVec::new(); 524 | for i in 0..1024 { 525 | v.push_mut(format!("{}", i)); 526 | } 527 | assert_eq!(v.len(), 1024); 528 | } 529 | --------------------------------------------------------------------------------