├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benches └── bench.rs ├── src ├── lib.rs ├── macros.rs ├── raw_vec.rs ├── slice.rs └── vec.rs └── tests ├── lib.rs └── vec.rs /.github/workflows/ci.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 | steps: 10 | - name: Checkout sources 11 | uses: actions/checkout@v2 12 | 13 | - name: Install nightly toolchain 14 | uses: actions-rs/toolchain@v1 15 | with: 16 | profile: minimal 17 | toolchain: nightly 18 | override: true 19 | 20 | - name: Run cargo check 21 | uses: actions-rs/cargo@v1 22 | with: 23 | command: check 24 | 25 | tests: 26 | name: Tests 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Checkout sources 30 | uses: actions/checkout@v2 31 | 32 | - name: Install nightly toolchain 33 | uses: actions-rs/toolchain@v1 34 | with: 35 | profile: minimal 36 | toolchain: nightly 37 | override: true 38 | 39 | - name: Run cargo test 40 | uses: actions-rs/cargo@v1 41 | with: 42 | command: test 43 | 44 | lints: 45 | name: Lints 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: Checkout sources 49 | uses: actions/checkout@v2 50 | 51 | - name: Install nightly toolchain 52 | uses: actions-rs/toolchain@v1 53 | with: 54 | profile: minimal 55 | toolchain: nightly 56 | override: true 57 | components: rustfmt, clippy 58 | 59 | - name: Run cargo fmt 60 | uses: actions-rs/cargo@v1 61 | with: 62 | command: fmt 63 | args: --all -- --check 64 | 65 | - name: Run cargo clippy 66 | uses: actions-rs/cargo@v1 67 | with: 68 | command: clippy 69 | args: -- -D warnings 70 | 71 | miri: 72 | name: Test (Miri) 73 | runs-on: ubuntu-latest 74 | steps: 75 | - name: Checkout sources 76 | uses: actions/checkout@v2 77 | 78 | - name: Install nightly toolchain 79 | uses: actions-rs/toolchain@v1 80 | with: 81 | profile: minimal 82 | toolchain: nightly 83 | override: true 84 | components: miri 85 | 86 | - name: Run cargo miri 87 | uses: actions-rs/cargo@v1 88 | with: 89 | command: miri 90 | args: test 91 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "ve" 5 | version = "0.0.3" 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ve" 3 | version = "0.0.3" 4 | authors = ["Ivan Tham "] 5 | edition = "2018" 6 | description = "More compact Vec" 7 | repository = "https://github.com/pickfire/ve" 8 | documentation = "https://docs.rs/ve" 9 | license = "MIT OR Apache-2.0" 10 | readme = "./README.md" 11 | keywords = ["vec", "slice"] 12 | categories = ["no-std", "memory-management"] 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ve 2 | === 3 | 4 | 5 | [![Build Status](https://github.com/pickfire/ve/workflows/Continuous%20Integration/badge.svg?branch=master)](https://github.com/pickfire/ve/actions) 6 | [![Documentation](https://docs.rs/ve/badge.svg)](https://docs.rs/ve) 7 | [![Crates.io](https://img.shields.io/crates/v/ve.svg)](https://crates.io/crates/ve) 8 | 9 | More compact version of `Vec`, uses 2 words instead of 3. Currently targetting 10 | only 64-bits machine and aim to be drop in replacement for `Vec`. 11 | 12 | This crate is work in progress, requires nightly and is highly experimental. 13 | Porting is done by hand based on rust liballoc, `String` may be next target. 14 | 15 | ```rust 16 | const WORD: usize = std::mem::size_of::(); 17 | 18 | assert_eq!(std::mem::size_of::>(), 3 * WORD); 19 | assert_eq!(std::mem::size_of::>(), 2 * WORD); 20 | ``` 21 | 22 | ## How does it work? 23 | 24 | +-----------+-----------+-----------+ 25 | std::vec::Vec | Pointer | Length | Capacity | 26 | +-----------+-----------+-----------+ 27 | 28 | +-----------+-----------+ 29 | ve::Vec | Pointer | Cap | Len | 30 | +-----------+-----------+ 31 | 32 | `ve::Vec` have capacity of 4294967295 compared to `Vec` 18446744073709551615. 33 | If you don't need that much digits, `ve::Vec` should be safe. 34 | 35 | Inspired by . 36 | 37 | ## Benchmarks 38 | 39 | Work in progress, so far creation time is slower. 40 | 41 | 42 | running 0 tests 43 | 44 | test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out 45 | 46 | ``` 47 | test bench_clone_0000 ... bench: 17 ns/iter (+/- 9) 48 | test bench_clone_0000_std ... bench: 12 ns/iter (+/- 5) 49 | test bench_clone_0010 ... bench: 41 ns/iter (+/- 10) = 243 MB/s 50 | test bench_clone_0010_std ... bench: 29 ns/iter (+/- 1) = 344 MB/s 51 | test bench_clone_0100 ... bench: 119 ns/iter (+/- 5) = 840 MB/s 52 | test bench_clone_0100_std ... bench: 118 ns/iter (+/- 2) = 847 MB/s 53 | test bench_clone_1000 ... bench: 929 ns/iter (+/- 68) = 1076 MB/s 54 | test bench_clone_1000_std ... bench: 927 ns/iter (+/- 8) = 1078 MB/s 55 | test bench_clone_from_01_0000_0000 ... bench: 23 ns/iter (+/- 0) 56 | test bench_clone_from_01_0000_0000_std ... bench: 18 ns/iter (+/- 0) 57 | test bench_clone_from_01_0000_0010 ... bench: 57 ns/iter (+/- 0) = 175 MB/s 58 | test bench_clone_from_01_0000_0010_std ... bench: 43 ns/iter (+/- 0) = 232 MB/s 59 | test bench_clone_from_01_0000_0100 ... bench: 149 ns/iter (+/- 1) = 671 MB/s 60 | test bench_clone_from_01_0000_0100_std ... bench: 139 ns/iter (+/- 13) = 719 MB/s 61 | test bench_clone_from_01_0000_1000 ... bench: 1,074 ns/iter (+/- 17) = 931 MB/s 62 | test bench_clone_from_01_0000_1000_std ... bench: 980 ns/iter (+/- 23) = 1020 MB/s 63 | test bench_clone_from_01_0010_0000 ... bench: 23 ns/iter (+/- 0) 64 | test bench_clone_from_01_0010_0000_std ... bench: 18 ns/iter (+/- 1) 65 | test bench_clone_from_01_0010_0010 ... bench: 57 ns/iter (+/- 0) = 175 MB/s 66 | test bench_clone_from_01_0010_0010_std ... bench: 43 ns/iter (+/- 1) = 232 MB/s 67 | test bench_clone_from_01_0010_0100 ... bench: 149 ns/iter (+/- 0) = 671 MB/s 68 | test bench_clone_from_01_0010_0100_std ... bench: 139 ns/iter (+/- 1) = 719 MB/s 69 | test bench_clone_from_01_0100_0010 ... bench: 57 ns/iter (+/- 3) = 175 MB/s 70 | test bench_clone_from_01_0100_0010_std ... bench: 43 ns/iter (+/- 0) = 232 MB/s 71 | test bench_clone_from_01_0100_0100 ... bench: 153 ns/iter (+/- 87) = 653 MB/s 72 | test bench_clone_from_01_0100_0100_std ... bench: 139 ns/iter (+/- 0) = 719 MB/s 73 | test bench_clone_from_01_0100_1000 ... bench: 1,072 ns/iter (+/- 17) = 932 MB/s 74 | test bench_clone_from_01_0100_1000_std ... bench: 980 ns/iter (+/- 323) = 1020 MB/s 75 | test bench_clone_from_01_1000_0100 ... bench: 149 ns/iter (+/- 2) = 671 MB/s 76 | test bench_clone_from_01_1000_0100_std ... bench: 139 ns/iter (+/- 2) = 719 MB/s 77 | test bench_clone_from_01_1000_1000 ... bench: 1,073 ns/iter (+/- 33) = 931 MB/s 78 | test bench_clone_from_01_1000_1000_std ... bench: 978 ns/iter (+/- 7) = 1022 MB/s 79 | test bench_clone_from_10_0000_0000 ... bench: 133 ns/iter (+/- 6) 80 | test bench_clone_from_10_0000_0000_std ... bench: 84 ns/iter (+/- 1) 81 | test bench_clone_from_10_0000_0010 ... bench: 345 ns/iter (+/- 6) = 289 MB/s 82 | test bench_clone_from_10_0000_0010_std ... bench: 225 ns/iter (+/- 10) = 444 MB/s 83 | test bench_clone_from_10_0000_0100 ... bench: 1,114 ns/iter (+/- 23) = 897 MB/s 84 | test bench_clone_from_10_0000_0100_std ... bench: 1,046 ns/iter (+/- 22) = 956 MB/s 85 | test bench_clone_from_10_0000_1000 ... bench: 8,589 ns/iter (+/- 223) = 1164 MB/s 86 | test bench_clone_from_10_0000_1000_std ... bench: 8,029 ns/iter (+/- 208) = 1245 MB/s 87 | test bench_clone_from_10_0010_0000 ... bench: 134 ns/iter (+/- 9) 88 | test bench_clone_from_10_0010_0000_std ... bench: 85 ns/iter (+/- 2) 89 | test bench_clone_from_10_0010_0010 ... bench: 346 ns/iter (+/- 58) = 289 MB/s 90 | test bench_clone_from_10_0010_0010_std ... bench: 223 ns/iter (+/- 13) = 448 MB/s 91 | test bench_clone_from_10_0010_0100 ... bench: 1,114 ns/iter (+/- 23) = 897 MB/s 92 | test bench_clone_from_10_0010_0100_std ... bench: 1,046 ns/iter (+/- 23) = 956 MB/s 93 | test bench_clone_from_10_0100_0010 ... bench: 344 ns/iter (+/- 6) = 290 MB/s 94 | test bench_clone_from_10_0100_0010_std ... bench: 225 ns/iter (+/- 22) = 444 MB/s 95 | test bench_clone_from_10_0100_0100 ... bench: 1,113 ns/iter (+/- 21) = 898 MB/s 96 | test bench_clone_from_10_0100_0100_std ... bench: 1,046 ns/iter (+/- 20) = 956 MB/s 97 | test bench_clone_from_10_0100_1000 ... bench: 8,616 ns/iter (+/- 242) = 1160 MB/s 98 | test bench_clone_from_10_0100_1000_std ... bench: 8,030 ns/iter (+/- 414) = 1245 MB/s 99 | test bench_clone_from_10_1000_0100 ... bench: 1,115 ns/iter (+/- 19) = 896 MB/s 100 | test bench_clone_from_10_1000_0100_std ... bench: 1,046 ns/iter (+/- 21) = 956 MB/s 101 | test bench_clone_from_10_1000_1000 ... bench: 8,587 ns/iter (+/- 373) = 1164 MB/s 102 | test bench_clone_from_10_1000_1000_std ... bench: 8,012 ns/iter (+/- 146) = 1248 MB/s 103 | test bench_extend_0000_0000 ... bench: 26 ns/iter (+/- 0) 104 | test bench_extend_0000_0000_std ... bench: 25 ns/iter (+/- 0) 105 | test bench_extend_0000_0010 ... bench: 83 ns/iter (+/- 2) = 120 MB/s 106 | test bench_extend_0000_0010_std ... bench: 65 ns/iter (+/- 1) = 153 MB/s 107 | test bench_extend_0000_0100 ... bench: 178 ns/iter (+/- 4) = 561 MB/s 108 | test bench_extend_0000_0100_std ... bench: 168 ns/iter (+/- 4) = 595 MB/s 109 | test bench_extend_0000_1000 ... bench: 1,164 ns/iter (+/- 32) = 859 MB/s 110 | test bench_extend_0000_1000_std ... bench: 1,170 ns/iter (+/- 73) = 854 MB/s 111 | test bench_extend_0010_0010 ... bench: 171 ns/iter (+/- 3) = 58 MB/s 112 | test bench_extend_0010_0010_std ... bench: 151 ns/iter (+/- 14) = 66 MB/s 113 | test bench_extend_0100_0100 ... bench: 370 ns/iter (+/- 9) = 270 MB/s 114 | test bench_extend_0100_0100_std ... bench: 350 ns/iter (+/- 9) = 285 MB/s 115 | test bench_extend_1000_1000 ... bench: 2,920 ns/iter (+/- 75) = 342 MB/s 116 | test bench_extend_1000_1000_std ... bench: 3,015 ns/iter (+/- 134) = 331 MB/s 117 | test bench_from_elem_0000 ... bench: 5 ns/iter (+/- 0) 118 | test bench_from_elem_0000_std ... bench: 4 ns/iter (+/- 0) 119 | test bench_from_elem_0010 ... bench: 35 ns/iter (+/- 0) = 285 MB/s 120 | test bench_from_elem_0010_std ... bench: 32 ns/iter (+/- 1) = 312 MB/s 121 | test bench_from_elem_0100 ... bench: 111 ns/iter (+/- 2) = 900 MB/s 122 | test bench_from_elem_0100_std ... bench: 111 ns/iter (+/- 2) = 900 MB/s 123 | test bench_from_elem_1000 ... bench: 798 ns/iter (+/- 33) = 1253 MB/s 124 | test bench_from_elem_1000_std ... bench: 795 ns/iter (+/- 16) = 1257 MB/s 125 | test bench_from_fn_0000 ... bench: 5 ns/iter (+/- 0) 126 | test bench_from_fn_0000_std ... bench: 5 ns/iter (+/- 0) 127 | test bench_from_fn_0010 ... bench: 33 ns/iter (+/- 0) = 303 MB/s 128 | test bench_from_fn_0010_std ... bench: 33 ns/iter (+/- 0) = 303 MB/s 129 | test bench_from_fn_0100 ... bench: 121 ns/iter (+/- 2) = 826 MB/s 130 | test bench_from_fn_0100_std ... bench: 119 ns/iter (+/- 3) = 840 MB/s 131 | test bench_from_fn_1000 ... bench: 948 ns/iter (+/- 23) = 1054 MB/s 132 | test bench_from_fn_1000_std ... bench: 951 ns/iter (+/- 18) = 1051 MB/s 133 | test bench_from_iter_0000 ... bench: 18 ns/iter (+/- 0) 134 | test bench_from_iter_0000_std ... bench: 12 ns/iter (+/- 0) 135 | test bench_from_iter_0010 ... bench: 72 ns/iter (+/- 1) = 138 MB/s 136 | test bench_from_iter_0010_std ... bench: 34 ns/iter (+/- 2) = 294 MB/s 137 | test bench_from_iter_0100 ... bench: 172 ns/iter (+/- 4) = 581 MB/s 138 | test bench_from_iter_0100_std ... bench: 124 ns/iter (+/- 4) = 806 MB/s 139 | test bench_from_iter_1000 ... bench: 1,168 ns/iter (+/- 70) = 856 MB/s 140 | test bench_from_iter_1000_std ... bench: 955 ns/iter (+/- 20) = 1047 MB/s 141 | test bench_from_slice_0000 ... bench: 18 ns/iter (+/- 0) 142 | test bench_from_slice_0000_std ... bench: 17 ns/iter (+/- 0) 143 | test bench_from_slice_0010 ... bench: 53 ns/iter (+/- 2) = 188 MB/s 144 | test bench_from_slice_0010_std ... bench: 51 ns/iter (+/- 1) = 196 MB/s 145 | test bench_from_slice_0100 ... bench: 163 ns/iter (+/- 4) = 613 MB/s 146 | test bench_from_slice_0100_std ... bench: 153 ns/iter (+/- 5) = 653 MB/s 147 | test bench_from_slice_1000 ... bench: 1,170 ns/iter (+/- 25) = 854 MB/s 148 | test bench_from_slice_1000_std ... bench: 1,192 ns/iter (+/- 188) = 838 MB/s 149 | test bench_new ... bench: 7 ns/iter (+/- 0) 150 | test bench_new_std ... bench: 2 ns/iter (+/- 0) 151 | test bench_push_all_0000_0000 ... bench: 17 ns/iter (+/- 1) 152 | test bench_push_all_0000_0000_std ... bench: 15 ns/iter (+/- 0) 153 | test bench_push_all_0000_0010 ... bench: 43 ns/iter (+/- 1) = 232 MB/s 154 | test bench_push_all_0000_0010_std ... bench: 41 ns/iter (+/- 1) = 243 MB/s 155 | test bench_push_all_0000_0100 ... bench: 130 ns/iter (+/- 3) = 769 MB/s 156 | test bench_push_all_0000_0100_std ... bench: 129 ns/iter (+/- 3) = 775 MB/s 157 | test bench_push_all_0000_1000 ... bench: 957 ns/iter (+/- 27) = 1044 MB/s 158 | test bench_push_all_0000_1000_std ... bench: 956 ns/iter (+/- 35) = 1046 MB/s 159 | test bench_push_all_0010_0010 ... bench: 116 ns/iter (+/- 2) = 86 MB/s 160 | test bench_push_all_0010_0010_std ... bench: 114 ns/iter (+/- 3) = 87 MB/s 161 | test bench_push_all_0100_0100 ... bench: 292 ns/iter (+/- 5) = 342 MB/s 162 | test bench_push_all_0100_0100_std ... bench: 287 ns/iter (+/- 6) = 348 MB/s 163 | test bench_push_all_1000_1000 ... bench: 1,926 ns/iter (+/- 60) = 519 MB/s 164 | test bench_push_all_1000_1000_std ... bench: 1,923 ns/iter (+/- 42) = 520 MB/s 165 | test bench_push_all_move_0000_0000 ... bench: 26 ns/iter (+/- 5) 166 | test bench_push_all_move_0000_0000_std ... bench: 25 ns/iter (+/- 2) 167 | test bench_push_all_move_0000_0010 ... bench: 70 ns/iter (+/- 3) = 142 MB/s 168 | test bench_push_all_move_0000_0010_std ... bench: 65 ns/iter (+/- 4) = 153 MB/s 169 | test bench_push_all_move_0000_0100 ... bench: 164 ns/iter (+/- 5) = 609 MB/s 170 | test bench_push_all_move_0000_0100_std ... bench: 175 ns/iter (+/- 3) = 571 MB/s 171 | test bench_push_all_move_0000_1000 ... bench: 1,165 ns/iter (+/- 25) = 858 MB/s 172 | test bench_push_all_move_0000_1000_std ... bench: 1,182 ns/iter (+/- 24) = 846 MB/s 173 | test bench_push_all_move_0010_0010 ... bench: 144 ns/iter (+/- 3) = 69 MB/s 174 | test bench_push_all_move_0010_0010_std ... bench: 134 ns/iter (+/- 10) = 74 MB/s 175 | test bench_push_all_move_0100_0100 ... bench: 335 ns/iter (+/- 10) = 298 MB/s 176 | test bench_push_all_move_0100_0100_std ... bench: 331 ns/iter (+/- 8) = 302 MB/s 177 | test bench_push_all_move_1000_1000 ... bench: 2,906 ns/iter (+/- 60) = 344 MB/s 178 | test bench_push_all_move_1000_1000_std ... bench: 2,975 ns/iter (+/- 85) = 336 MB/s 179 | test bench_with_capacity_0000 ... bench: 3 ns/iter (+/- 0) 180 | test bench_with_capacity_0000_std ... bench: 3 ns/iter (+/- 0) 181 | test bench_with_capacity_0010 ... bench: 17 ns/iter (+/- 1) = 588 MB/s 182 | test bench_with_capacity_0010_std ... bench: 30 ns/iter (+/- 0) = 333 MB/s 183 | test bench_with_capacity_0100 ... bench: 17 ns/iter (+/- 0) = 5882 MB/s 184 | test bench_with_capacity_0100_std ... bench: 30 ns/iter (+/- 1) = 3333 MB/s 185 | test bench_with_capacity_1000 ... bench: 38 ns/iter (+/- 5) = 26315 MB/s 186 | test bench_with_capacity_1000_std ... bench: 39 ns/iter (+/- 0) = 25641 MB/s 187 | ``` 188 | 189 | ## License 190 | 191 | Licensed under either of 192 | 193 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 194 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 195 | 196 | at your option. 197 | 198 | ### Contribution 199 | 200 | Unless you explicitly state otherwise, any contribution intentionally submitted 201 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall 202 | be dual licensed as above, without any additional terms or conditions. 203 | -------------------------------------------------------------------------------- /benches/bench.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | 3 | extern crate test; 4 | 5 | use std::iter::{repeat, FromIterator}; 6 | use test::{black_box, Bencher}; 7 | 8 | #[bench] 9 | fn bench_new(b: &mut Bencher) { 10 | b.iter(|| { 11 | let v: ve::Vec = black_box(ve::Vec::new()); 12 | assert_eq!(v.len(), 0); 13 | assert_eq!(v.capacity(), 0); 14 | }); 15 | } 16 | 17 | #[bench] 18 | fn bench_new_std(b: &mut Bencher) { 19 | b.iter(|| { 20 | let v: Vec = black_box(Vec::new()); 21 | assert_eq!(v.len(), 0); 22 | assert_eq!(v.capacity(), 0); 23 | }); 24 | } 25 | 26 | fn do_bench_with_capacity(b: &mut Bencher, src_len: usize) { 27 | b.bytes = src_len as u64; 28 | 29 | b.iter(|| { 30 | let v: ve::Vec = black_box(ve::Vec::with_capacity(src_len)); 31 | assert_eq!(v.len(), 0); 32 | assert_eq!(v.capacity(), src_len); 33 | }); 34 | } 35 | 36 | fn do_bench_with_capacity_std(b: &mut Bencher, src_len: usize) { 37 | b.bytes = src_len as u64; 38 | 39 | b.iter(|| { 40 | let v: Vec = black_box(Vec::with_capacity(src_len)); 41 | assert_eq!(v.len(), 0); 42 | assert_eq!(v.capacity(), src_len); 43 | }); 44 | } 45 | 46 | #[bench] 47 | fn bench_with_capacity_0000(b: &mut Bencher) { 48 | do_bench_with_capacity(b, 0) 49 | } 50 | 51 | #[bench] 52 | fn bench_with_capacity_0000_std(b: &mut Bencher) { 53 | do_bench_with_capacity_std(b, 0) 54 | } 55 | 56 | #[bench] 57 | fn bench_with_capacity_0010(b: &mut Bencher) { 58 | do_bench_with_capacity(b, 10) 59 | } 60 | 61 | #[bench] 62 | fn bench_with_capacity_0010_std(b: &mut Bencher) { 63 | do_bench_with_capacity_std(b, 10) 64 | } 65 | 66 | #[bench] 67 | fn bench_with_capacity_0100(b: &mut Bencher) { 68 | do_bench_with_capacity(b, 100) 69 | } 70 | 71 | #[bench] 72 | fn bench_with_capacity_0100_std(b: &mut Bencher) { 73 | do_bench_with_capacity_std(b, 100) 74 | } 75 | 76 | #[bench] 77 | fn bench_with_capacity_1000(b: &mut Bencher) { 78 | do_bench_with_capacity(b, 1000) 79 | } 80 | #[bench] 81 | fn bench_with_capacity_1000_std(b: &mut Bencher) { 82 | do_bench_with_capacity_std(b, 1000) 83 | } 84 | 85 | fn do_bench_from_fn(b: &mut Bencher, src_len: usize) { 86 | b.bytes = src_len as u64; 87 | 88 | b.iter(|| { 89 | let dst = (0..src_len).collect::>(); 90 | assert_eq!(dst.len(), src_len); 91 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 92 | }) 93 | } 94 | 95 | fn do_bench_from_fn_std(b: &mut Bencher, src_len: usize) { 96 | b.bytes = src_len as u64; 97 | 98 | b.iter(|| { 99 | let dst = (0..src_len).collect::>(); 100 | assert_eq!(dst.len(), src_len); 101 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 102 | }) 103 | } 104 | 105 | #[bench] 106 | fn bench_from_fn_0000(b: &mut Bencher) { 107 | do_bench_from_fn(b, 0) 108 | } 109 | 110 | #[bench] 111 | fn bench_from_fn_0000_std(b: &mut Bencher) { 112 | do_bench_from_fn_std(b, 0) 113 | } 114 | 115 | #[bench] 116 | fn bench_from_fn_0010(b: &mut Bencher) { 117 | do_bench_from_fn(b, 10) 118 | } 119 | 120 | #[bench] 121 | fn bench_from_fn_0010_std(b: &mut Bencher) { 122 | do_bench_from_fn_std(b, 10) 123 | } 124 | 125 | #[bench] 126 | fn bench_from_fn_0100(b: &mut Bencher) { 127 | do_bench_from_fn(b, 100) 128 | } 129 | 130 | #[bench] 131 | fn bench_from_fn_0100_std(b: &mut Bencher) { 132 | do_bench_from_fn_std(b, 100) 133 | } 134 | 135 | #[bench] 136 | fn bench_from_fn_1000(b: &mut Bencher) { 137 | do_bench_from_fn(b, 1000) 138 | } 139 | 140 | #[bench] 141 | fn bench_from_fn_1000_std(b: &mut Bencher) { 142 | do_bench_from_fn_std(b, 1000) 143 | } 144 | 145 | fn do_bench_from_elem(b: &mut Bencher, src_len: usize) { 146 | b.bytes = src_len as u64; 147 | 148 | b.iter(|| { 149 | let dst: ve::Vec = repeat(5).take(src_len).collect(); 150 | assert_eq!(dst.len(), src_len); 151 | assert!(dst.iter().all(|x| *x == 5)); 152 | }) 153 | } 154 | 155 | fn do_bench_from_elem_std(b: &mut Bencher, src_len: usize) { 156 | b.bytes = src_len as u64; 157 | 158 | b.iter(|| { 159 | let dst: Vec = repeat(5).take(src_len).collect(); 160 | assert_eq!(dst.len(), src_len); 161 | assert!(dst.iter().all(|x| *x == 5)); 162 | }) 163 | } 164 | 165 | #[bench] 166 | fn bench_from_elem_0000(b: &mut Bencher) { 167 | do_bench_from_elem(b, 0) 168 | } 169 | 170 | #[bench] 171 | fn bench_from_elem_0000_std(b: &mut Bencher) { 172 | do_bench_from_elem_std(b, 0) 173 | } 174 | 175 | #[bench] 176 | fn bench_from_elem_0010(b: &mut Bencher) { 177 | do_bench_from_elem(b, 10) 178 | } 179 | 180 | #[bench] 181 | fn bench_from_elem_0010_std(b: &mut Bencher) { 182 | do_bench_from_elem_std(b, 10) 183 | } 184 | 185 | #[bench] 186 | fn bench_from_elem_0100(b: &mut Bencher) { 187 | do_bench_from_elem(b, 100) 188 | } 189 | 190 | #[bench] 191 | fn bench_from_elem_0100_std(b: &mut Bencher) { 192 | do_bench_from_elem_std(b, 100) 193 | } 194 | 195 | #[bench] 196 | fn bench_from_elem_1000(b: &mut Bencher) { 197 | do_bench_from_elem(b, 1000) 198 | } 199 | 200 | #[bench] 201 | fn bench_from_elem_1000_std(b: &mut Bencher) { 202 | do_bench_from_elem_std(b, 1000) 203 | } 204 | 205 | fn do_bench_from_slice(b: &mut Bencher, src_len: usize) { 206 | let src: ve::Vec<_> = FromIterator::from_iter(0..src_len); 207 | 208 | b.bytes = src_len as u64; 209 | 210 | b.iter(|| { 211 | let dst = src.clone()[..].to_vec(); 212 | assert_eq!(dst.len(), src_len); 213 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 214 | }); 215 | } 216 | 217 | fn do_bench_from_slice_std(b: &mut Bencher, src_len: usize) { 218 | let src: Vec<_> = FromIterator::from_iter(0..src_len); 219 | 220 | b.bytes = src_len as u64; 221 | 222 | b.iter(|| { 223 | let dst = src.clone()[..].to_vec(); 224 | assert_eq!(dst.len(), src_len); 225 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 226 | }); 227 | } 228 | 229 | #[bench] 230 | fn bench_from_slice_0000(b: &mut Bencher) { 231 | do_bench_from_slice(b, 0) 232 | } 233 | 234 | #[bench] 235 | fn bench_from_slice_0000_std(b: &mut Bencher) { 236 | do_bench_from_slice_std(b, 0) 237 | } 238 | 239 | #[bench] 240 | fn bench_from_slice_0010(b: &mut Bencher) { 241 | do_bench_from_slice(b, 10) 242 | } 243 | 244 | #[bench] 245 | fn bench_from_slice_0010_std(b: &mut Bencher) { 246 | do_bench_from_slice_std(b, 10) 247 | } 248 | 249 | #[bench] 250 | fn bench_from_slice_0100(b: &mut Bencher) { 251 | do_bench_from_slice(b, 100) 252 | } 253 | 254 | #[bench] 255 | fn bench_from_slice_0100_std(b: &mut Bencher) { 256 | do_bench_from_slice_std(b, 100) 257 | } 258 | 259 | #[bench] 260 | fn bench_from_slice_1000(b: &mut Bencher) { 261 | do_bench_from_slice(b, 1000) 262 | } 263 | 264 | #[bench] 265 | fn bench_from_slice_1000_std(b: &mut Bencher) { 266 | do_bench_from_slice_std(b, 1000) 267 | } 268 | 269 | fn do_bench_from_iter(b: &mut Bencher, src_len: usize) { 270 | let src: ve::Vec<_> = FromIterator::from_iter(0..src_len); 271 | 272 | b.bytes = src_len as u64; 273 | 274 | b.iter(|| { 275 | let dst: Vec<_> = FromIterator::from_iter(src.clone()); 276 | assert_eq!(dst.len(), src_len); 277 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 278 | }); 279 | } 280 | 281 | fn do_bench_from_iter_std(b: &mut Bencher, src_len: usize) { 282 | let src: Vec<_> = FromIterator::from_iter(0..src_len); 283 | 284 | b.bytes = src_len as u64; 285 | 286 | b.iter(|| { 287 | let dst: Vec<_> = FromIterator::from_iter(src.clone()); 288 | assert_eq!(dst.len(), src_len); 289 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 290 | }); 291 | } 292 | 293 | #[bench] 294 | fn bench_from_iter_0000(b: &mut Bencher) { 295 | do_bench_from_iter(b, 0) 296 | } 297 | 298 | #[bench] 299 | fn bench_from_iter_0000_std(b: &mut Bencher) { 300 | do_bench_from_iter_std(b, 0) 301 | } 302 | 303 | #[bench] 304 | fn bench_from_iter_0010(b: &mut Bencher) { 305 | do_bench_from_iter(b, 10) 306 | } 307 | 308 | #[bench] 309 | fn bench_from_iter_0010_std(b: &mut Bencher) { 310 | do_bench_from_iter_std(b, 10) 311 | } 312 | 313 | #[bench] 314 | fn bench_from_iter_0100(b: &mut Bencher) { 315 | do_bench_from_iter(b, 100) 316 | } 317 | 318 | #[bench] 319 | fn bench_from_iter_0100_std(b: &mut Bencher) { 320 | do_bench_from_iter_std(b, 100) 321 | } 322 | 323 | #[bench] 324 | fn bench_from_iter_1000(b: &mut Bencher) { 325 | do_bench_from_iter(b, 1000) 326 | } 327 | 328 | #[bench] 329 | fn bench_from_iter_1000_std(b: &mut Bencher) { 330 | do_bench_from_iter_std(b, 1000) 331 | } 332 | 333 | fn do_bench_extend(b: &mut Bencher, dst_len: usize, src_len: usize) { 334 | let dst: ve::Vec<_> = FromIterator::from_iter(0..dst_len); 335 | let src: ve::Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); 336 | 337 | b.bytes = src_len as u64; 338 | 339 | b.iter(|| { 340 | let mut dst = dst.clone(); 341 | dst.extend(src.clone()); 342 | assert_eq!(dst.len(), dst_len + src_len); 343 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 344 | }); 345 | } 346 | 347 | fn do_bench_extend_std(b: &mut Bencher, dst_len: usize, src_len: usize) { 348 | let dst: Vec<_> = FromIterator::from_iter(0..dst_len); 349 | let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); 350 | 351 | b.bytes = src_len as u64; 352 | 353 | b.iter(|| { 354 | let mut dst = dst.clone(); 355 | dst.extend(src.clone()); 356 | assert_eq!(dst.len(), dst_len + src_len); 357 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 358 | }); 359 | } 360 | 361 | #[bench] 362 | fn bench_extend_0000_0000(b: &mut Bencher) { 363 | do_bench_extend(b, 0, 0) 364 | } 365 | 366 | #[bench] 367 | fn bench_extend_0000_0000_std(b: &mut Bencher) { 368 | do_bench_extend_std(b, 0, 0) 369 | } 370 | 371 | #[bench] 372 | fn bench_extend_0000_0010(b: &mut Bencher) { 373 | do_bench_extend(b, 0, 10) 374 | } 375 | 376 | #[bench] 377 | fn bench_extend_0000_0010_std(b: &mut Bencher) { 378 | do_bench_extend_std(b, 0, 10) 379 | } 380 | 381 | #[bench] 382 | fn bench_extend_0000_0100(b: &mut Bencher) { 383 | do_bench_extend(b, 0, 100) 384 | } 385 | 386 | #[bench] 387 | fn bench_extend_0000_0100_std(b: &mut Bencher) { 388 | do_bench_extend_std(b, 0, 100) 389 | } 390 | 391 | #[bench] 392 | fn bench_extend_0000_1000(b: &mut Bencher) { 393 | do_bench_extend(b, 0, 1000) 394 | } 395 | 396 | #[bench] 397 | fn bench_extend_0000_1000_std(b: &mut Bencher) { 398 | do_bench_extend_std(b, 0, 1000) 399 | } 400 | 401 | #[bench] 402 | fn bench_extend_0010_0010(b: &mut Bencher) { 403 | do_bench_extend(b, 10, 10) 404 | } 405 | 406 | #[bench] 407 | fn bench_extend_0010_0010_std(b: &mut Bencher) { 408 | do_bench_extend_std(b, 10, 10) 409 | } 410 | 411 | #[bench] 412 | fn bench_extend_0100_0100(b: &mut Bencher) { 413 | do_bench_extend(b, 100, 100) 414 | } 415 | 416 | #[bench] 417 | fn bench_extend_0100_0100_std(b: &mut Bencher) { 418 | do_bench_extend_std(b, 100, 100) 419 | } 420 | 421 | #[bench] 422 | fn bench_extend_1000_1000(b: &mut Bencher) { 423 | do_bench_extend(b, 1000, 1000) 424 | } 425 | 426 | #[bench] 427 | fn bench_extend_1000_1000_std(b: &mut Bencher) { 428 | do_bench_extend_std(b, 1000, 1000) 429 | } 430 | 431 | fn do_bench_extend_from_slice(b: &mut Bencher, dst_len: usize, src_len: usize) { 432 | let dst: ve::Vec<_> = FromIterator::from_iter(0..dst_len); 433 | let src: ve::Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); 434 | 435 | b.bytes = src_len as u64; 436 | 437 | b.iter(|| { 438 | let mut dst = dst.clone(); 439 | dst.extend_from_slice(&src); 440 | assert_eq!(dst.len(), dst_len + src_len); 441 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 442 | }); 443 | } 444 | 445 | fn do_bench_extend_from_slice_std(b: &mut Bencher, dst_len: usize, src_len: usize) { 446 | let dst: Vec<_> = FromIterator::from_iter(0..dst_len); 447 | let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); 448 | 449 | b.bytes = src_len as u64; 450 | 451 | b.iter(|| { 452 | let mut dst = dst.clone(); 453 | dst.extend_from_slice(&src); 454 | assert_eq!(dst.len(), dst_len + src_len); 455 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 456 | }); 457 | } 458 | 459 | #[bench] 460 | fn bench_extend_from_slice_0000_0000(b: &mut Bencher) { 461 | do_bench_extend_from_slice(b, 0, 0) 462 | } 463 | 464 | #[bench] 465 | fn bench_extend_from_slice_0000_0000_std(b: &mut Bencher) { 466 | do_bench_extend_from_slice_std(b, 0, 0) 467 | } 468 | 469 | #[bench] 470 | fn bench_extend_from_slice_0000_0010(b: &mut Bencher) { 471 | do_bench_extend_from_slice(b, 0, 10) 472 | } 473 | 474 | #[bench] 475 | fn bench_extend_from_slice_0000_0010_std(b: &mut Bencher) { 476 | do_bench_extend_from_slice_std(b, 0, 10) 477 | } 478 | 479 | #[bench] 480 | fn bench_extend_from_slice_0000_0100(b: &mut Bencher) { 481 | do_bench_extend_from_slice(b, 0, 100) 482 | } 483 | 484 | #[bench] 485 | fn bench_extend_from_slice_0000_0100_std(b: &mut Bencher) { 486 | do_bench_extend_from_slice_std(b, 0, 100) 487 | } 488 | 489 | #[bench] 490 | fn bench_extend_from_slice_0000_1000(b: &mut Bencher) { 491 | do_bench_extend_from_slice(b, 0, 1000) 492 | } 493 | 494 | #[bench] 495 | fn bench_extend_from_slice_0000_1000_std(b: &mut Bencher) { 496 | do_bench_extend_from_slice_std(b, 0, 1000) 497 | } 498 | 499 | #[bench] 500 | fn bench_extend_from_slice_0010_0010(b: &mut Bencher) { 501 | do_bench_extend_from_slice(b, 10, 10) 502 | } 503 | 504 | #[bench] 505 | fn bench_extend_from_slice_0010_0010_std(b: &mut Bencher) { 506 | do_bench_extend_from_slice_std(b, 10, 10) 507 | } 508 | 509 | #[bench] 510 | fn bench_extend_from_slice_0100_0100(b: &mut Bencher) { 511 | do_bench_extend_from_slice(b, 100, 100) 512 | } 513 | 514 | #[bench] 515 | fn bench_extend_from_slice_0100_0100_std(b: &mut Bencher) { 516 | do_bench_extend_from_slice_std(b, 100, 100) 517 | } 518 | 519 | #[bench] 520 | fn bench_extend_from_slice_1000_1000(b: &mut Bencher) { 521 | do_bench_extend_from_slice(b, 1000, 1000) 522 | } 523 | 524 | #[bench] 525 | fn bench_extend_from_slice_1000_1000_std(b: &mut Bencher) { 526 | do_bench_extend_from_slice_std(b, 1000, 1000) 527 | } 528 | 529 | fn do_bench_clone(b: &mut Bencher, src_len: usize) { 530 | let src: ve::Vec<_> = FromIterator::from_iter(0..src_len); 531 | 532 | b.bytes = src_len as u64; 533 | 534 | b.iter(|| { 535 | let dst = src.clone(); 536 | assert_eq!(dst.len(), src_len); 537 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 538 | }); 539 | } 540 | 541 | fn do_bench_clone_std(b: &mut Bencher, src_len: usize) { 542 | let src: Vec<_> = FromIterator::from_iter(0..src_len); 543 | 544 | b.bytes = src_len as u64; 545 | 546 | b.iter(|| { 547 | let dst = src.clone(); 548 | assert_eq!(dst.len(), src_len); 549 | assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); 550 | }); 551 | } 552 | 553 | #[bench] 554 | fn bench_clone_0000(b: &mut Bencher) { 555 | do_bench_clone(b, 0) 556 | } 557 | 558 | #[bench] 559 | fn bench_clone_0000_std(b: &mut Bencher) { 560 | do_bench_clone_std(b, 0) 561 | } 562 | 563 | #[bench] 564 | fn bench_clone_0010(b: &mut Bencher) { 565 | do_bench_clone(b, 10) 566 | } 567 | 568 | #[bench] 569 | fn bench_clone_0010_std(b: &mut Bencher) { 570 | do_bench_clone_std(b, 10) 571 | } 572 | 573 | #[bench] 574 | fn bench_clone_0100(b: &mut Bencher) { 575 | do_bench_clone(b, 100) 576 | } 577 | 578 | #[bench] 579 | fn bench_clone_0100_std(b: &mut Bencher) { 580 | do_bench_clone_std(b, 100) 581 | } 582 | 583 | #[bench] 584 | fn bench_clone_1000(b: &mut Bencher) { 585 | do_bench_clone(b, 1000) 586 | } 587 | 588 | #[bench] 589 | fn bench_clone_1000_std(b: &mut Bencher) { 590 | do_bench_clone_std(b, 1000) 591 | } 592 | 593 | fn do_bench_clone_from(b: &mut Bencher, times: usize, dst_len: usize, src_len: usize) { 594 | let dst: ve::Vec<_> = FromIterator::from_iter(0..src_len); 595 | let src: ve::Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); 596 | 597 | b.bytes = (times * src_len) as u64; 598 | 599 | b.iter(|| { 600 | let mut dst = dst.clone(); 601 | 602 | for _ in 0..times { 603 | dst.clone_from(&src); 604 | 605 | assert_eq!(dst.len(), src_len); 606 | assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x)); 607 | } 608 | }); 609 | } 610 | 611 | fn do_bench_clone_from_std(b: &mut Bencher, times: usize, dst_len: usize, src_len: usize) { 612 | let dst: Vec<_> = FromIterator::from_iter(0..src_len); 613 | let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len); 614 | 615 | b.bytes = (times * src_len) as u64; 616 | 617 | b.iter(|| { 618 | let mut dst = dst.clone(); 619 | 620 | for _ in 0..times { 621 | dst.clone_from(&src); 622 | 623 | assert_eq!(dst.len(), src_len); 624 | assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x)); 625 | } 626 | }); 627 | } 628 | 629 | #[bench] 630 | fn bench_clone_from_01_0000_0000(b: &mut Bencher) { 631 | do_bench_clone_from(b, 1, 0, 0) 632 | } 633 | 634 | #[bench] 635 | fn bench_clone_from_01_0000_0000_std(b: &mut Bencher) { 636 | do_bench_clone_from_std(b, 1, 0, 0) 637 | } 638 | 639 | #[bench] 640 | fn bench_clone_from_01_0000_0010(b: &mut Bencher) { 641 | do_bench_clone_from(b, 1, 0, 10) 642 | } 643 | 644 | #[bench] 645 | fn bench_clone_from_01_0000_0010_std(b: &mut Bencher) { 646 | do_bench_clone_from_std(b, 1, 0, 10) 647 | } 648 | 649 | #[bench] 650 | fn bench_clone_from_01_0000_0100(b: &mut Bencher) { 651 | do_bench_clone_from(b, 1, 0, 100) 652 | } 653 | 654 | #[bench] 655 | fn bench_clone_from_01_0000_0100_std(b: &mut Bencher) { 656 | do_bench_clone_from_std(b, 1, 0, 100) 657 | } 658 | 659 | #[bench] 660 | fn bench_clone_from_01_0000_1000(b: &mut Bencher) { 661 | do_bench_clone_from(b, 1, 0, 1000) 662 | } 663 | 664 | #[bench] 665 | fn bench_clone_from_01_0000_1000_std(b: &mut Bencher) { 666 | do_bench_clone_from_std(b, 1, 0, 1000) 667 | } 668 | 669 | #[bench] 670 | fn bench_clone_from_01_0010_0010(b: &mut Bencher) { 671 | do_bench_clone_from(b, 1, 10, 10) 672 | } 673 | 674 | #[bench] 675 | fn bench_clone_from_01_0010_0010_std(b: &mut Bencher) { 676 | do_bench_clone_from_std(b, 1, 10, 10) 677 | } 678 | 679 | #[bench] 680 | fn bench_clone_from_01_0100_0100(b: &mut Bencher) { 681 | do_bench_clone_from(b, 1, 100, 100) 682 | } 683 | 684 | #[bench] 685 | fn bench_clone_from_01_0100_0100_std(b: &mut Bencher) { 686 | do_bench_clone_from_std(b, 1, 100, 100) 687 | } 688 | 689 | #[bench] 690 | fn bench_clone_from_01_1000_1000(b: &mut Bencher) { 691 | do_bench_clone_from(b, 1, 1000, 1000) 692 | } 693 | 694 | #[bench] 695 | fn bench_clone_from_01_1000_1000_std(b: &mut Bencher) { 696 | do_bench_clone_from_std(b, 1, 1000, 1000) 697 | } 698 | 699 | #[bench] 700 | fn bench_clone_from_01_0010_0100(b: &mut Bencher) { 701 | do_bench_clone_from(b, 1, 10, 100) 702 | } 703 | 704 | #[bench] 705 | fn bench_clone_from_01_0010_0100_std(b: &mut Bencher) { 706 | do_bench_clone_from_std(b, 1, 10, 100) 707 | } 708 | 709 | #[bench] 710 | fn bench_clone_from_01_0100_1000(b: &mut Bencher) { 711 | do_bench_clone_from(b, 1, 100, 1000) 712 | } 713 | 714 | #[bench] 715 | fn bench_clone_from_01_0100_1000_std(b: &mut Bencher) { 716 | do_bench_clone_from_std(b, 1, 100, 1000) 717 | } 718 | 719 | #[bench] 720 | fn bench_clone_from_01_0010_0000(b: &mut Bencher) { 721 | do_bench_clone_from(b, 1, 10, 0) 722 | } 723 | 724 | #[bench] 725 | fn bench_clone_from_01_0010_0000_std(b: &mut Bencher) { 726 | do_bench_clone_from_std(b, 1, 10, 0) 727 | } 728 | 729 | #[bench] 730 | fn bench_clone_from_01_0100_0010(b: &mut Bencher) { 731 | do_bench_clone_from(b, 1, 100, 10) 732 | } 733 | 734 | #[bench] 735 | fn bench_clone_from_01_0100_0010_std(b: &mut Bencher) { 736 | do_bench_clone_from_std(b, 1, 100, 10) 737 | } 738 | 739 | #[bench] 740 | fn bench_clone_from_01_1000_0100(b: &mut Bencher) { 741 | do_bench_clone_from(b, 1, 1000, 100) 742 | } 743 | 744 | #[bench] 745 | fn bench_clone_from_01_1000_0100_std(b: &mut Bencher) { 746 | do_bench_clone_from_std(b, 1, 1000, 100) 747 | } 748 | 749 | #[bench] 750 | fn bench_clone_from_10_0000_0000(b: &mut Bencher) { 751 | do_bench_clone_from(b, 10, 0, 0) 752 | } 753 | 754 | #[bench] 755 | fn bench_clone_from_10_0000_0000_std(b: &mut Bencher) { 756 | do_bench_clone_from_std(b, 10, 0, 0) 757 | } 758 | 759 | #[bench] 760 | fn bench_clone_from_10_0000_0010(b: &mut Bencher) { 761 | do_bench_clone_from(b, 10, 0, 10) 762 | } 763 | 764 | #[bench] 765 | fn bench_clone_from_10_0000_0010_std(b: &mut Bencher) { 766 | do_bench_clone_from_std(b, 10, 0, 10) 767 | } 768 | 769 | #[bench] 770 | fn bench_clone_from_10_0000_0100(b: &mut Bencher) { 771 | do_bench_clone_from(b, 10, 0, 100) 772 | } 773 | 774 | #[bench] 775 | fn bench_clone_from_10_0000_0100_std(b: &mut Bencher) { 776 | do_bench_clone_from_std(b, 10, 0, 100) 777 | } 778 | 779 | #[bench] 780 | fn bench_clone_from_10_0000_1000(b: &mut Bencher) { 781 | do_bench_clone_from(b, 10, 0, 1000) 782 | } 783 | 784 | #[bench] 785 | fn bench_clone_from_10_0000_1000_std(b: &mut Bencher) { 786 | do_bench_clone_from_std(b, 10, 0, 1000) 787 | } 788 | 789 | #[bench] 790 | fn bench_clone_from_10_0010_0010(b: &mut Bencher) { 791 | do_bench_clone_from(b, 10, 10, 10) 792 | } 793 | 794 | #[bench] 795 | fn bench_clone_from_10_0010_0010_std(b: &mut Bencher) { 796 | do_bench_clone_from_std(b, 10, 10, 10) 797 | } 798 | 799 | #[bench] 800 | fn bench_clone_from_10_0100_0100(b: &mut Bencher) { 801 | do_bench_clone_from(b, 10, 100, 100) 802 | } 803 | 804 | #[bench] 805 | fn bench_clone_from_10_0100_0100_std(b: &mut Bencher) { 806 | do_bench_clone_from_std(b, 10, 100, 100) 807 | } 808 | 809 | #[bench] 810 | fn bench_clone_from_10_1000_1000(b: &mut Bencher) { 811 | do_bench_clone_from(b, 10, 1000, 1000) 812 | } 813 | 814 | #[bench] 815 | fn bench_clone_from_10_1000_1000_std(b: &mut Bencher) { 816 | do_bench_clone_from_std(b, 10, 1000, 1000) 817 | } 818 | 819 | #[bench] 820 | fn bench_clone_from_10_0010_0100(b: &mut Bencher) { 821 | do_bench_clone_from(b, 10, 10, 100) 822 | } 823 | 824 | #[bench] 825 | fn bench_clone_from_10_0010_0100_std(b: &mut Bencher) { 826 | do_bench_clone_from_std(b, 10, 10, 100) 827 | } 828 | 829 | #[bench] 830 | fn bench_clone_from_10_0100_1000(b: &mut Bencher) { 831 | do_bench_clone_from(b, 10, 100, 1000) 832 | } 833 | 834 | #[bench] 835 | fn bench_clone_from_10_0100_1000_std(b: &mut Bencher) { 836 | do_bench_clone_from_std(b, 10, 100, 1000) 837 | } 838 | 839 | #[bench] 840 | fn bench_clone_from_10_0010_0000(b: &mut Bencher) { 841 | do_bench_clone_from(b, 10, 10, 0) 842 | } 843 | 844 | #[bench] 845 | fn bench_clone_from_10_0010_0000_std(b: &mut Bencher) { 846 | do_bench_clone_from_std(b, 10, 10, 0) 847 | } 848 | 849 | #[bench] 850 | fn bench_clone_from_10_0100_0010(b: &mut Bencher) { 851 | do_bench_clone_from(b, 10, 100, 10) 852 | } 853 | 854 | #[bench] 855 | fn bench_clone_from_10_0100_0010_std(b: &mut Bencher) { 856 | do_bench_clone_from_std(b, 10, 100, 10) 857 | } 858 | 859 | #[bench] 860 | fn bench_clone_from_10_1000_0100(b: &mut Bencher) { 861 | do_bench_clone_from(b, 10, 1000, 100) 862 | } 863 | 864 | #[bench] 865 | fn bench_clone_from_10_1000_0100_std(b: &mut Bencher) { 866 | do_bench_clone_from_std(b, 10, 1000, 100) 867 | } 868 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Faster, more compact implementation of `Vec`. 2 | //! 3 | //! ```rust 4 | //! use std::mem::size_of; 5 | //! use ve::Vec; 6 | //! 7 | //! const WORD: usize = size_of::(); 8 | //! 9 | //! assert_eq!(size_of::>(), 2 * WORD); 10 | //! ``` 11 | #![allow(incomplete_features)] 12 | #![deny(unsafe_op_in_unsafe_fn)] 13 | #![feature(allocator_api)] 14 | #![feature(allow_internal_unstable)] 15 | #![feature(const_fn)] 16 | #![feature(const_generics)] 17 | #![feature(core_intrinsics)] 18 | #![feature(exact_size_is_empty)] 19 | #![feature(dropck_eyepatch)] 20 | #![feature(new_uninit)] 21 | #![feature(slice_partition_dedup)] 22 | #![feature(slice_ptr_len)] 23 | #![feature(min_specialization)] 24 | #![feature(rustc_attrs)] 25 | #![feature(trusted_len)] 26 | #![feature(try_reserve)] 27 | #![feature(unsafe_block_in_unsafe_fn)] 28 | #![warn(missing_docs)] 29 | #![no_std] 30 | extern crate alloc; 31 | 32 | // Module with internal macros used by other modules (needs to be included before other modules). 33 | #[macro_use] 34 | mod macros; 35 | 36 | pub mod raw_vec; 37 | pub mod slice; 38 | pub mod vec; 39 | 40 | pub use crate::vec::Vec; 41 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | /// Creates a [`Vec`] containing the arguments. 2 | /// 3 | /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions. 4 | /// There are two forms of this macro: 5 | /// 6 | /// - Create a [`Vec`] containing a given list of elements: 7 | /// 8 | /// ``` 9 | /// let v = vec![1, 2, 3]; 10 | /// assert_eq!(v[0], 1); 11 | /// assert_eq!(v[1], 2); 12 | /// assert_eq!(v[2], 3); 13 | /// ``` 14 | /// 15 | /// - Create a [`Vec`] from a given element and size: 16 | /// 17 | /// ``` 18 | /// let v = vec![1; 3]; 19 | /// assert_eq!(v, [1, 1, 1]); 20 | /// ``` 21 | /// 22 | /// Note that unlike array expressions this syntax supports all elements which implements [`Clone`] 23 | /// and the number of elements doesn't have to be a constant. 24 | /// 25 | /// This will use `clone` to duplicate an expression, so one should be careful when using this with 26 | /// types having a nonstandard `Clone` implementation. For example, `vec!![Rc::new(1); 5]` will 27 | /// create a vector of five references to the same boxed integer value, not five references 28 | /// pointing to independently boxed integers. 29 | /// 30 | /// [`Vec`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html 31 | /// [`Clone`]: https://doc.rust-lang.org/stable/std/clone/trait.Clone.html 32 | #[macro_export] 33 | #[allow_internal_unstable(box_syntax)] 34 | macro_rules! vec { 35 | () => ( 36 | $crate::vec::Vec::new() 37 | ); 38 | ($elem:expr; $n:expr) => ( 39 | $crate::vec::from_elem($elem, $n) 40 | ); 41 | ($($x:expr),*) => ( 42 | $crate::slice::into_vec(box [$($x),+]) 43 | ); 44 | ($($x:expr,)*) => (vec![$($x),*]) 45 | } 46 | -------------------------------------------------------------------------------- /src/raw_vec.rs: -------------------------------------------------------------------------------- 1 | #![doc(hidden)] 2 | 3 | /// Implementation details for `Vec`. 4 | use core::alloc::{AllocRef, Layout, LayoutErr}; 5 | use core::mem::{self, ManuallyDrop, MaybeUninit}; 6 | use core::ptr::NonNull; 7 | use core::{cmp, intrinsics, slice}; 8 | 9 | use alloc::alloc::{handle_alloc_error, Global}; 10 | use alloc::boxed::Box; 11 | use alloc::collections::TryReserveError::{self, *}; 12 | 13 | pub(crate) const MASK_LO: usize = u32::MAX as usize; // len 14 | pub(crate) const MASK_HI: usize = !MASK_LO; // cap 15 | 16 | enum AllocInit { 17 | /// The contents of the new memory are uninitialized. 18 | Uninitialized, 19 | /// The new memory is guaranteed to be zeroed. 20 | Zeroed, 21 | } 22 | 23 | /// A low-level utility for more ergonomically allocating, reallocating, and deallocating a buffer 24 | /// of memory on the heap without having to worry about all the corner cases involved. This type is 25 | /// excellent for building your own data structures like Vec and Veque. In particular: 26 | /// 27 | /// * Produces `NonNull::danging()` on zero-sized types. 28 | /// * Produces `NonNull::danglng()` on zero-length allocations. 29 | /// * Avoid freeing `NonNull::dangling()`. 30 | /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics). 31 | /// * Guards against 32-bit systems allocating more than isize::MAX bytes. 32 | /// * Guards against overflowing your length. 33 | /// * Calls `handle_alloc_error` for fallible allocations. 34 | /// * Contains a `ptr::Unique` and thus endows the user with all related benefits. 35 | /// * Uses the excess returned from the allocator to use the largest available capacity. 36 | /// 37 | /// This type does not in anyway inspect the memory that it manages. When dropped it *will* free 38 | /// its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec` to handle 39 | /// the actual things *stored* inside of a `RawVec`. 40 | /// 41 | /// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns 42 | /// `usize::MAX`. This means that you need to be careful when round-tripping this type with a 43 | /// `Box<[T]>`, since `capacity()` won't yield the length. 44 | #[allow(missing_debug_implementations)] 45 | pub struct RawVec { 46 | ptr: NonNull, 47 | /// Consists of `cap` and `len`. 48 | fat: usize, 49 | alloc: A, 50 | } 51 | 52 | impl RawVec { 53 | /// Creates the biggest possible `RawVec` (on the system heap) without allocating. If `T` has 54 | /// positive size, then this makes a `RawVec` with capacity `0`. If `T` is zero-sized, then it 55 | /// makes a `RawVec` with capacity `usize::MAX`. Useful for implementing delayed allocation. 56 | pub const fn new() -> Self { 57 | Self::new_in(Global) 58 | } 59 | 60 | /// Creates a `RawVec` (on the system heap) with exactly the capacity and alignment 61 | /// requirements for a `[T; capacity]`. This is equivalent to calling `RawVec::new` when 62 | /// `capacity` is `0` or `T` is zero-sized. Note that if `T` is zero-sized this means you will 63 | /// *not* get a `RawVec` with the requested capacity. 64 | /// 65 | /// # Panics 66 | /// 67 | /// Panics if the requested capacity exceeds `isize::MAX` bytes. 68 | /// 69 | /// # Aborts 70 | /// 71 | /// Aborts on OOM. 72 | #[inline] 73 | pub fn with_capacity(capacity: usize) -> Self { 74 | Self::with_capacity_in(capacity, Global) 75 | } 76 | 77 | /// Like `with_capacity`, but guarantees the buffer is zeroed. 78 | #[inline] 79 | pub fn with_capacity_zeroed(capacity: usize) -> Self { 80 | Self::with_capacity_zeroed_in(capacity, Global) 81 | } 82 | 83 | /// Reconstitutes a `RawVec` from a pointer, capacity and length. 84 | /// 85 | /// # Safety 86 | /// 87 | /// The `ptr` must be allocated (on the system heap), and with the given `capacity`. 88 | /// The `capacity` cannot exceed `u32::MAX` for sized types. ZST vectors may have capacity up to 89 | /// `usize::MAX`. 90 | /// If the `ptr` and `capacity` come from a `RawVec`, then this is guaranteed. 91 | #[inline] 92 | pub unsafe fn from_raw_parts(ptr: *mut T, capacity: usize, len: usize) -> Self { 93 | unsafe { Self::from_raw_parts_in(ptr, capacity, len, Global) } 94 | } 95 | 96 | /// Converts a `Box` into a `RawVec`. 97 | pub fn from_box(slice: Box<[T]>) -> Self { 98 | unsafe { 99 | let mut slice = ManuallyDrop::new(slice); 100 | RawVec::from_raw_parts(slice.as_mut_ptr(), slice.len(), slice.len()) 101 | } 102 | } 103 | 104 | /// Converts the entire buffer into `Box<[MaybeUninit]>` with the specified `len`. 105 | /// 106 | /// Note that this will correctly reconstitute any `cap` change that may have been performed. 107 | /// (See description of type for details.) 108 | /// 109 | /// # Safety 110 | /// 111 | /// * `len` must be greater than or equal to the most recently requested capacity, and 112 | /// * `len` must be less than or equal to `self.capacity()` 113 | /// 114 | /// Note, that the requested capacity and `self.capacity()` could differ, as an allocator could 115 | /// overallocate and return a greater memory block than requested. 116 | pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit]> { 117 | // Sanity-check on half of safety requirement (we cannot check the other half). 118 | debug_assert!( 119 | len <= self.capacity(), 120 | "`len` must be smaller or equal to `self.capacity()`" 121 | ); 122 | 123 | let me = ManuallyDrop::new(self); 124 | unsafe { 125 | let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit, len); 126 | Box::from_raw(slice) 127 | } 128 | } 129 | } 130 | 131 | impl RawVec { 132 | /// Like `new`, but parameterized over the choice of allocator for the 133 | /// returned `RawVec`. 134 | pub const fn new_in(alloc: A) -> Self { 135 | // `fat: 0` means "unallocated", zero-sized types are ignored. 136 | Self { 137 | ptr: NonNull::dangling(), 138 | fat: 0, 139 | alloc, 140 | } 141 | } 142 | 143 | /// Like `with_capacity`, but parameterized over the choice of allocator for the returned 144 | /// `RawVec`. 145 | #[inline] 146 | pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 147 | Self::allocate_in(capacity, 0, AllocInit::Uninitialized, alloc) 148 | } 149 | 150 | /// Like `with_capacity_zeroed`, but parameterized over the choice of allocator for the 151 | /// returned `RawVec`. 152 | #[inline] 153 | pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { 154 | Self::allocate_in(capacity, capacity, AllocInit::Zeroed, alloc) 155 | } 156 | 157 | fn allocate_in(capacity: usize, len: usize, init: AllocInit, mut alloc: A) -> Self { 158 | if mem::size_of::() == 0 { 159 | Self::new_in(alloc) 160 | } else { 161 | // We avoid `unwrap_or_else` here because it bloats the amount of LLVM IR generated. 162 | let layout = match Layout::array::(capacity) { 163 | Ok(layout) => layout, 164 | Err(_) => capacity_overflow(), 165 | }; 166 | match alloc_guard(layout.size()) { 167 | Ok(_) => {} 168 | Err(_) => capacity_overflow(), 169 | } 170 | let result = match init { 171 | AllocInit::Uninitialized => alloc.alloc(layout), 172 | AllocInit::Zeroed => alloc.alloc_zeroed(layout), 173 | }; 174 | let ptr = match result { 175 | Ok(ptr) => ptr, 176 | Err(_) => handle_alloc_error(layout), 177 | }; 178 | 179 | Self { 180 | ptr: ptr.cast(), 181 | // Safety: No need for MASK_LO, already checked from alloc_guard 182 | fat: Self::capacity_from_bytes(ptr.len()) << 32 | len, 183 | alloc, 184 | } 185 | } 186 | } 187 | 188 | /// Reconstitutes a `RawVec` from a pointer, capacity, length and allocator. 189 | /// 190 | /// # Safety 191 | /// 192 | /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given 193 | /// `capacity`. 194 | /// The `capacity` cannot exceed `u32::MAX` for sized types. ZST vectors may have a capacity up 195 | /// to `usize::MAX`. 196 | /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is 197 | /// guaranteed. 198 | #[inline] 199 | pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, length: usize, alloc: A) -> Self { 200 | Self { 201 | ptr: unsafe { NonNull::new_unchecked(ptr) }, 202 | fat: (capacity & MASK_LO) << 32 | length & MASK_LO, 203 | alloc, 204 | } 205 | } 206 | 207 | /// Gets a raw pointer to the start of the allocation. Note that this is `NonNull::dangling()` 208 | /// if `capacity == 0` or `T` is zero-sized. In the former case, you must be careful. 209 | pub fn ptr(&self) -> *mut T { 210 | self.ptr.as_ptr() 211 | } 212 | 213 | /// Gets the capacity of the allocation. 214 | /// 215 | /// This will always be `usize::MAX` if `T` is zero-sized. 216 | #[inline(always)] 217 | pub fn capacity(&self) -> usize { 218 | if mem::size_of::() == 0 { 219 | usize::MAX 220 | } else { 221 | (self.fat & MASK_HI) >> 32 222 | } 223 | } 224 | 225 | /// Gets the length of the allocation. 226 | pub fn len(&self) -> usize { 227 | self.fat & MASK_LO 228 | } 229 | 230 | /// Set the length of the allocation. 231 | pub fn set_len(&mut self, len: usize) { 232 | self.fat = self.fat & MASK_HI | len & MASK_LO; 233 | } 234 | 235 | /// Returns a mutable reference to fat. 236 | pub fn fat_mut(&mut self) -> &mut usize { 237 | &mut self.fat 238 | } 239 | 240 | /// Returns a shared reference to the allocator backing this `RawVec`. 241 | pub fn alloc(&self) -> &A { 242 | &self.alloc 243 | } 244 | 245 | /// Returns a mutable reference to the allocator backing this `RawVec`. 246 | pub fn alloc_mut(&mut self) -> &mut A { 247 | &mut self.alloc 248 | } 249 | 250 | fn current_memory(&self) -> Option<(NonNull, Layout)> { 251 | if mem::size_of::() == 0 || self.capacity() == 0 { 252 | None 253 | } else { 254 | // We have allocated chunk of memory, so we can bypass runtime checks to get our 255 | // current layout. 256 | unsafe { 257 | let align = mem::align_of::(); 258 | let size = mem::size_of::() * self.capacity(); 259 | let layout = Layout::from_size_align_unchecked(size, align); 260 | Some((self.ptr.cast(), layout)) 261 | } 262 | } 263 | } 264 | 265 | /// Ensures that the buffer contains at least enough space to hold `len + additional` elements. 266 | /// If it doesn't already have enough capacity, will reallocate enough space plus comfortable 267 | /// slack space to get amortized `O(1)` behavior. Will limit this behavior if it would 268 | /// needlessly cause itself to panic. 269 | /// 270 | /// If `len` exceeds `self.capacity()`, this may fail to actually allocate the requested space. 271 | /// This is not really unsafe, but the unsafe code *you* write that relies on the behavior of 272 | /// this function may break. 273 | /// 274 | /// This is ideal for implementing a bulk-push operation like `extend`. 275 | /// 276 | /// # Panics 277 | /// 278 | /// Panics if the new capacity exceeds `isize::MAX` bytes. 279 | /// 280 | /// # Aborts 281 | /// 282 | /// Aborts on OOM. 283 | pub fn reserve(&mut self, len: usize, additional: usize) { 284 | match self.try_reserve(len, additional) { 285 | Err(CapacityOverflow) => capacity_overflow(), 286 | Err(AllocError { layout, .. }) => handle_alloc_error(layout), 287 | Ok(()) => { /* yay */ } 288 | } 289 | } 290 | 291 | /// The same as `reserve`, but returns on errors instead of panicking or aborting. 292 | pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { 293 | if self.needs_to_grow(len, additional) { 294 | self.grow_amortized(len, additional) 295 | } else { 296 | Ok(()) 297 | } 298 | } 299 | 300 | /// Ensures that the buffer contains at least enough space to hold `len + additional` elements. 301 | /// If it doesn't already, will reallocate the minimum possible ammount of memory necessary. 302 | /// Generally this will be exactly the amount of memory necessary, but in principle the 303 | /// allocator is free to give back more than what we asked for. 304 | /// 305 | /// If `len` exceeds `self.capacity()`, this may fail to actually allocate the requested space. 306 | /// This is not really unsafe, but the unsafe code *you* write that relies on the behavior of 307 | /// this function may break. 308 | /// 309 | /// # Panics 310 | /// 311 | /// Panics if the new capacity exceeds `isize::MAX` bytes. 312 | /// 313 | /// # Aborts 314 | /// 315 | /// Aborts on OOM. 316 | pub fn reserve_exact(&mut self, len: usize, additional: usize) { 317 | match self.try_reserve_exact(len, additional) { 318 | Err(CapacityOverflow) => capacity_overflow(), 319 | Err(AllocError { layout, .. }) => handle_alloc_error(layout), 320 | Ok(()) => { /* yay */ } 321 | } 322 | } 323 | 324 | /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. 325 | pub fn try_reserve_exact( 326 | &mut self, 327 | len: usize, 328 | additional: usize, 329 | ) -> Result<(), TryReserveError> { 330 | if self.needs_to_grow(len, additional) { 331 | self.grow_exact(len, additional) 332 | } else { 333 | Ok(()) 334 | } 335 | } 336 | 337 | /// Shrinks the allocation down to the specified amount. If the given amount is 0, actually 338 | /// completely deallocates. 339 | /// 340 | /// # Panics 341 | /// 342 | /// Panics if the given amount is *larger* than the current capacity. 343 | /// 344 | /// # Aborts 345 | /// 346 | /// Aborts on OOM. 347 | pub(crate) fn shrink_to_fit(&mut self, amount: usize) { 348 | match self.shrink(amount) { 349 | Err(CapacityOverflow) => capacity_overflow(), 350 | Err(AllocError { layout, .. }) => handle_alloc_error(layout), 351 | Ok(()) => { /* yay */ } 352 | } 353 | } 354 | } 355 | 356 | impl RawVec { 357 | /// Returns if the buffer needs to grow to fulfill the needed extra capacity. 358 | /// Mainly used to make inlining reserve-calls possible without inlining `grow`. 359 | fn needs_to_grow(&self, len: usize, additional: usize) -> bool { 360 | additional > self.capacity().wrapping_sub(len) 361 | } 362 | 363 | fn capacity_from_bytes(excess: usize) -> usize { 364 | debug_assert_ne!(mem::size_of::(), 0); 365 | excess / mem::size_of::() 366 | } 367 | 368 | fn set_ptr(&mut self, ptr: NonNull<[u8]>) { 369 | self.ptr = ptr.cast(); 370 | self.fat = (ptr.len() & MASK_LO) << 32 | self.fat & MASK_LO; 371 | } 372 | 373 | /// This method is usually instantiated many times. So we want it to be as small as possible, 374 | /// to improve compile times. But we also want as much of generated code to run faster. 375 | /// Therefore, this method is carefully written so that all the code that depends on `T` is 376 | /// within it, while as much of the code that doesn't depend on `T` as possible is in functions 377 | /// that are non-generic over `T`. 378 | fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { 379 | // This is ensured by the calling contexts. 380 | debug_assert!(additional > 0); 381 | 382 | if mem::size_of::() == 0 { 383 | // Since we return a capacity of `u32::MAX` when `elem_size` is 0, getting to here 384 | // necessarily means the `RawVec` is overfull. 385 | return Err(CapacityOverflow); 386 | } 387 | 388 | // Nothing we can really do about these checks, sadly. 389 | let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; 390 | 391 | // This guarantees exponential growth. The doubling cannot overflow because 392 | // `cap <= isize::MAX` and the type of `cap` is `u32`. 393 | let cap = cmp::max(self.capacity() * 2, required_cap); 394 | 395 | // Tiny Vecs are dumb. Skip to: 396 | // - 8 if the element size is 1, because any heap allocators is likely to round up a 397 | // request of less than 8 bytes to at least 8 bytes. 398 | // - 4 if elements are moderate-sized (<= 1KiB). 399 | // - 1 otherwise, to avoid wasting too much space for very short Vecs. 400 | // Note that `min_non_zero_cap` is computed statically. 401 | let elem_size = mem::size_of::(); 402 | let min_non_zero_cap = if elem_size == 1 { 403 | 8 404 | } else if elem_size <= 1024 { 405 | 4 406 | } else { 407 | 1 408 | }; 409 | let cap = cmp::max(min_non_zero_cap, cap); 410 | 411 | let new_layout = Layout::array::(cap); 412 | 413 | // `finish_grow` is non-generic over `T`. 414 | let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; 415 | self.set_ptr(ptr); 416 | Ok(()) 417 | } 418 | 419 | /// The constraints on this method are much the same as those on `grow_amortized`, but this 420 | /// method is usually instantiated less often so it's less critical. 421 | fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { 422 | if mem::size_of::() == 0 { 423 | // Since we return a capacity of `u32::MAX` when `elem_size` is 0, getting to here 424 | // necessarily means the `RawVec` is overfull. 425 | return Err(CapacityOverflow); 426 | } 427 | 428 | let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; 429 | let new_layout = Layout::array::(cap); 430 | 431 | // `finish_grow` is non-generic over `T`. 432 | let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; 433 | self.set_ptr(ptr); 434 | Ok(()) 435 | } 436 | 437 | fn shrink(&mut self, amount: usize) -> Result<(), TryReserveError> { 438 | assert!( 439 | amount <= self.capacity(), 440 | "Tried to shrink to a larger capacity" 441 | ); 442 | 443 | let (ptr, layout) = if let Some(mem) = self.current_memory() { 444 | mem 445 | } else { 446 | return Ok(()); 447 | }; 448 | let new_size = amount * mem::size_of::(); 449 | 450 | let ptr = unsafe { 451 | let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); 452 | self.alloc 453 | .shrink(ptr, layout, new_layout) 454 | .map_err(|_| TryReserveError::AllocError { 455 | layout: new_layout, 456 | non_exhaustive: (), 457 | })? 458 | }; 459 | self.set_ptr(ptr); 460 | Ok(()) 461 | } 462 | } 463 | 464 | // This function is outside `RawVec` to minimize compile times. See the comment above 465 | // `RawVec::grow_amortized` for details. (The `A` parameter isn't significant, because the number 466 | // of different `A` types seen in practice is much smaller than number of `T` types.) 467 | fn finish_grow( 468 | new_layout: Result, 469 | current_memory: Option<(NonNull, Layout)>, 470 | alloc: &mut A, 471 | ) -> Result, TryReserveError> 472 | where 473 | A: AllocRef, 474 | { 475 | // Check for the error here to minimize the size of `RawVec::grow_*`. 476 | let new_layout = new_layout.map_err(|_| CapacityOverflow)?; 477 | 478 | alloc_guard(new_layout.size())?; 479 | 480 | let memory = if let Some((ptr, old_layout)) = current_memory { 481 | debug_assert_eq!(old_layout.align(), new_layout.align()); 482 | unsafe { 483 | // The allocator checks for alignment equality 484 | intrinsics::assume(old_layout.align() == new_layout.align()); 485 | alloc.grow(ptr, old_layout, new_layout) 486 | } 487 | } else { 488 | alloc.alloc(new_layout) 489 | }; 490 | 491 | memory.map_err(|_| AllocError { 492 | layout: new_layout, 493 | non_exhaustive: (), 494 | }) 495 | } 496 | 497 | unsafe impl<#[may_dangle] T, A: AllocRef> Drop for RawVec { 498 | /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. 499 | fn drop(&mut self) { 500 | if let Some((ptr, layout)) = self.current_memory() { 501 | unsafe { self.alloc.dealloc(ptr, layout) } 502 | } 503 | } 504 | } 505 | 506 | // We need to guarantee the following: 507 | // * We don't ever allocate `> u32::MAX` byte-size objects. 508 | // * We don't overflow `usize::MAX` and actually allocate too little. 509 | #[inline] 510 | fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> { 511 | if alloc_size > u32::MAX as usize { 512 | Err(CapacityOverflow) 513 | } else { 514 | Ok(()) 515 | } 516 | } 517 | 518 | // One central function responsible for repoting capacity overflows. This'll ensure that the code 519 | // generation related to these panics is minimal as there's only one location which panics rather 520 | // than a bunch throughout the module. 521 | fn capacity_overflow() -> ! { 522 | panic!("capacity overflow"); 523 | } 524 | -------------------------------------------------------------------------------- /src/slice.rs: -------------------------------------------------------------------------------- 1 | #![doc(hidden)] 2 | 3 | /// Replace standard library `slice` implementation to interface with `Vec`. 4 | use alloc::borrow::Borrow; 5 | 6 | use crate::vec::Vec; 7 | 8 | //////////////////////////////////////////////////////////////////////////////// 9 | // Basic slice extension methods 10 | //////////////////////////////////////////////////////////////////////////////// 11 | 12 | pub use hack::into_vec; 13 | pub use hack::to_vec; 14 | 15 | // Use japaric hack for `impl [T]` for `cfg(test)` which `impl [T]` is not available. 16 | mod hack { 17 | use crate::vec::Vec; 18 | use alloc::boxed::Box; 19 | 20 | pub fn into_vec(b: Box<[T]>) -> Vec { 21 | let len = b.len(); 22 | let b = Box::into_raw(b); 23 | unsafe { Vec::from_raw_parts(b as *mut T, len, len) } 24 | } 25 | 26 | pub fn to_vec(s: &[T]) -> Vec 27 | where 28 | T: Clone, 29 | { 30 | let mut vec = Vec::with_capacity(s.len()); 31 | vec.extend_from_slice(s); 32 | vec 33 | } 34 | } 35 | 36 | //////////////////////////////////////////////////////////////////////////////// 37 | // Standard trait implementations for slices 38 | //////////////////////////////////////////////////////////////////////////////// 39 | 40 | impl Borrow<[T]> for Vec { 41 | fn borrow(&self) -> &[T] { 42 | &self[..] 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/vec.rs: -------------------------------------------------------------------------------- 1 | //! A contiguous growable array type with heap-allocated contents, written `Vec`. 2 | //! 3 | //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and `O(1)` pop (from the end). 4 | //! 5 | //! Vectors ensure they never alloctae more than `isize::MAX` bytes. 6 | //! 7 | //! # Examples 8 | //! 9 | //! You can explicitly create a [`Vec`] with [`new`]: 10 | //! 11 | //! ``` 12 | //! use ve::Vec; 13 | //! 14 | //! let v: Vec = Vec::new(); 15 | //! ``` 16 | //! 17 | //! ...or by using the [`vec!`] macro: 18 | //! 19 | //! ``` 20 | //! use ve::{Vec, vec}; 21 | //! 22 | //! let v: Vec = vec![]; 23 | //! 24 | //! let v = vec![1, 2, 3, 4, 5]; 25 | //! 26 | //! let v = vec![0; 10]; // ten zeros 27 | //! ``` 28 | //! 29 | //! You can [`push`] values onto the end of a vector (which will grow the vector as needed): 30 | //! 31 | //! ``` 32 | //! # use ve::vec; 33 | //! let mut v = vec![1, 2]; 34 | //! 35 | //! v.push(3); 36 | //! ``` 37 | //! 38 | //! Popping values works in much the same way: 39 | //! 40 | //! ``` 41 | //! # use ve::vec; 42 | //! let mut v = vec![1, 2]; 43 | //! 44 | //! let two = v.pop(); 45 | //! ``` 46 | //! 47 | //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits): 48 | //! 49 | //! ``` 50 | //! # use ve::vec; 51 | //! let mut v = vec![1, 2, 3]; 52 | //! let three = v[2]; 53 | //! v[1] = v[1] + 5; 54 | //! ``` 55 | //! 56 | //! [`Vec`]: Vec 57 | //! [`new`]: Vec::new 58 | //! [`push`]: Vec::push 59 | 60 | use core::cmp::Ordering; 61 | use core::fmt; 62 | use core::hash::{Hash, Hasher}; 63 | use core::intrinsics::{arith_offset, assume}; 64 | use core::iter::{FromIterator, FusedIterator, TrustedLen}; 65 | use core::marker::PhantomData; 66 | use core::mem::{self, ManuallyDrop}; 67 | use core::ops::Bound::{Excluded, Included, Unbounded}; 68 | use core::ops::{self, Index, IndexMut, RangeBounds}; 69 | use core::ptr::{self, NonNull}; 70 | use core::slice::{self, SliceIndex}; 71 | 72 | use alloc::borrow::{Cow, ToOwned}; 73 | use alloc::boxed::Box; 74 | 75 | use crate::raw_vec::{RawVec, MASK_HI, MASK_LO}; 76 | 77 | /// A continuous growable array type, written `Vec` but pronounced 'vector'. 78 | /// 79 | /// # Examples 80 | /// 81 | /// ``` 82 | /// # use ve::Vec; 83 | /// let mut vec = Vec::new(); 84 | /// vec.push(1); 85 | /// vec.push(2); 86 | /// 87 | /// assert_eq!(vec.len(), 2); 88 | /// assert_eq!(vec[0], 1); 89 | /// 90 | /// assert_eq!(vec.pop(), Some(2)); 91 | /// assert_eq!(vec.len(), 1); 92 | /// 93 | /// vec[0] = 7; 94 | /// assert_eq!(vec[0], 7); 95 | /// 96 | /// vec.extend([1, 2, 3].iter().copied()); 97 | /// 98 | /// for x in &vec { 99 | /// println!("{}", x); 100 | /// } 101 | /// assert_eq!(vec, [7, 1, 2, 3]); 102 | /// ``` 103 | /// 104 | /// The [`vec!`] macro is provided to make initialization more convenient: 105 | /// 106 | /// ``` 107 | /// # use ve::vec; 108 | /// let mut vec = vec![1, 2, 3]; 109 | /// vec.push(4); 110 | /// assert_eq!(vec, [1, 2, 3, 4]); 111 | /// ``` 112 | /// 113 | /// It can also initialize each element of a `Vec` with a given value. 114 | /// This may be more efficient than performing allocation and initialization in separate steps, 115 | /// especially when initializing a vector of zeros: 116 | /// 117 | /// ``` 118 | /// # use ve::vec; 119 | /// let vec = vec![0; 5]; 120 | /// assert_eq!(vec, [0, 0, 0, 0, 0]); 121 | /// 122 | /// // The follwing is equavalent, but potentially slower: 123 | /// let mut vec1 = Vec::with_capacity(5); 124 | /// vec1.resize(5, 0); 125 | /// ``` 126 | /// 127 | /// Use a `Vec` as an efficient stack: 128 | /// 129 | /// ``` 130 | /// # use ve::Vec; 131 | /// let mut stack = Vec::new(); 132 | /// 133 | /// stack.push(1); 134 | /// stack.push(2); 135 | /// stack.push(3); 136 | /// 137 | /// while let Some(top) = stack.pop() { 138 | /// // Prints 3, 2, 1 139 | /// println!("{}", top); 140 | /// } 141 | /// ``` 142 | /// 143 | /// # Indexing 144 | /// 145 | /// The `Vec` type allows to access values by index, because it implements [`Index`] trait. 146 | /// An example will be more explicit: 147 | /// 148 | /// ``` 149 | /// # use ve::vec; 150 | /// let v = vec![0, 2, 4, 6]; 151 | /// println!("{}", v[1]); // it will display '2' 152 | /// ``` 153 | /// 154 | /// However be careful: if you try to access an index which isn't in the `Vec`, 155 | /// your software will panic! You cannot do this: 156 | /// 157 | /// ```should_panic 158 | /// # use ve::vec; 159 | /// let v = vec![0, 2, 4, 6]; 160 | /// println!("{}", v[6]); // it will panic! 161 | /// ``` 162 | /// 163 | /// Use [`get`] and [`get_mut`] if you want to check whether the index is in the `Vec`. 164 | /// 165 | /// # Slicing 166 | /// 167 | /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects. 168 | /// To get a slice, use `&`. Example: 169 | /// 170 | /// ``` 171 | /// # use ve::vec; 172 | /// fn read_slice(slice: &[usize]) { 173 | /// // ... 174 | /// } 175 | /// 176 | /// let v = vec![0, 1]; 177 | /// read_slice(&v); 178 | /// 179 | /// // ... and that's all! 180 | /// // you can also do it like this: 181 | /// let u: &[usize] = &v; 182 | /// ``` 183 | /// 184 | /// In Rust, it's more common to pass slices as arguments rather than vectors when you just want to 185 | /// provide read access. The same goes for [`String`] and [`&str`]. 186 | /// 187 | /// # Capacity and reallocation 188 | /// 189 | /// The capacity of a vector is the amount of space allocated for any future elements that will be 190 | /// added onto the vector. This is not to be confused with the *length* of a vector, which 191 | /// specifies the number of actual elements within the vector. If a vector's length exceeds its 192 | /// capacity, its capacity will automatically be increased but its elements will have to be 193 | /// reallocated. 194 | /// 195 | /// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 196 | /// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or 197 | /// cause reallocation to occur. However, if the vector's length is increased to 11, it will have 198 | /// to reallocate, which can be slow. For this reason, it is recommended to use 199 | /// [`Vec::with_capacity`] whenever possible to specify how big the vector is expected to get. 200 | /// 201 | /// # Guarantees 202 | /// 203 | /// TODO Guarantees 204 | /// 205 | /// [`get`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.get 206 | /// [`get_mut`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.get_mut 207 | /// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html 208 | /// [`&str`]: type@str 209 | pub struct Vec { 210 | buf: RawVec, 211 | } 212 | 213 | impl Vec { 214 | /// Constructs a new empty, `Vec`. 215 | /// 216 | /// The vector will not allocate until elements are pushed onto it. 217 | /// 218 | /// # Examples 219 | /// 220 | /// ``` 221 | /// # use ve::Vec; 222 | /// let mut vec: Vec = Vec::new(); 223 | /// ``` 224 | #[inline] 225 | pub const fn new() -> Vec { 226 | Vec { buf: RawVec::new() } 227 | } 228 | 229 | /// Constructs a new, empty `Vec` with the specified capacity. 230 | /// 231 | /// The vector will be able to hold exactly `capacity` elements without reallocating. If 232 | /// `capacity` is 0, the vector will not allocate. 233 | /// 234 | /// It is important to note that although the returned vector has the *capacity* specified, the 235 | /// vector will have a zero *length*. For an explanation of the difference between length and 236 | /// capacity, see *[Capacity and reallocation]*. 237 | /// 238 | /// [Capacity and reallocation]: #capacity-and-reallocation 239 | /// 240 | /// # Examples 241 | /// 242 | /// ``` 243 | /// # use ve::Vec; 244 | /// let mut vec = Vec::with_capacity(10); 245 | /// 246 | /// // The vector contains no items, even though it has capacity for more 247 | /// assert_eq!(vec.len(), 0); 248 | /// assert_eq!(vec.capacity(), 10); 249 | /// 250 | /// // These are all done without reallocating... 251 | /// for i in 0..10 { 252 | /// vec.push(i); 253 | /// } 254 | /// assert_eq!(vec.len(), 10); 255 | /// assert_eq!(vec.capacity(), 10); 256 | /// 257 | /// // ...but this may make the vector reallocate 258 | /// vec.push(11); 259 | /// assert_eq!(vec.len(), 11); 260 | /// assert!(vec.capacity() >= 11); 261 | /// ``` 262 | #[inline] 263 | pub fn with_capacity(capacity: usize) -> Vec { 264 | Vec { 265 | buf: RawVec::with_capacity(capacity), 266 | } 267 | } 268 | 269 | /// Creates a `Vec` directly from the raw components of another vector. 270 | /// 271 | /// # Safety 272 | /// 273 | /// This is highly unsafe, due to the number of invariants that aren't checked: 274 | /// 275 | /// * `ptr` needs to have been previously allocated via [`String`]/`Vec` (at least, it's 276 | /// highly likely to be incorrect if it wasn't). 277 | /// * `T` needs to have the same size and alignment as what `ptr` was allocated with. (`T` 278 | /// having a less strict alignment is not sufficient, the alignment really needs to be equal 279 | /// to satisfy the [`dealloc`] requirement that memory must be allocated and deallocated with 280 | /// the same layout.) 281 | /// * `length` needs to be less than or equal to `capacity`. 282 | /// * `capacity` needs to be the capacity that the pointer was allocated with. 283 | /// 284 | /// Violating these may cause problems like corrupting the allocator's internal data 285 | /// structures. For example it is **not** safe to build a `Vec` from a pointer to a C 286 | /// `char` array with length `size_t`. It's also not safe to build one from a `Vec` and 287 | /// its length, because the allocator cares about the alignment, and these two types have 288 | /// different alignments. The buffer was allocated with alignment 2 (for `u16`), but after 289 | /// turning it into a `Vec` it'll be deallocated with alignment 1. 290 | /// 291 | /// The ownership of `ptr` is effectively transferred to the `Vec` which may then 292 | /// deallocate, reallocate or change the contents of memory pointed to by the pointer at will. 293 | /// Ensure that nothing else uses the pointer after calling this function. 294 | /// 295 | /// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html 296 | /// [`dealloc`]: https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html#tymethod.dealloc 297 | /// 298 | /// # Examples 299 | /// 300 | /// ``` 301 | /// # use ve::vec; 302 | /// use std::ptr; 303 | /// use std::mem; 304 | /// 305 | /// let v = vec![1, 2, 3]; 306 | /// 307 | // FIXME Update this when vec_into_raw_parts is stabilized 308 | /// // Prevent running `v`'s destructor so we are in complete control 309 | /// // of the allocation. 310 | /// let mut v = mem::ManuallyDrop::new(v); 311 | /// 312 | /// // Pull out the various important pieces of information about `v` 313 | /// let p = v.as_mut_ptr(); 314 | /// let len = v.len(); 315 | /// let cap = v.capacity(); 316 | /// 317 | /// unsafe { 318 | /// // Overwrite memory with 4, 5, 6 319 | /// for i in 0..len as isize { 320 | /// ptr::write(p.offset(i), 4 + i); 321 | /// } 322 | /// 323 | /// // Put everything back together into a Vec 324 | /// let rebuilt = Vec::from_raw_parts(p, len, cap); 325 | /// assert_eq!(rebuilt, [4, 5, 6]); 326 | /// } 327 | /// ``` 328 | pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec { 329 | Vec { 330 | buf: unsafe { RawVec::from_raw_parts(ptr, capacity, length) }, 331 | } 332 | } 333 | 334 | /// Returns the number of elements the vector can hold without reallocating. 335 | /// 336 | /// # Examples 337 | /// 338 | /// ``` 339 | /// # use ve::Vec; 340 | /// let vec: Vec = Vec::with_capacity(10); 341 | /// assert_eq!(vec.capacity(), 10); 342 | /// ``` 343 | #[inline] 344 | pub fn capacity(&self) -> usize { 345 | self.buf.capacity() 346 | } 347 | 348 | /// Reserves capacity for at least `additional` more elements to be inserted in the given 349 | /// `Vec`. The collection may reserve more space to avoid frequent reallocations. After 350 | /// calling `reserve`, capacity will be greater than or equal to `self.len() + additional`. 351 | /// Does nothing if capacity is already sufficient. 352 | /// 353 | /// # Panics 354 | /// 355 | /// Panics if the new capacity overflows `usize`. 356 | /// 357 | /// # Examples 358 | /// 359 | /// ``` 360 | /// # use ve::vec; 361 | /// let mut vec = vec![1]; 362 | /// vec.reserve(10); 363 | /// assert!(vec.capacity() >= 11); 364 | /// ``` 365 | pub fn reserve(&mut self, additional: usize) { 366 | self.buf.reserve(self.buf.len(), additional); 367 | } 368 | 369 | /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the 370 | /// given `Vec`. After calling `reserve_exact`, capacity will be greater than or equal to 371 | /// `self.len() + additional`. Does nothing if the capacity is already sufficient. 372 | /// 373 | /// Note that the allocator may give the collection more space than it requests. Therefore, 374 | /// capacity can not be relied upon to be precisely minimal. Prefer `reverse` if future 375 | /// insertions are expected. 376 | /// 377 | /// # Panics 378 | /// 379 | /// Panics if the new capacity overflows `usize`. 380 | /// 381 | /// # Examples 382 | /// 383 | /// ``` 384 | /// # use ve::vec; 385 | /// let mut vec = vec![1]; 386 | /// vec.reserve_exact(10); 387 | /// assert!(vec.capacity() >= 11); 388 | /// ``` 389 | pub fn reserve_exact(&mut self, additional: usize) { 390 | self.buf.reserve_exact(self.len(), additional); 391 | } 392 | 393 | /// Shrinks the capacity of the vector as much as possible. 394 | /// 395 | /// It will drop down as close as possible to the length but the allocator may still inform the 396 | /// vector that there is space for a few more elements. 397 | /// 398 | /// # Examples 399 | /// 400 | /// ``` 401 | /// # use ve::vec; 402 | /// let mut vec = Vec::with_capacity(10); 403 | /// vec.extend([1, 2, 3].iter().cloned()); 404 | /// assert_eq!(vec.capacity(), 10); 405 | /// vec.shrink_to_fit(); 406 | /// assert!(vec.capacity() >= 3); 407 | /// ``` 408 | pub fn shrink_to_fit(&mut self) { 409 | // The capacity is never less than the length, and there's nothing to do when they are 410 | // equal, so we can avoid the panic case in `RawVec::shrink_to_fit` by only calling it 411 | // with a greater capacity. 412 | if self.capacity() > self.len() { 413 | self.buf.shrink_to_fit(self.len()); 414 | } 415 | } 416 | 417 | /// Converts the vector into [`Box<[T]>`][owned slice]. 418 | /// 419 | /// Note that this will drop any excess capacity. 420 | /// 421 | /// [owned slice]: Box 422 | /// 423 | /// # Examples 424 | /// 425 | /// ``` 426 | /// # use ve::vec; 427 | /// let v = vec![1, 2, 3]; 428 | /// 429 | /// let slice = v.into_boxed_slice(); 430 | /// ``` 431 | /// 432 | /// Any excess capacity is removed: 433 | /// 434 | /// ``` 435 | /// # use ve::Vec; 436 | /// let mut vec = Vec::with_capacity(10); 437 | /// vec.extend([1, 2, 3].iter().cloned()); 438 | /// 439 | /// assert_eq!(vec.capacity(), 10); 440 | /// let slice = vec.into_boxed_slice(); 441 | /// assert_eq!(slice.into_vec().capacity(), 3); 442 | /// ``` 443 | pub fn into_boxed_slice(mut self) -> Box<[T]> { 444 | self.shrink_to_fit(); 445 | let me = ManuallyDrop::new(self); 446 | unsafe { 447 | let buf = ptr::read(&me.buf); 448 | let len = me.len(); 449 | buf.into_box(len).assume_init() 450 | } 451 | } 452 | 453 | /// Shortens the vector, keeping the first `len` elements and dropping the rest. 454 | /// 455 | /// If `len` is greater than the vector's current length, this has no effect. 456 | /// 457 | /// The [`drain`] method can emulate `truncate`, but causes the excess elements to be returned 458 | /// instead of dropped. 459 | /// 460 | /// Note that this method has no effect on the allocated capacity of the vector. 461 | /// 462 | /// # Examples 463 | /// 464 | /// Truncating a five element vector to two elements: 465 | /// 466 | /// ``` 467 | /// # use ve::vec; 468 | /// let mut vec = vec![1, 2, 3, 4, 5]; 469 | /// vec.truncate(2); 470 | /// assert_eq!(vec, [1, 2]); 471 | /// ``` 472 | /// 473 | /// No truncation occurs when `len` is greater than the vector's current length: 474 | /// 475 | /// ``` 476 | /// # use ve::vec; 477 | /// let mut vec = vec![1, 2, 3]; 478 | /// vec.truncate(8); 479 | /// assert_eq!(vec, [1, 2, 3]); 480 | /// ``` 481 | /// 482 | /// Truncating when `len == 0` is equivalent to calling the [`clear`] method. 483 | /// 484 | /// ``` 485 | /// # use ve::vec; 486 | /// let mut vec = vec![1, 2, 3]; 487 | /// vec.truncate(0); 488 | /// assert_eq!(vec, []); 489 | /// ``` 490 | /// 491 | /// [`clear`]: Vec::clear 492 | /// [`drain`]: Vec::drain 493 | pub fn truncate(&mut self, len: usize) { 494 | // This is safe because: 495 | // 496 | // * the slice passed to `drop_in_place` is valid; the `len > self.len` case avoids 497 | // creating an invalid slice, and 498 | // * the `len` of the vector is shrunk before calling `drop_in_place`, such that no value 499 | // will be dropped twice in case `drop_in_place` were to panic once (if it panics twice, 500 | // the program aborts). 501 | unsafe { 502 | if len > self.len() { 503 | return; 504 | } 505 | let remaining_len = self.len() - len; 506 | let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 507 | self.buf.set_len(len); 508 | ptr::drop_in_place(s); 509 | } 510 | } 511 | 512 | /// Extracts a slice containing the entire vector. 513 | /// 514 | /// Equivalent to `&s[..]`. 515 | /// 516 | /// # Examples 517 | /// 518 | /// ``` 519 | /// # use ve::vec; 520 | /// use std::io::{self, Write}; 521 | /// let buffer = vec![1, 2, 3, 4, 5]; 522 | /// io::sink().write(buffer.as_slice()).unwrap(); 523 | /// ``` 524 | #[inline] 525 | pub fn as_slice(&self) -> &[T] { 526 | self 527 | } 528 | 529 | /// Extracts a mutable slice containing the entire vector. 530 | /// 531 | /// Equivalent to `&mut s[..]`. 532 | /// 533 | /// # Examples 534 | /// 535 | /// ``` 536 | /// # use ve::vec; 537 | /// use std::io::{self, Read}; 538 | /// let mut buffer = vec![0; 3]; 539 | /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); 540 | /// ``` 541 | #[inline] 542 | pub fn as_mut_slice(&mut self) -> &mut [T] { 543 | self 544 | } 545 | 546 | /// Returns a raw pointer to the vector's buffer. 547 | /// 548 | /// The caller must ensure that the vector outlives the ponitre this function requires, or else 549 | /// it will end up pointing to garbage. Modifying the vector may cause its buffer to be 550 | /// reallocated, which would also make any pointers to it invalid. 551 | /// 552 | /// The caller must also ensure that the memory (non-transitively) points to is never written 553 | /// to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If 554 | /// you need to mutate the contents of the slice, use [`as_mut_ptr`]. 555 | /// 556 | /// # Examples 557 | /// 558 | /// ``` 559 | /// # use ve::vec; 560 | /// let x = vec![1, 2, 4]; 561 | /// let x_ptr = x.as_ptr(); 562 | /// 563 | /// unsafe { 564 | /// for i in 0..x.len() { 565 | /// assert_eq!(*x_ptr.add(i), 1 << i); 566 | /// } 567 | /// } 568 | /// ``` 569 | /// 570 | /// [`as_mut_ptr`]: Vec::as_mut_ptr 571 | #[inline] 572 | pub fn as_ptr(&self) -> *const T { 573 | // We shadow the slice method of thesame name to avoid going through `deref`, which creates 574 | // an immediate reference. 575 | let ptr = self.buf.ptr(); 576 | unsafe { 577 | assume(!ptr.is_null()); 578 | } 579 | ptr 580 | } 581 | 582 | /// Returns an unsafe mutable pointer to the vector's buffer. 583 | /// 584 | /// The caller must ensure that the vector outlives the pointer this function returns, or else 585 | /// it will end up pointing to garbage. Modifying the vector may cause its buffer to be 586 | /// reallocated, which would also make any pointers to it invalid. 587 | /// 588 | /// # Examples 589 | /// 590 | /// ``` 591 | /// # use ve::Vec; 592 | /// // Allocate vector big enough for 4 elements. 593 | /// let size = 4; 594 | /// let mut x: Vec = Vec::with_capacity(size); 595 | /// let x_ptr = x.as_mut_ptr(); 596 | /// 597 | /// // Initialize elements via raw pointer writes, then set length. 598 | /// unsafe { 599 | /// for i in 0..size { 600 | /// *x_ptr.add(i) = i as i32; 601 | /// } 602 | /// x.set_len(size); 603 | /// } 604 | /// assert_eq!(&*x, &[0,1,2,3]); 605 | /// ``` 606 | #[inline] 607 | pub fn as_mut_ptr(&mut self) -> *mut T { 608 | // We shadow the slice method of the same name to avoid going around `deref_mut`, which 609 | // creates an intermediate referenc. 610 | let ptr = self.buf.ptr(); 611 | unsafe { 612 | assume(!ptr.is_null()); 613 | } 614 | ptr 615 | } 616 | 617 | /// Forces the length of the vector to `new_len`. 618 | /// 619 | /// THis is a low-level operation that maintains none of the normal invariants of the types. 620 | /// Normally changing the length of a vector is done using one of the safe operations instead, 621 | /// such as [`truncate`], [`resize`], [`extend`], or [`clear`]. 622 | /// 623 | /// [`truncate`]: Vec::truncate 624 | /// [`resize`]: Vec::resize 625 | /// [`extend`]: Extend::extend 626 | /// [`clear`]: Vec::clear 627 | /// 628 | /// # Safety 629 | /// 630 | /// - `new_len` must be less than or equal to [`capacity()`]. 631 | /// - The elements at `old_len..new_len` must be initialized. 632 | /// 633 | /// [`capacity()`]: Vec::capacity 634 | /// 635 | /// # Examples 636 | /// 637 | /// This method can be useful for situations in which the vector is serving as a buffer for 638 | /// other code, particularly over FFI: 639 | /// 640 | /// ```no_run 641 | /// # #![allow(dead_code)] 642 | /// # use ve::Vec; 643 | /// # // This is just a minimal skeleton for the doc sample; 644 | /// # // don't use this as a starting point for a real library. 645 | /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void } 646 | /// # const Z_OK: i32 = 0; 647 | /// # extern "C" { 648 | /// # fn deflateGetDictionary( 649 | /// # strm: *mut std::ffi::c_void, 650 | /// # dictionary: *mut u8, 651 | /// # dictLength: *mut usize, 652 | /// # ) -> i32; 653 | /// # } 654 | /// # impl StreamWrapper { 655 | /// pub fn get_dictionary(&self) -> Option> { 656 | /// // Per the FFI method's docs, "32768 bytes is always enough". 657 | /// let mut dict = Vec::with_capacity(32_768); 658 | /// let mut dict_length = 0; 659 | /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: 660 | /// // 1. `dict_length` elements were initialized. 661 | /// // 2. `dict_length` <= the capacity (32_768) 662 | /// unsafe { 663 | /// // Make the FFI call... 664 | /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); 665 | /// if r == Z_OK { 666 | /// // ...and update the length to what was initialized 667 | /// dict.set_len(dict_length); 668 | /// Some(dict) 669 | /// } else { 670 | /// None 671 | /// } 672 | /// } 673 | /// } 674 | /// # } 675 | /// ``` 676 | /// 677 | /// While the following example is sound, there is a memory leak since the inner vectors were 678 | /// not freed prior to the `set_len` call: 679 | /// 680 | /// ``` 681 | /// # use ve::vec; 682 | /// let mut vec = vec![vec![1, 0, 0], 683 | /// vec![0, 1, 0], 684 | /// vec![0, 0, 1]]; 685 | /// // SAFETY: 686 | /// // 1. `old_len..0` is empty so no elements need to be initialized. 687 | /// // 2. `0 <= capacity` always holds whatever `capacity` is. 688 | /// unsafe { 689 | /// vec.set_len(0); 690 | /// } 691 | /// ``` 692 | /// 693 | /// Normally, here, one would use [`clear`] instead to correctly drop the contents and thus 694 | /// not leak memory. 695 | #[inline] 696 | pub unsafe fn set_len(&mut self, new_len: usize) { 697 | debug_assert!(new_len <= self.capacity()); 698 | 699 | self.buf.set_len(new_len); 700 | } 701 | 702 | /// Removes an element from the vector and returns it. 703 | /// 704 | /// The removed element is replaced by the last element of the vector. 705 | /// 706 | /// This does not preserve ordering, but is O(1). 707 | /// 708 | /// # Panics 709 | /// 710 | /// Panics if `index` is out of bounds. 711 | /// 712 | /// # Examples 713 | /// 714 | /// ``` 715 | /// # use ve::vec; 716 | /// let mut v = vec!["foo", "bar", "baz", "qux"]; 717 | /// 718 | /// assert_eq!(v.swap_remove(1), "bar"); 719 | /// assert_eq!(v, ["foo", "qux", "baz"]); 720 | /// 721 | /// assert_eq!(v.swap_remove(0), "foo"); 722 | /// assert_eq!(v, ["baz", "qux"]); 723 | /// ``` 724 | #[inline] 725 | pub fn swap_remove(&mut self, index: usize) -> T { 726 | #[cold] 727 | #[inline(never)] 728 | fn assert_failed(index: usize, len: usize) -> ! { 729 | panic!( 730 | "swap_remove index (is {}) should be < len (is {})", 731 | index, len 732 | ); 733 | } 734 | 735 | let len = self.len(); 736 | if index >= len { 737 | assert_failed(index, len); 738 | } 739 | unsafe { 740 | // We replace self[index] with the last element. Note that if the bounds check above 741 | // succeeds there must be a last element (which can be self[index] itself). 742 | let last = ptr::read(self.as_ptr().add(len - 1)); 743 | let hole = self.as_mut_ptr().add(index); 744 | self.set_len(len - 1); 745 | ptr::replace(hole, last) 746 | } 747 | } 748 | 749 | /// Inserts an element at position `index` within the vector, shifting all elements after it to 750 | /// the right. 751 | /// 752 | /// # Panics 753 | /// 754 | /// Panics if `index > len`. 755 | /// 756 | /// # Examples 757 | /// 758 | /// ``` 759 | /// # use ve::vec; 760 | /// let mut vec = vec![1, 2, 3]; 761 | /// vec.insert(1, 4); 762 | /// assert_eq!(vec, [1, 4, 2, 3]); 763 | /// vec.insert(4, 5); 764 | /// assert_eq!(vec, [1, 4, 2, 3, 5]); 765 | /// ``` 766 | pub fn insert(&mut self, index: usize, element: T) { 767 | #[cold] 768 | #[inline(never)] 769 | fn assert_failed(index: usize, len: usize) -> ! { 770 | panic!( 771 | "insertion index (is {}) should be <= len (is {})", 772 | index, len 773 | ); 774 | } 775 | 776 | let len = self.len(); 777 | if index > len { 778 | assert_failed(index, len); 779 | } 780 | 781 | // space for the new element 782 | if len == self.buf.capacity() { 783 | self.reserve(1); 784 | } 785 | 786 | unsafe { 787 | // infallible 788 | // The spot to put the new value 789 | { 790 | let p = self.as_mut_ptr().add(index); 791 | // Shift everything over to make space. (Duplicating the `index`th element into two 792 | // consecutive places.) 793 | ptr::copy(p, p.offset(1), len - index); 794 | // Write it in, overwriting the first copy of the `index`th element. 795 | ptr::write(p, element); 796 | } 797 | self.set_len(len + 1); 798 | } 799 | } 800 | 801 | /// Removes all but the first of consecutive elements in the vector satisfying a given equality 802 | /// relation. 803 | /// 804 | /// The `same_bucket` function is passed references to two elements from the vector and must 805 | /// determine if the elements compare equal. The elements are passed in opposite order from 806 | /// their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed. 807 | /// 808 | /// If the vector is sorted, this removes all duplicates. 809 | /// 810 | /// # Examples 811 | /// 812 | /// ``` 813 | /// # use ve::vec; 814 | /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; 815 | /// 816 | /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); 817 | /// 818 | /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); 819 | /// ``` 820 | pub fn dedup_by(&mut self, same_bucket: F) 821 | where 822 | F: FnMut(&mut T, &mut T) -> bool, 823 | { 824 | let len = { 825 | let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket); 826 | dedup.len() 827 | }; 828 | self.truncate(len); 829 | } 830 | 831 | /// Appends an element to the back of a collection. 832 | /// 833 | /// # Panics 834 | /// 835 | /// * Panics if the requested capacity exceeds `usize::MAX` bytes. 836 | /// * Panics on 32-bit platforms if the requested capacity exceeds 837 | /// `isize::MAX` bytes. 838 | /// 839 | /// # Examples 840 | /// 841 | /// ``` 842 | /// # use ve::vec; 843 | /// let mut vec = vec![1, 2]; 844 | /// vec.push(3); 845 | /// assert_eq!(vec, [1, 2, 3]); 846 | /// ``` 847 | #[inline] 848 | pub fn push(&mut self, value: T) { 849 | // This will panic or abort if we would allocate > isize::MAX bytes or if the length 850 | // increment would overflow for zero-sized types. 851 | if self.len() == self.buf.capacity() { 852 | self.reserve(1); 853 | } 854 | unsafe { 855 | let end = self.as_mut_ptr().add(self.len()); 856 | ptr::write(end, value); 857 | self.set_len(self.len() + 1); 858 | } 859 | } 860 | 861 | /// Removes the last element from a vector and returns it, or [`None`] if it is empty. 862 | /// 863 | /// # Examples 864 | /// 865 | /// ``` 866 | /// # use ve::vec; 867 | /// let mut vec = vec![1, 2, 3]; 868 | /// assert_eq!(vec.pop(), Some(3)); 869 | /// assert_eq!(vec, [1, 2]); 870 | /// ``` 871 | #[inline] 872 | pub fn pop(&mut self) -> Option { 873 | if self.len() == 0 { 874 | None 875 | } else { 876 | unsafe { 877 | self.set_len(self.len() - 1); 878 | Some(ptr::read(self.as_ptr().add(self.len()))) 879 | } 880 | } 881 | } 882 | 883 | /// Moves all the elements of `other` into `Self`, leaving `other` empty. 884 | /// 885 | /// # Panics 886 | /// 887 | /// Panics if the number of elements in the vector overflows a `usize`. 888 | /// 889 | /// # Examples 890 | /// 891 | /// ``` 892 | /// let mut vec = vec![1, 2, 3]; 893 | /// let mut vec2 = vec![4, 5, 6]; 894 | /// vec.append(&mut vec2);; 895 | /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); 896 | /// assert_eq!(vec2, []); 897 | /// ``` 898 | pub fn append(&mut self, other: &mut Self) { 899 | unsafe { 900 | self.append_elements(other.as_slice() as _); 901 | other.set_len(0); 902 | } 903 | } 904 | 905 | /// Appends elements to `Self` from other buffer. 906 | #[inline] 907 | unsafe fn append_elements(&mut self, other: *const [T]) { 908 | let count = unsafe { (*other).len() }; 909 | self.reserve(count); 910 | let len = self.len(); 911 | unsafe { 912 | ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count); 913 | self.set_len(len + count); 914 | } 915 | } 916 | 917 | /// Creates a draining iterator that removes the specified range in the vector and yields the 918 | /// removed items. 919 | /// 920 | /// When the iterator **is** dropped, all elements in the range are removed from the vector, 921 | /// even if the iterator was not fully consumed. If the iterator **is not** dropped (with 922 | /// [`mem::forget`] for example), it is unspecified how many elements are removed. 923 | /// 924 | /// # Panics 925 | /// 926 | /// Panics if the starting point is greater than the ending point or if the ending point is 927 | /// greater than the length of the vector. 928 | /// 929 | /// # Examples 930 | /// 931 | /// ``` 932 | /// let mut v = vec![1, 2, 3]; 933 | /// let u: Vec<_> = v.drain(1..).collect(); 934 | /// assert_eq!(v, &[1]); 935 | /// assert_eq!(u, &[2, 3]); 936 | /// 937 | /// // A full range clears the vector 938 | /// v.drain(..); 939 | /// assert_eq!(v, &[]); 940 | /// ``` 941 | pub fn drain(&mut self, range: R) -> Drain<'_, T> 942 | where 943 | R: RangeBounds, 944 | { 945 | // Memory safety 946 | // 947 | // When the Drain is first created, it shortens the length of the source vector to make 948 | // sure no uninitialized or moved-from elements are accessible at all if the Drain's 949 | // destructor never gets to run. 950 | // 951 | // Drain will ptr::read out the values to remove. 952 | // When finished, remaining tail of the vec is copied back to cover the hole, and the 953 | // vector length is restored to the new depth. 954 | let len = self.len(); 955 | let start = match range.start_bound() { 956 | Included(&n) => n, 957 | Excluded(&n) => n + 1, 958 | Unbounded => 0, 959 | }; 960 | let end = match range.end_bound() { 961 | Included(&n) => n + 1, 962 | Excluded(&n) => n, 963 | Unbounded => len, 964 | }; 965 | 966 | #[cold] 967 | #[inline(never)] 968 | fn start_assert_failed(start: usize, end: usize) -> ! { 969 | panic!( 970 | "start drain index (is {}) should be <= end drain index (is {})", 971 | start, end 972 | ); 973 | } 974 | 975 | #[cold] 976 | #[inline(never)] 977 | fn end_assert_failed(end: usize, len: usize) -> ! { 978 | panic!("end drain index (is {}) should be <= len (is {})", end, len); 979 | } 980 | 981 | if start > end { 982 | start_assert_failed(start, end); 983 | } 984 | if end > len { 985 | end_assert_failed(end, len); 986 | } 987 | 988 | unsafe { 989 | // set self.vec length's to start, to be safe in case Drain is leaked 990 | self.set_len(start); 991 | // Use the borrow in the IterMut to indicate borrowing behavior of the whole Drain 992 | // iterator (like &mut T). 993 | let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 994 | Drain { 995 | tail_start: end, 996 | tail_len: len - end, 997 | iter: range_slice.iter(), 998 | vec: NonNull::from(self), 999 | } 1000 | } 1001 | } 1002 | 1003 | /// Clears the vector, removing all values. 1004 | /// 1005 | /// Note that this method has no effect on the allocated capacity of the vector. 1006 | /// 1007 | /// # Examples 1008 | /// 1009 | /// ``` 1010 | /// # use ve::vec; 1011 | /// let mut v = vec![1, 2, 3]; 1012 | /// 1013 | /// v.clear(); 1014 | /// 1015 | /// assert!(v.is_empty()); 1016 | /// ``` 1017 | #[inline] 1018 | pub fn clear(&mut self) { 1019 | self.truncate(0); 1020 | } 1021 | 1022 | /// Returns the number of elements in the vector, also referred to as its 'length'. 1023 | /// 1024 | /// # Examples 1025 | /// 1026 | /// ``` 1027 | /// let a = vec![1, 2, 3]; 1028 | /// assert_eq!(a.len(), 3); 1029 | /// ``` 1030 | #[inline] 1031 | pub fn len(&self) -> usize { 1032 | self.buf.len() 1033 | } 1034 | 1035 | /// Returns `true` if the vector contains no elements. 1036 | /// 1037 | /// # Examples 1038 | /// 1039 | /// ``` 1040 | /// # use ve::Vec; 1041 | /// let mut v = Vec::new(); 1042 | /// assert!(v.is_empty()); 1043 | /// 1044 | /// v.push(1); 1045 | /// assert!(!v.is_empty()); 1046 | /// ``` 1047 | pub fn is_empty(&self) -> bool { 1048 | self.len() == 0 1049 | } 1050 | 1051 | // TODO split_off 1052 | 1053 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. 1054 | /// 1055 | /// If `new_len` is greater than `len`, the `Vec` is extended by the difference, with each 1056 | /// additional slot filled with the result of calling the closure `f`. The return values from 1057 | /// `f` will end up in the `Vec` in the order they have been generated. 1058 | /// 1059 | /// If `new_len` is less than `len`, the `Vec` is simply truncated. 1060 | /// 1061 | /// This method uses a closure to create new values on every push. If you'd rather [`Clone`] a 1062 | /// given value, use [`Vec::resize`]. If you want to use the [`Default`] trait to generate 1063 | /// values, you can pass [`Default::default`] as the second argument. 1064 | /// 1065 | /// # Examples 1066 | /// 1067 | /// ``` 1068 | /// # use ve::vec; 1069 | /// let mut vec = vec![1, 2, 3]; 1070 | /// vec.resize_with(5, Default::default); 1071 | /// assert_eq!(vec, [1, 2, 3, 0, 0]); 1072 | /// 1073 | /// let mut vec = vec![]; 1074 | /// let mut p = 1; 1075 | /// vec.resize_with(4, || { p *= 2; p }); 1076 | /// assert_eq!(vec, [2, 4, 8, 16]); 1077 | /// ``` 1078 | pub fn resize_with(&mut self, new_len: usize, f: F) 1079 | where 1080 | F: FnMut() -> T, 1081 | { 1082 | let len = self.len(); 1083 | if new_len > len { 1084 | self.extend_with(new_len - len, ExtendFunc(f)); 1085 | } else { 1086 | self.truncate(new_len); 1087 | } 1088 | } 1089 | } 1090 | 1091 | impl Vec { 1092 | /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. 1093 | /// 1094 | /// If `new_len` is greater than `len`, the `Vec` is extended by the difference, with each 1095 | /// additional slot filled with `value`. If `new_len` is less than `len`, the `Vec` is simply 1096 | /// truncated. 1097 | /// 1098 | /// This method requires `T` to implement [`Clone`], in order to be able to clone the passed 1099 | /// value. 1100 | /// If you need more flexibility (or want to rely on [`Default`] instead of [`Clone`]), use 1101 | /// [`resize_with`]. 1102 | /// 1103 | /// # Examples 1104 | /// 1105 | /// ``` 1106 | /// # use ve::vec; 1107 | /// let mut vec = vec!["hello"]; 1108 | /// vec.resize(3, "world"); 1109 | /// assert_eq!(vec, ["hello", "world", "world"]); 1110 | /// 1111 | /// let mut vec = vec![1, 2, 3, 4]; 1112 | /// vec.resize(2, 0); 1113 | /// assert_eq!(vec, [1, 2]); 1114 | /// ``` 1115 | /// 1116 | /// [`resize_with`]: Vec::resize_with 1117 | pub fn resize(&mut self, new_len: usize, value: T) { 1118 | let len = self.len(); 1119 | 1120 | if new_len > len { 1121 | self.extend_with(new_len - len, ExtendElement(value)) 1122 | } else { 1123 | self.truncate(new_len); 1124 | } 1125 | } 1126 | 1127 | /// Clones and appends all the elements in a slice to the `Vec`. 1128 | /// 1129 | /// Iterates over the slice `other`, clones each element, and then appends it to this `Vec`. 1130 | /// The `other` vector is traversed in-order. 1131 | /// 1132 | /// Note that this function is same as [`extend`] except that it is specialized to work with 1133 | /// slices instead. If and when Rust gets specialization this function will likely be 1134 | /// deprecated (but still available). 1135 | /// 1136 | /// # Examples 1137 | /// 1138 | /// ``` 1139 | /// # use ve::vec; 1140 | /// let mut vec = vec![1]; 1141 | /// vec.extend_from_slice(&[2, 3, 4]); 1142 | /// assert_eq!(vec, [1, 2, 3, 4]); 1143 | /// ``` 1144 | /// 1145 | /// [`extend`]: Extend::extend 1146 | pub fn extend_from_slice(&mut self, other: &[T]) { 1147 | self.spec_extend(other.iter()) 1148 | } 1149 | } 1150 | 1151 | // This code generalizes `extend_with_{element,default}`. 1152 | trait ExtendWith { 1153 | fn next(&mut self) -> T; 1154 | fn last(self) -> T; 1155 | } 1156 | 1157 | struct ExtendElement(T); 1158 | impl ExtendWith for ExtendElement { 1159 | fn next(&mut self) -> T { 1160 | self.0.clone() 1161 | } 1162 | fn last(self) -> T { 1163 | self.0 1164 | } 1165 | } 1166 | 1167 | struct ExtendDefault; 1168 | impl ExtendWith for ExtendDefault { 1169 | fn next(&mut self) -> T { 1170 | Default::default() 1171 | } 1172 | fn last(self) -> T { 1173 | Default::default() 1174 | } 1175 | } 1176 | 1177 | struct ExtendFunc(F); 1178 | impl T> ExtendWith for ExtendFunc { 1179 | fn next(&mut self) -> T { 1180 | (self.0)() 1181 | } 1182 | fn last(mut self) -> T { 1183 | (self.0)() 1184 | } 1185 | } 1186 | 1187 | impl Vec { 1188 | /// Extend the vector by `n` values, using the given generator. 1189 | fn extend_with>(&mut self, n: usize, mut value: E) { 1190 | self.reserve(n); 1191 | 1192 | unsafe { 1193 | let mut ptr = self.as_mut_ptr().add(self.len()); 1194 | // Use SetLenOnDrop to work around bug where compiler may not realize the store through 1195 | // `ptr` through` self.set_len() don't alias. 1196 | let mut local_len = SetLenOnDrop::new(self.buf.fat_mut()); 1197 | 1198 | // Write all elements extend the last one 1199 | for _ in 1..n { 1200 | ptr::write(ptr, value.next()); 1201 | ptr = ptr.offset(1); 1202 | // Increment the length in every step in case next() panics 1203 | local_len.increment_len(1); 1204 | } 1205 | 1206 | if n > 0 { 1207 | // We can write the last element directly without cloning needlessly 1208 | ptr::write(ptr, value.last()); 1209 | local_len.increment_len(1); 1210 | } 1211 | 1212 | // len set by scope guard 1213 | } 1214 | } 1215 | } 1216 | 1217 | // Set the length of the vec when the `SetLenOnDrop` goes out of scope. 1218 | // 1219 | // The idea is: The length field in SetLenOnDrop is a local variable that the optimizer will see 1220 | // does not alias with any stores through the Vec's data pointer. This is a workaround for alias 1221 | // analysis issue #32115 1222 | struct SetLenOnDrop<'a> { 1223 | fat: &'a mut usize, 1224 | local_len: usize, 1225 | } 1226 | 1227 | impl<'a> SetLenOnDrop<'a> { 1228 | #[inline] 1229 | fn new(fat: &'a mut usize) -> Self { 1230 | SetLenOnDrop { 1231 | local_len: *fat & MASK_LO, 1232 | fat, 1233 | } 1234 | } 1235 | 1236 | #[inline] 1237 | fn increment_len(&mut self, increment: usize) { 1238 | self.local_len += increment; 1239 | } 1240 | } 1241 | 1242 | impl Drop for SetLenOnDrop<'_> { 1243 | #[inline] 1244 | fn drop(&mut self) { 1245 | *self.fat = *self.fat & MASK_HI | self.local_len & MASK_LO; 1246 | } 1247 | } 1248 | 1249 | impl Vec { 1250 | /// Removes consecutive repeated elemnts in the vector according to the [`PartialEq`] trait 1251 | /// implementation. 1252 | /// 1253 | /// If the vector is sorted, this removes all duplicates. 1254 | /// 1255 | /// # Examples 1256 | /// 1257 | /// ``` 1258 | /// # use ve::vec; 1259 | /// let mut vec = vec![1, 2, 2, 3, 2]; 1260 | /// 1261 | /// vec.dedup(); 1262 | /// 1263 | /// assert_eq!(vec, [1, 2, 3, 2]); 1264 | /// ``` 1265 | #[inline] 1266 | pub fn dedup(&mut self) { 1267 | self.dedup_by(|a, b| a == b) 1268 | } 1269 | } 1270 | 1271 | //////////////////////////////////////////////////////////////////////////////// 1272 | // Internal methods and functions 1273 | //////////////////////////////////////////////////////////////////////////////// 1274 | 1275 | #[doc(hidden)] 1276 | pub fn from_elem(elem: T, n: usize) -> Vec { 1277 | ::from_elem(elem, n) 1278 | } 1279 | 1280 | // Specialization trait used for Vec::from_elem 1281 | trait SpecFromElem: Sized { 1282 | fn from_elem(elem: Self, n: usize) -> Vec; 1283 | } 1284 | 1285 | impl SpecFromElem for T { 1286 | default fn from_elem(elem: Self, n: usize) -> Vec { 1287 | let mut v = Vec::with_capacity(n); 1288 | v.extend_with(n, ExtendElement(elem)); 1289 | v 1290 | } 1291 | } 1292 | 1293 | impl SpecFromElem for i8 { 1294 | #[inline] 1295 | fn from_elem(elem: i8, n: usize) -> Vec { 1296 | if elem == 0 { 1297 | return Vec { 1298 | buf: RawVec::with_capacity_zeroed(n), 1299 | }; 1300 | } 1301 | unsafe { 1302 | let mut v = Vec::with_capacity(n); 1303 | ptr::write_bytes(v.as_mut_ptr(), elem as u8, n); 1304 | v.set_len(n); 1305 | v 1306 | } 1307 | } 1308 | } 1309 | 1310 | impl SpecFromElem for u8 { 1311 | #[inline] 1312 | fn from_elem(elem: u8, n: usize) -> Vec { 1313 | if elem == 0 { 1314 | return Vec { 1315 | buf: RawVec::with_capacity_zeroed(n), 1316 | }; 1317 | } 1318 | unsafe { 1319 | let mut v = Vec::with_capacity(n); 1320 | ptr::write_bytes(v.as_mut_ptr(), elem, n); 1321 | v.set_len(n); 1322 | v 1323 | } 1324 | } 1325 | } 1326 | 1327 | impl SpecFromElem for T { 1328 | #[inline] 1329 | fn from_elem(elem: T, n: usize) -> Vec { 1330 | if elem.is_zero() { 1331 | return Vec { 1332 | buf: RawVec::with_capacity_zeroed(n), 1333 | }; 1334 | } 1335 | let mut v = Vec::with_capacity(n); 1336 | v.extend_with(n, ExtendElement(elem)); 1337 | v 1338 | } 1339 | } 1340 | 1341 | #[rustc_specialization_trait] 1342 | unsafe trait IsZero { 1343 | /// Whether this value is zero 1344 | fn is_zero(&self) -> bool; 1345 | } 1346 | 1347 | macro_rules! impl_is_zero { 1348 | ($t:ty, $is_zero:expr) => { 1349 | unsafe impl IsZero for $t { 1350 | #[inline] 1351 | fn is_zero(&self) -> bool { 1352 | $is_zero(*self) 1353 | } 1354 | } 1355 | }; 1356 | } 1357 | 1358 | impl_is_zero!(i16, |x| x == 0); 1359 | impl_is_zero!(i32, |x| x == 0); 1360 | impl_is_zero!(i64, |x| x == 0); 1361 | impl_is_zero!(i128, |x| x == 0); 1362 | impl_is_zero!(isize, |x| x == 0); 1363 | 1364 | impl_is_zero!(u16, |x| x == 0); 1365 | impl_is_zero!(u32, |x| x == 0); 1366 | impl_is_zero!(u64, |x| x == 0); 1367 | impl_is_zero!(u128, |x| x == 0); 1368 | impl_is_zero!(usize, |x| x == 0); 1369 | 1370 | impl_is_zero!(bool, |x| x == false); 1371 | impl_is_zero!(char, |x| x == '\0'); 1372 | 1373 | impl_is_zero!(f32, |x: f32| x.to_bits() == 0); 1374 | impl_is_zero!(f64, |x: f64| x.to_bits() == 0); 1375 | 1376 | unsafe impl IsZero for *const T { 1377 | #[inline] 1378 | fn is_zero(&self) -> bool { 1379 | (*self).is_null() 1380 | } 1381 | } 1382 | 1383 | unsafe impl IsZero for *mut T { 1384 | #[inline] 1385 | fn is_zero(&self) -> bool { 1386 | (*self).is_null() 1387 | } 1388 | } 1389 | 1390 | // `Option<&T>` and `Option>` are guaranteed to represent `None` as null. 1391 | // For fat pointers, the bytes that would be the pointer metadata in the `Some` variant are padding 1392 | // in the `None` variant, so ignoring them and zero-initializing instead is ok. 1393 | // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of `SpecFromElem`. 1394 | 1395 | unsafe impl IsZero for Option<&T> { 1396 | #[inline] 1397 | fn is_zero(&self) -> bool { 1398 | self.is_none() 1399 | } 1400 | } 1401 | 1402 | unsafe impl IsZero for Option> { 1403 | #[inline] 1404 | fn is_zero(&self) -> bool { 1405 | self.is_none() 1406 | } 1407 | } 1408 | 1409 | //////////////////////////////////////////////////////////////////////////////// 1410 | // Common trait implementations for Vec 1411 | //////////////////////////////////////////////////////////////////////////////// 1412 | 1413 | impl ops::Deref for Vec { 1414 | type Target = [T]; 1415 | 1416 | fn deref(&self) -> &[T] { 1417 | unsafe { slice::from_raw_parts(self.as_ptr(), self.len()) } 1418 | } 1419 | } 1420 | 1421 | impl ops::DerefMut for Vec { 1422 | fn deref_mut(&mut self) -> &mut [T] { 1423 | unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len()) } 1424 | } 1425 | } 1426 | 1427 | impl Clone for Vec { 1428 | fn clone(&self) -> Vec { 1429 | let mut vec = Vec::with_capacity(self.len()); 1430 | vec.extend_from_slice(&**self); 1431 | vec 1432 | } 1433 | } 1434 | 1435 | impl Hash for Vec { 1436 | #[inline] 1437 | fn hash(&self, state: &mut H) { 1438 | Hash::hash(&**self, state) 1439 | } 1440 | } 1441 | 1442 | impl> Index for Vec { 1443 | type Output = I::Output; 1444 | 1445 | #[inline] 1446 | fn index(&self, index: I) -> &Self::Output { 1447 | Index::index(&**self, index) 1448 | } 1449 | } 1450 | 1451 | impl> IndexMut for Vec { 1452 | #[inline] 1453 | fn index_mut(&mut self, index: I) -> &mut Self::Output { 1454 | IndexMut::index_mut(&mut **self, index) 1455 | } 1456 | } 1457 | 1458 | impl Extend for Vec { 1459 | #[inline] 1460 | fn extend>(&mut self, iter: I) { 1461 | >::spec_extend(self, iter.into_iter()) 1462 | } 1463 | } 1464 | 1465 | impl FromIterator for Vec { 1466 | #[inline] 1467 | fn from_iter>(iter: I) -> Vec { 1468 | >::from_iter(iter.into_iter()) 1469 | } 1470 | } 1471 | 1472 | impl IntoIterator for Vec { 1473 | type Item = T; 1474 | type IntoIter = IntoIter; 1475 | /// Creates a consuming iterator, that is, one that moves each value out of the vector (from 1476 | /// start to end). The vector cannot be used after calling this. 1477 | /// 1478 | /// # Examples 1479 | /// 1480 | /// ``` 1481 | /// # use ve::vec; 1482 | /// let v = vec!["a".to_string(), "b".to_string()]; 1483 | /// for s in v.into_iter() { 1484 | /// // s has type String, not &String 1485 | /// println!("{}", s); 1486 | /// } 1487 | /// ``` 1488 | #[inline] 1489 | fn into_iter(self) -> IntoIter { 1490 | unsafe { 1491 | let mut me = ManuallyDrop::new(self); 1492 | let begin = me.as_mut_ptr(); 1493 | let end = if mem::size_of::() == 0 { 1494 | arith_offset(begin as *const i8, me.len() as isize) as *const T 1495 | } else { 1496 | begin.add(me.len()) as *const T 1497 | }; 1498 | let cap = me.buf.capacity(); 1499 | IntoIter { 1500 | buf: NonNull::new_unchecked(begin), 1501 | phantom: PhantomData, 1502 | cap, 1503 | ptr: begin, 1504 | end, 1505 | } 1506 | } 1507 | } 1508 | } 1509 | 1510 | impl<'a, T> IntoIterator for &'a Vec { 1511 | type Item = &'a T; 1512 | type IntoIter = slice::Iter<'a, T>; 1513 | 1514 | fn into_iter(self) -> slice::Iter<'a, T> { 1515 | self.iter() 1516 | } 1517 | } 1518 | 1519 | impl<'a, T> IntoIterator for &'a mut Vec { 1520 | type Item = &'a mut T; 1521 | type IntoIter = slice::IterMut<'a, T>; 1522 | 1523 | fn into_iter(self) -> slice::IterMut<'a, T> { 1524 | self.iter_mut() 1525 | } 1526 | } 1527 | 1528 | // Specialization trait used for Vec::from_iter and Vec::extend 1529 | trait SpecExtend { 1530 | fn from_iter(iter: I) -> Self; 1531 | fn spec_extend(&mut self, iter: I); 1532 | } 1533 | 1534 | impl SpecExtend for Vec 1535 | where 1536 | I: Iterator, 1537 | { 1538 | default fn from_iter(mut iterator: I) -> Self { 1539 | // Unroll the first iteration, as the vector is going to be expanded on this iteration in 1540 | // every case when the iterable is not empty, but the loop in extend_desugared() is not 1541 | // going to see the vector being full in the few subsequent loop iterations. So we get 1542 | // better branch prediction. 1543 | let mut vec = match iterator.next() { 1544 | None => return Vec::new(), 1545 | Some(element) => { 1546 | let (lower, _) = iterator.size_hint(); 1547 | let mut vec = Vec::with_capacity(lower.saturating_add(1)); 1548 | unsafe { 1549 | ptr::write(vec.as_mut_ptr(), element); 1550 | vec.set_len(1); 1551 | } 1552 | vec 1553 | } 1554 | }; 1555 | as SpecExtend>::spec_extend(&mut vec, iterator); 1556 | vec 1557 | } 1558 | 1559 | default fn spec_extend(&mut self, iter: I) { 1560 | self.extend_desugared(iter) 1561 | } 1562 | } 1563 | 1564 | impl SpecExtend for Vec 1565 | where 1566 | I: TrustedLen, 1567 | { 1568 | default fn from_iter(iterator: I) -> Self { 1569 | let mut vec = Vec::new(); 1570 | vec.spec_extend(iterator); 1571 | vec 1572 | } 1573 | 1574 | default fn spec_extend(&mut self, iterator: I) { 1575 | // This is the case for a TrustedLen iterator. 1576 | let (low, high) = iterator.size_hint(); 1577 | if let Some(high_value) = high { 1578 | debug_assert_eq!( 1579 | low, 1580 | high_value, 1581 | "TrustedLen iterator's size hint is not exact: {:?}", 1582 | (low, high) 1583 | ); 1584 | } 1585 | if let Some(additional) = high { 1586 | self.reserve(additional); 1587 | unsafe { 1588 | let mut ptr = self.as_mut_ptr().add(self.len()); 1589 | let mut local_len = SetLenOnDrop::new(self.buf.fat_mut()); 1590 | iterator.for_each(move |element| { 1591 | ptr::write(ptr, element); 1592 | ptr = ptr.offset(1); 1593 | local_len.increment_len(1); 1594 | }); 1595 | } 1596 | } else { 1597 | self.extend_desugared(iterator) 1598 | } 1599 | } 1600 | } 1601 | 1602 | // impl SpecExtend> for Vec { 1603 | // fn from_iter(iterator: IntoIter) -> Self { 1604 | // // A common 1605 | // } 1606 | // } 1607 | 1608 | impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec 1609 | where 1610 | I: Iterator, 1611 | T: Clone, 1612 | { 1613 | default fn from_iter(iterator: I) -> Self { 1614 | SpecExtend::from_iter(iterator.cloned()) 1615 | } 1616 | 1617 | default fn spec_extend(&mut self, iterator: I) { 1618 | self.spec_extend(iterator.cloned()) 1619 | } 1620 | } 1621 | 1622 | impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec 1623 | where 1624 | T: Copy, 1625 | { 1626 | fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) { 1627 | let slice = iterator.as_slice(); 1628 | self.reserve(slice.len()); 1629 | unsafe { 1630 | let len = self.len(); 1631 | let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len()); 1632 | dst_slice.copy_from_slice(slice); 1633 | self.set_len(len + slice.len()); 1634 | } 1635 | } 1636 | } 1637 | 1638 | impl Vec { 1639 | fn extend_desugared>(&mut self, mut iterator: I) { 1640 | // This is the case for a general iterator. 1641 | // 1642 | // This function should be the moral equivalent of: 1643 | // 1644 | // for item in iterator { 1645 | // self.push(item); 1646 | // } 1647 | while let Some(element) = iterator.next() { 1648 | let len = self.len(); 1649 | if len == self.capacity() { 1650 | let (lower, _) = iterator.size_hint(); 1651 | self.reserve(lower.saturating_add(1)); 1652 | } 1653 | unsafe { 1654 | ptr::write(self.as_mut_ptr().add(len), element); 1655 | // NB can't overflow since we would have had to alloc the address space 1656 | self.set_len(len + 1); 1657 | } 1658 | } 1659 | } 1660 | 1661 | /// Creates a splicing iterator that replaces the specified range in the vector with the given 1662 | /// `replace_with` iterator and yields the remove items. 1663 | /// `replace_with` does not need to be the same length as `range`. 1664 | /// 1665 | /// `range` is removed even if the iterator is not consumed until the end. 1666 | /// 1667 | /// It is unspecified how many elements are removed from the vector if the `Splice` value is 1668 | /// leaked. 1669 | /// 1670 | /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. 1671 | /// 1672 | /// This is optimal if: 1673 | /// 1674 | /// * The tail (elements in the vector after `range`) is empty, 1675 | /// * or `replace_with` yields fewer elements than `range`'s length 1676 | /// * or the lower bound of its `size_hint()` is exact. 1677 | /// 1678 | /// Otherwise, a temporary vector is allocated and the tail is moved twice. 1679 | /// 1680 | /// # Panics 1681 | /// 1682 | /// Panics if the starting point is greater than the end point or if the end point is greater 1683 | /// than the length of the vector. 1684 | /// 1685 | /// # Examples 1686 | /// 1687 | /// ``` 1688 | /// # use ve::vec; 1689 | /// let mut v = vec![1, 2, 3]; 1690 | /// let new = [7, 8]; 1691 | /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect(); 1692 | /// assert_eq!(v, &[7, 8, 3]); 1693 | /// assert_eq!(u, &[1, 2]); 1694 | /// ``` 1695 | #[inline] 1696 | pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter> 1697 | where 1698 | R: RangeBounds, 1699 | I: IntoIterator, 1700 | { 1701 | Splice { 1702 | drain: self.drain(range), 1703 | replace_with: replace_with.into_iter(), 1704 | } 1705 | } 1706 | } 1707 | 1708 | macro_rules! __impl_slice_eq1 { 1709 | ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?) => { 1710 | impl PartialEq<$rhs> for $lhs 1711 | where 1712 | A: PartialEq, 1713 | $($ty: $bound)? 1714 | { 1715 | #[inline] 1716 | fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } 1717 | #[inline] 1718 | fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] } 1719 | } 1720 | } 1721 | } 1722 | 1723 | __impl_slice_eq1! { [] Vec, Vec } 1724 | __impl_slice_eq1! { [] Vec, &[B] } 1725 | __impl_slice_eq1! { [] Vec, &mut [B] } 1726 | __impl_slice_eq1! { [] &[A], Vec } 1727 | __impl_slice_eq1! { [] &mut [A], Vec } 1728 | __impl_slice_eq1! { [] Cow<'_, [A]>, Vec where A: Clone } 1729 | // __impl_slice_eq1! { [] Cow<'_, [A]>, &[B], A: Clone } 1730 | // __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B], A: Clone } 1731 | __impl_slice_eq1! { [const N: usize] Vec, [B; N] } 1732 | __impl_slice_eq1! { [const N: usize] Vec, &[B; N] } 1733 | 1734 | /// Implements comparison of vectors, lexographically. 1735 | impl PartialOrd for Vec { 1736 | #[inline] 1737 | fn partial_cmp(&self, other: &Vec) -> Option { 1738 | PartialOrd::partial_cmp(&**self, &**other) 1739 | } 1740 | } 1741 | 1742 | impl Eq for Vec {} 1743 | 1744 | /// Implements ordering of vectors, lexographically. 1745 | impl Ord for Vec { 1746 | #[inline] 1747 | fn cmp(&self, other: &Vec) -> Ordering { 1748 | Ord::cmp(&**self, &**other) 1749 | } 1750 | } 1751 | 1752 | unsafe impl<#[may_dangle] T> Drop for Vec { 1753 | fn drop(&mut self) { 1754 | unsafe { 1755 | // use drop for [T] 1756 | // use a raw slice to refer to the elements of the vector as weakest necessary type; 1757 | // could avoid questions of validity in certain cases 1758 | ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len())) 1759 | } 1760 | } 1761 | } 1762 | 1763 | impl Default for Vec { 1764 | /// Creates an empty `Vec`. 1765 | fn default() -> Vec { 1766 | Vec::new() 1767 | } 1768 | } 1769 | 1770 | impl fmt::Debug for Vec { 1771 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1772 | fmt::Debug::fmt(&**self, f) 1773 | } 1774 | } 1775 | 1776 | impl AsRef> for Vec { 1777 | fn as_ref(&self) -> &Vec { 1778 | self 1779 | } 1780 | } 1781 | 1782 | impl AsMut> for Vec { 1783 | fn as_mut(&mut self) -> &mut Vec { 1784 | self 1785 | } 1786 | } 1787 | 1788 | impl AsRef<[T]> for Vec { 1789 | fn as_ref(&self) -> &[T] { 1790 | self 1791 | } 1792 | } 1793 | 1794 | impl AsMut<[T]> for Vec { 1795 | fn as_mut(&mut self) -> &mut [T] { 1796 | self 1797 | } 1798 | } 1799 | 1800 | impl From<&[T]> for Vec { 1801 | fn from(s: &[T]) -> Vec { 1802 | crate::slice::to_vec(s) 1803 | } 1804 | } 1805 | 1806 | impl From<&mut [T]> for Vec { 1807 | fn from(s: &mut [T]) -> Vec { 1808 | crate::slice::to_vec(s) 1809 | } 1810 | } 1811 | 1812 | impl From<[T; N]> for Vec { 1813 | fn from(s: [T; N]) -> Vec { 1814 | crate::slice::into_vec(Box::new(s)) 1815 | } 1816 | } 1817 | 1818 | impl<'a, T> From> for Vec 1819 | where 1820 | [T]: ToOwned>, 1821 | { 1822 | fn from(s: Cow<'a, [T]>) -> Vec { 1823 | s.into_owned() 1824 | } 1825 | } 1826 | 1827 | impl From> for Vec { 1828 | fn from(s: Box<[T]>) -> Vec { 1829 | crate::slice::into_vec(s) 1830 | } 1831 | } 1832 | 1833 | impl From> for Box<[T]> { 1834 | fn from(v: Vec) -> Box<[T]> { 1835 | v.into_boxed_slice() 1836 | } 1837 | } 1838 | 1839 | impl From<&str> for Vec { 1840 | fn from(s: &str) -> Vec { 1841 | From::from(s.as_bytes()) 1842 | } 1843 | } 1844 | 1845 | //////////////////////////////////////////////////////////////////////////////// 1846 | // Clone-on-write 1847 | //////////////////////////////////////////////////////////////////////////////// 1848 | 1849 | //////////////////////////////////////////////////////////////////////////////// 1850 | // Iterators 1851 | //////////////////////////////////////////////////////////////////////////////// 1852 | 1853 | /// An iterator that moves out of a vector. 1854 | /// 1855 | /// This `struct` is created by the `into_iter` method on [`Vec`] (provided by the [`IntoIterator`] 1856 | /// trait). 1857 | pub struct IntoIter { 1858 | buf: NonNull, 1859 | phantom: PhantomData, 1860 | cap: usize, 1861 | ptr: *const T, 1862 | end: *const T, 1863 | } 1864 | 1865 | impl fmt::Debug for IntoIter { 1866 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1867 | f.debug_tuple("IntoIter").field(&self.as_slice()).finish() 1868 | } 1869 | } 1870 | 1871 | impl IntoIter { 1872 | /// Returns the remaining items of this iterator as a slice. 1873 | /// 1874 | /// # Examples 1875 | /// 1876 | /// ``` 1877 | /// # use ve::vec; 1878 | /// let vec = vec!['a', 'b', 'c']; 1879 | /// let mut into_iter = vec.into_iter(); 1880 | /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); 1881 | /// let _ = into_iter.next().unwrap(); 1882 | /// assert_eq!(into_iter.as_slice(), &['b', 'c']); 1883 | /// ``` 1884 | pub fn as_slice(&self) -> &[T] { 1885 | unsafe { slice::from_raw_parts(self.ptr, self.len()) } 1886 | } 1887 | 1888 | /// Returns the remaining items of this iterator as a mutable slice. 1889 | /// 1890 | /// # Examples 1891 | /// 1892 | /// ``` 1893 | /// # use ve::vec; 1894 | /// let vec = vec!['a', 'b', 'c']; 1895 | /// let mut into_iter = vec.into_iter(); 1896 | /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); 1897 | /// into_iter.as_mut_slice()[2] = 'z'; 1898 | /// assert_eq!(into_iter.next().unwrap(), 'a'); 1899 | /// assert_eq!(into_iter.next().unwrap(), 'b'); 1900 | /// assert_eq!(into_iter.next().unwrap(), 'z'); 1901 | /// ``` 1902 | pub fn as_mut_slice(&mut self) -> &mut [T] { 1903 | unsafe { &mut *self.as_raw_mut_slice() } 1904 | } 1905 | 1906 | fn as_raw_mut_slice(&mut self) -> *mut [T] { 1907 | unsafe { &mut *ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len()) } 1908 | } 1909 | } 1910 | 1911 | impl AsRef<[T]> for IntoIter { 1912 | fn as_ref(&self) -> &[T] { 1913 | self.as_slice() 1914 | } 1915 | } 1916 | 1917 | unsafe impl Send for IntoIter {} 1918 | unsafe impl Sync for IntoIter {} 1919 | 1920 | impl Iterator for IntoIter { 1921 | type Item = T; 1922 | 1923 | #[inline] 1924 | fn next(&mut self) -> Option { 1925 | if self.ptr as *const _ == self.end { 1926 | None 1927 | } else if mem::size_of::() == 0 { 1928 | // purposely don't use 'ptr.offset' because for vectors with 0-size elements 1929 | // this would return the same pointer. 1930 | self.ptr = unsafe { arith_offset(self.ptr as *const T, 1) as *mut T }; 1931 | 1932 | // Make up a value of this ZST. 1933 | Some(unsafe { mem::zeroed() }) 1934 | } else { 1935 | let old = self.ptr; 1936 | self.ptr = unsafe { self.ptr.offset(1) }; 1937 | 1938 | Some(unsafe { ptr::read(old) }) 1939 | } 1940 | } 1941 | 1942 | #[inline] 1943 | fn size_hint(&self) -> (usize, Option) { 1944 | let exact = if mem::size_of::() == 0 { 1945 | (self.end as usize).wrapping_sub(self.ptr as usize) 1946 | } else { 1947 | unsafe { self.end.offset_from(self.ptr) as usize } 1948 | }; 1949 | (exact, Some(exact)) 1950 | } 1951 | 1952 | #[inline] 1953 | fn count(self) -> usize { 1954 | self.len() 1955 | } 1956 | } 1957 | 1958 | impl DoubleEndedIterator for IntoIter { 1959 | #[inline] 1960 | fn next_back(&mut self) -> Option { 1961 | if self.end == self.ptr { 1962 | None 1963 | } else if mem::size_of::() == 0 { 1964 | // See above for why 'ptr.offset' isn't used 1965 | self.end = unsafe { arith_offset(self.end as *const T, -1) as *mut T }; 1966 | 1967 | // Make up a value of this ZST. 1968 | Some(unsafe { mem::zeroed() }) 1969 | } else { 1970 | self.end = unsafe { self.end.offset(-1) }; 1971 | 1972 | Some(unsafe { ptr::read(self.end) }) 1973 | } 1974 | } 1975 | } 1976 | 1977 | impl ExactSizeIterator for IntoIter { 1978 | fn is_empty(&self) -> bool { 1979 | self.ptr == self.end 1980 | } 1981 | } 1982 | 1983 | impl FusedIterator for IntoIter {} 1984 | 1985 | unsafe impl TrustedLen for IntoIter {} 1986 | 1987 | impl Clone for IntoIter { 1988 | fn clone(&self) -> IntoIter { 1989 | Vec::from(self.as_slice()).into_iter() 1990 | } 1991 | } 1992 | 1993 | unsafe impl<#[may_dangle] T> Drop for IntoIter { 1994 | fn drop(&mut self) { 1995 | struct DropGuard<'a, T>(&'a mut IntoIter); 1996 | 1997 | impl Drop for DropGuard<'_, T> { 1998 | fn drop(&mut self) { 1999 | // RawVec handles deallocation 2000 | let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap, 0) }; 2001 | } 2002 | } 2003 | 2004 | let guard = DropGuard(self); 2005 | // destroy the remaining elements 2006 | unsafe { 2007 | ptr::drop_in_place(guard.0.as_raw_mut_slice()); 2008 | } 2009 | // now `guard` will be dropped and do the rest 2010 | } 2011 | } 2012 | 2013 | /// A draining iterator for `Vec`. 2014 | /// 2015 | /// This `struct` is created by the [`Vec::drain`]. 2016 | pub struct Drain<'a, T: 'a> { 2017 | /// Index of tail to preserve 2018 | tail_start: usize, 2019 | /// Length of tail 2020 | tail_len: usize, 2021 | /// Current remaining range to remove 2022 | iter: slice::Iter<'a, T>, 2023 | vec: NonNull>, 2024 | } 2025 | 2026 | impl fmt::Debug for Drain<'_, T> { 2027 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 2028 | f.debug_tuple("Drain").field(&self.iter.as_slice()).finish() 2029 | } 2030 | } 2031 | 2032 | impl<'a, T> Drain<'a, T> { 2033 | /// Returns the remaining items of this iterator as a slice. 2034 | /// 2035 | /// # Examples 2036 | /// 2037 | /// ``` 2038 | /// # use ve::vec; 2039 | /// let mut vec = vec!['a', 'b', 'c']; 2040 | /// let mut drain = vec.drain(..); 2041 | /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']); 2042 | /// let _ = drain.next().unwrap(); 2043 | /// assert_eq!(drain.as_slice(), &['b', 'c']); 2044 | /// ``` 2045 | pub fn as_slice(&self) -> &[T] { 2046 | self.iter.as_slice() 2047 | } 2048 | } 2049 | 2050 | impl<'a, T> AsRef<[T]> for Drain<'a, T> { 2051 | fn as_ref(&self) -> &[T] { 2052 | self.as_slice() 2053 | } 2054 | } 2055 | 2056 | unsafe impl Sync for Drain<'_, T> {} 2057 | unsafe impl Send for Drain<'_, T> {} 2058 | 2059 | impl Iterator for Drain<'_, T> { 2060 | type Item = T; 2061 | 2062 | #[inline] 2063 | fn next(&mut self) -> Option { 2064 | self.iter 2065 | .next() 2066 | .map(|elt| unsafe { ptr::read(elt as *const _) }) 2067 | } 2068 | 2069 | fn size_hint(&self) -> (usize, Option) { 2070 | self.iter.size_hint() 2071 | } 2072 | } 2073 | 2074 | impl DoubleEndedIterator for Drain<'_, T> { 2075 | #[inline] 2076 | fn next_back(&mut self) -> Option { 2077 | self.iter 2078 | .next_back() 2079 | .map(|elt| unsafe { ptr::read(elt as *const _) }) 2080 | } 2081 | } 2082 | 2083 | impl Drop for Drain<'_, T> { 2084 | fn drop(&mut self) { 2085 | /// Continues dropping the remaining elements in the `Drain`, then moves back the 2086 | /// un-`Drain`ed elements to restore the original `Vec`. 2087 | struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>); 2088 | 2089 | impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> { 2090 | fn drop(&mut self) { 2091 | // Continue the same loop we have below. If the loop already finished, this does 2092 | // nothing. 2093 | self.0.for_each(drop); 2094 | 2095 | if self.0.tail_len > 0 { 2096 | unsafe { 2097 | let source_vec = self.0.vec.as_mut(); 2098 | // memmove back untouched tail, update to new length 2099 | let start = source_vec.len(); 2100 | let tail = self.0.tail_start; 2101 | if tail != start { 2102 | let src = source_vec.as_ptr().add(tail); 2103 | let dst = source_vec.as_mut_ptr().add(start); 2104 | ptr::copy(src, dst, self.0.tail_len); 2105 | } 2106 | source_vec.set_len(start + self.0.tail_len); 2107 | } 2108 | } 2109 | } 2110 | } 2111 | 2112 | // exhaust self first 2113 | while let Some(item) = self.next() { 2114 | let guard = DropGuard(self); 2115 | drop(item); 2116 | mem::forget(guard); 2117 | } 2118 | 2119 | // Drop a `DropGuard` to move back the non-drained tail of `self`. 2120 | DropGuard(self); 2121 | } 2122 | } 2123 | 2124 | impl ExactSizeIterator for Drain<'_, T> { 2125 | fn is_empty(&self) -> bool { 2126 | self.iter.is_empty() 2127 | } 2128 | } 2129 | 2130 | impl FusedIterator for Drain<'_, T> {} 2131 | 2132 | /// A splicing iterator for `Vec`. 2133 | /// 2134 | /// This struct is created by the [`Vec::splice`]. 2135 | /// See its documentation for more. 2136 | #[derive(Debug)] 2137 | pub struct Splice<'a, I: Iterator + 'a> { 2138 | drain: Drain<'a, I::Item>, 2139 | replace_with: I, 2140 | } 2141 | 2142 | impl Iterator for Splice<'_, I> { 2143 | type Item = I::Item; 2144 | 2145 | fn next(&mut self) -> Option { 2146 | self.drain.next() 2147 | } 2148 | 2149 | fn size_hint(&self) -> (usize, Option) { 2150 | self.drain.size_hint() 2151 | } 2152 | } 2153 | 2154 | impl DoubleEndedIterator for Splice<'_, I> { 2155 | #[inline] 2156 | fn next_back(&mut self) -> Option { 2157 | self.drain.next_back() 2158 | } 2159 | } 2160 | 2161 | impl ExactSizeIterator for Splice<'_, I> {} 2162 | 2163 | impl Drop for Splice<'_, I> { 2164 | fn drop(&mut self) { 2165 | self.drain.by_ref().for_each(drop); 2166 | 2167 | unsafe { 2168 | if self.drain.tail_len == 0 { 2169 | self.drain.vec.as_mut().extend(self.replace_with.by_ref()); 2170 | return; 2171 | } 2172 | 2173 | // First fill the range left by drain(). 2174 | if !self.drain.fill(&mut self.replace_with) { 2175 | return; 2176 | } 2177 | 2178 | // There may be more elements. Use the lower bound as an estimate. 2179 | // FIXME: Is the upper bound a better guess? Or something else? 2180 | let (lower_bound, _upper_bound) = self.replace_with.size_hint(); 2181 | if lower_bound > 0 { 2182 | self.drain.move_tail(lower_bound); 2183 | if !self.drain.fill(&mut self.replace_with) { 2184 | return; 2185 | } 2186 | } 2187 | 2188 | // Collect any remaining elements. 2189 | // This is a zero-length vector which does not allocate if `lower_bound` was exact. 2190 | let mut collected = self 2191 | .replace_with 2192 | .by_ref() 2193 | .collect::>() 2194 | .into_iter(); 2195 | // Now we have an exact count. 2196 | if collected.len() > 0 { 2197 | self.drain.move_tail(collected.len()); 2198 | let filled = self.drain.fill(&mut collected); 2199 | debug_assert!(filled); 2200 | debug_assert_eq!(collected.len(), 0); 2201 | } 2202 | } 2203 | // Let `Drain::Drop` move the tail back if necessary and restore `vec.len`. 2204 | } 2205 | } 2206 | 2207 | /// Private helper methods for `Splice::Drop` 2208 | impl Drain<'_, T> { 2209 | /// The range from `self.vec.len` to `self.tail_start` contains elements that have been moved 2210 | /// out. 2211 | /// Fill that range as much as possible with the new elements from the `replace_with` iterator. 2212 | /// Returns `true` if we filled the entire range. (`replace_with.next()` didn't return `None`.) 2213 | unsafe fn fill>(&mut self, replace_with: &mut I) -> bool { 2214 | let vec = unsafe { self.vec.as_mut() }; 2215 | let range_start = vec.len(); 2216 | let range_end = self.tail_start; 2217 | let range_slice = unsafe { 2218 | slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start) 2219 | }; 2220 | 2221 | for place in range_slice { 2222 | if let Some(new_item) = replace_with.next() { 2223 | unsafe { 2224 | ptr::write(place, new_item); 2225 | vec.set_len(vec.len() + 1); 2226 | } 2227 | } else { 2228 | return false; 2229 | } 2230 | } 2231 | true 2232 | } 2233 | 2234 | // Makes room for inserting more elements before the tail. 2235 | unsafe fn move_tail(&mut self, additional: usize) { 2236 | let vec = unsafe { self.vec.as_mut() }; 2237 | let len = self.tail_start + self.tail_len; 2238 | vec.buf.reserve(len, additional); 2239 | 2240 | let new_tail_start = self.tail_start + additional; 2241 | unsafe { 2242 | let src = vec.as_ptr().add(self.tail_start); 2243 | let dst = vec.as_mut_ptr().add(new_tail_start); 2244 | ptr::copy(src, dst, self.tail_len); 2245 | } 2246 | self.tail_start = new_tail_start; 2247 | } 2248 | } 2249 | -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | mod vec; 2 | -------------------------------------------------------------------------------- /tests/vec.rs: -------------------------------------------------------------------------------- 1 | use std::mem::size_of; 2 | use ve::Vec; 3 | 4 | #[test] 5 | fn test_small_vec_struct() { 6 | assert_eq!(size_of::>(), size_of::() * 2); 7 | } 8 | --------------------------------------------------------------------------------