├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── deploy-docs.sh └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | matrix: 4 | include: 5 | - rust: nightly 6 | script: 7 | - cargo build 8 | - cargo test 9 | - cargo doc --no-deps 10 | after_success: | 11 | [ "$TRAVIS_RUST_VERSION" = nightly ] && 12 | [ "$TRAVIS_BRANCH" = master ] && 13 | [ "$TRAVIS_PULL_REQUEST" = false ] && 14 | bash deploy-docs.sh 15 | notifications: 16 | webhooks: http://huon.me:54857/travis 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "raw-vec" 3 | version = "0.2.0" 4 | authors = ["Alexis Beingessner "] 5 | 6 | license = "MIT/Apache-2.0" 7 | description = "A Raw utility for managing contiguous heap allocations" 8 | repository = "https://github.com/contain-rs/raw-vec" 9 | homepage = "https://github.com/contain-rs/raw-vec" 10 | documentation = "https://contain-rs.github.io/raw-vec/raw_vec" 11 | keywords = ["data-structures", "collections", "raw_vec", "vec", "contain-rs"] 12 | readme = "README.md" 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 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A Raw utility for managing contiguous heap allocations 2 | 3 | Documentation is available at https://contain-rs.github.io/raw-vec/raw_vec. 4 | 5 | -------------------------------------------------------------------------------- /deploy-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o errexit -o nounset 4 | 5 | rev=$(git rev-parse --short HEAD) 6 | 7 | cd target/doc 8 | 9 | git init 10 | git config user.email 'FlashCat@users.noreply.github.com' 11 | git config user.name 'FlashCat' 12 | git remote add upstream "https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" 13 | git fetch upstream gh-pages 14 | git reset upstream/gh-pages 15 | 16 | touch . 17 | 18 | git add -A . 19 | git commit -m "rebuild pages at ${rev}" 20 | git push -q upstream HEAD:gh-pages 21 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | #![feature(unsafe_no_drop_flag, unique, filling_drop, dropck_parametricity, allocator, box_syntax, alloc, heap_api, oom)] 12 | 13 | extern crate alloc; 14 | 15 | use std::ptr::Unique; 16 | use std::mem; 17 | use std::slice; 18 | use std::boxed::Box; 19 | use std::ops::Drop; 20 | use std::cmp; 21 | 22 | use alloc::heap; 23 | use alloc::oom; 24 | 25 | /// A low-level utility for more ergonomically allocating, reallocating, and deallocating a 26 | /// a buffer of memory on the heap without having to worry about all the corner cases 27 | /// involved. This type is excellent for building your own data structures like Vec and VecDeque. 28 | /// In particular: 29 | /// 30 | /// * Produces heap::EMPTY on zero-sized types 31 | /// * Produces heap::EMPTY on zero-length allocations 32 | /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics) 33 | /// * Guards against 32-bit systems allocating more than isize::MAX bytes 34 | /// * Guards against overflowing your length 35 | /// * Aborts on OOM 36 | /// * Avoids freeing heap::EMPTY 37 | /// * Contains a ptr::Unique and thus endows the user with all related benefits 38 | /// 39 | /// This type does not in anyway inspect the memory that it manages. When dropped it *will* 40 | /// free its memory, but it *won't* try to Drop its contents. It is up to the user of RawVec 41 | /// to handle the actual things *stored* inside of a RawVec. 42 | /// 43 | /// Note that a RawVec always forces its capacity to be usize::MAX for zero-sized types. 44 | /// This enables you to use capacity growing logic catch the overflows in your length 45 | /// that might occur with zero-sized types. 46 | /// 47 | /// However this means that you need to be careful when roundtripping this type 48 | /// with a `Box<[T]>`: `cap()` won't yield the len. However `with_capacity`, 49 | /// `shrink_to_fit`, and `from_box` will actually set RawVec's private capacity 50 | /// field. This allows zero-sized types to not be special-cased by consumers of 51 | /// this type. 52 | #[unsafe_no_drop_flag] 53 | pub struct RawVec { 54 | ptr: Unique, 55 | cap: usize, 56 | } 57 | 58 | impl RawVec { 59 | /// Creates the biggest possible RawVec without allocating. If T has positive 60 | /// size, then this makes a RawVec with capacity 0. If T has 0 size, then it 61 | /// it makes a RawVec with capacity `usize::MAX`. Useful for implementing 62 | /// delayed allocation. 63 | pub fn new() -> Self { 64 | unsafe { 65 | // !0 is usize::MAX. This branch should be stripped at compile time. 66 | let cap = if mem::size_of::() == 0 { 67 | !0 68 | } else { 69 | 0 70 | }; 71 | 72 | // heap::EMPTY doubles as "unallocated" and "zero-sized allocation" 73 | RawVec { 74 | ptr: Unique::new(heap::EMPTY as *mut T), 75 | cap: cap, 76 | } 77 | } 78 | } 79 | 80 | /// Creates a RawVec with exactly the capacity and alignment requirements 81 | /// for a `[T; cap]`. This is equivalent to calling RawVec::new when `cap` is 0 82 | /// or T is zero-sized. Note that if `T` is zero-sized this means you will *not* 83 | /// get a RawVec with the requested capacity! 84 | /// 85 | /// # Panics 86 | /// 87 | /// * Panics if the requested capacity exceeds `usize::MAX` bytes. 88 | /// * Panics on 32-bit platforms if the requested capacity exceeds 89 | /// `isize::MAX` bytes. 90 | /// 91 | /// # Aborts 92 | /// 93 | /// Aborts on OOM 94 | pub fn with_capacity(cap: usize) -> Self { 95 | unsafe { 96 | let elem_size = mem::size_of::(); 97 | 98 | let alloc_size = cap.checked_mul(elem_size).expect("capacity overflow"); 99 | alloc_guard(alloc_size); 100 | 101 | // handles ZSTs and `cap = 0` alike 102 | let ptr = if alloc_size == 0 { 103 | heap::EMPTY as *mut u8 104 | } else { 105 | let align = mem::align_of::(); 106 | let ptr = heap::allocate(alloc_size, align); 107 | if ptr.is_null() { 108 | oom() 109 | } 110 | ptr 111 | }; 112 | 113 | RawVec { 114 | ptr: Unique::new(ptr as *mut _), 115 | cap: cap, 116 | } 117 | } 118 | } 119 | 120 | /// Reconstitutes a RawVec from a pointer and capacity. 121 | /// 122 | /// # Undefined Behavior 123 | /// 124 | /// The ptr must be allocated, and with the given capacity. The 125 | /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems). 126 | /// If the ptr and capacity come from a RawVec, then this is guaranteed. 127 | pub unsafe fn from_raw_parts(ptr: *mut T, cap: usize) -> Self { 128 | RawVec { 129 | ptr: Unique::new(ptr), 130 | cap: cap, 131 | } 132 | } 133 | 134 | /// Converts a `Box<[T]>` into a `RawVec`. 135 | pub fn from_box(mut slice: Box<[T]>) -> Self { 136 | unsafe { 137 | let result = RawVec::from_raw_parts(slice.as_mut_ptr(), slice.len()); 138 | mem::forget(slice); 139 | result 140 | } 141 | } 142 | } 143 | 144 | impl RawVec { 145 | /// Gets a raw pointer to the start of the allocation. Note that this is 146 | /// heap::EMPTY if `cap = 0` or T is zero-sized. In the former case, you must 147 | /// be careful. 148 | pub fn ptr(&self) -> *mut T { 149 | *self.ptr 150 | } 151 | 152 | /// Gets the capacity of the allocation. 153 | /// 154 | /// This will always be `usize::MAX` if `T` is zero-sized. 155 | #[inline(always)] 156 | pub fn cap(&self) -> usize { 157 | if mem::size_of::() == 0 { 158 | !0 159 | } else { 160 | self.cap 161 | } 162 | } 163 | 164 | /// Doubles the size of the type's backing allocation. This is common enough 165 | /// to want to do that it's easiest to just have a dedicated method. Slightly 166 | /// more efficient logic can be provided for this than the general case. 167 | /// 168 | /// This function is ideal for when pushing elements one-at-a-time because 169 | /// you don't need to incur the costs of the more general computations 170 | /// reserve needs to do to guard against overflow. You do however need to 171 | /// manually check if your `len == cap`. 172 | /// 173 | /// # Panics 174 | /// 175 | /// * Panics if T is zero-sized on the assumption that you managed to exhaust 176 | /// all `usize::MAX` slots in your imaginary buffer. 177 | /// * Panics on 32-bit platforms if the requested capacity exceeds 178 | /// `isize::MAX` bytes. 179 | /// 180 | /// # Aborts 181 | /// 182 | /// Aborts on OOM 183 | /// 184 | /// # Examples 185 | /// 186 | /// ```ignore 187 | /// struct MyVec { 188 | /// buf: RawVec, 189 | /// len: usize, 190 | /// } 191 | /// 192 | /// impl MyVec { 193 | /// pub fn push(&mut self, elem: T) { 194 | /// if self.len == self.buf.cap() { self.buf.double(); } 195 | /// // double would have aborted or panicked if the len exceeded 196 | /// // `isize::MAX` so this is safe to do unchecked now. 197 | /// unsafe { 198 | /// ptr::write(self.buf.ptr().offset(self.len as isize), elem); 199 | /// } 200 | /// self.len += 1; 201 | /// } 202 | /// } 203 | /// ``` 204 | #[inline(never)] 205 | #[cold] 206 | pub fn double(&mut self) { 207 | unsafe { 208 | let elem_size = mem::size_of::(); 209 | 210 | // since we set the capacity to usize::MAX when elem_size is 211 | // 0, getting to here necessarily means the RawVec is overfull. 212 | assert!(elem_size != 0, "capacity overflow"); 213 | 214 | let align = mem::align_of::(); 215 | 216 | let (new_cap, ptr) = if self.cap == 0 { 217 | // skip to 4 because tiny Vec's are dumb; but not if that would cause overflow 218 | let new_cap = if elem_size > (!0) / 8 { 219 | 1 220 | } else { 221 | 4 222 | }; 223 | let ptr = heap::allocate(new_cap * elem_size, align); 224 | (new_cap, ptr) 225 | } else { 226 | // Since we guarantee that we never allocate more than isize::MAX bytes, 227 | // `elem_size * self.cap <= isize::MAX` as a precondition, so this can't overflow 228 | let new_cap = 2 * self.cap; 229 | let new_alloc_size = new_cap * elem_size; 230 | alloc_guard(new_alloc_size); 231 | let ptr = heap::reallocate(self.ptr() as *mut _, 232 | self.cap * elem_size, 233 | new_alloc_size, 234 | align); 235 | (new_cap, ptr) 236 | }; 237 | 238 | // If allocate or reallocate fail, we'll get `null` back 239 | if ptr.is_null() { 240 | oom() 241 | } 242 | 243 | self.ptr = Unique::new(ptr as *mut _); 244 | self.cap = new_cap; 245 | } 246 | } 247 | 248 | /// Attempts to double the size of the type's backing allocation in place. This is common 249 | /// enough to want to do that it's easiest to just have a dedicated method. Slightly 250 | /// more efficient logic can be provided for this than the general case. 251 | /// 252 | /// Returns true if the reallocation attempt has succeeded, or false otherwise. 253 | /// 254 | /// # Panics 255 | /// 256 | /// * Panics if T is zero-sized on the assumption that you managed to exhaust 257 | /// all `usize::MAX` slots in your imaginary buffer. 258 | /// * Panics on 32-bit platforms if the requested capacity exceeds 259 | /// `isize::MAX` bytes. 260 | #[inline(never)] 261 | #[cold] 262 | pub fn double_in_place(&mut self) -> bool { 263 | unsafe { 264 | let elem_size = mem::size_of::(); 265 | let align = mem::align_of::(); 266 | 267 | // since we set the capacity to usize::MAX when elem_size is 268 | // 0, getting to here necessarily means the RawVec is overfull. 269 | assert!(elem_size != 0, "capacity overflow"); 270 | 271 | // Since we guarantee that we never allocate more than isize::MAX bytes, 272 | // `elem_size * self.cap <= isize::MAX` as a precondition, so this can't overflow 273 | let new_cap = 2 * self.cap; 274 | let new_alloc_size = new_cap * elem_size; 275 | 276 | alloc_guard(new_alloc_size); 277 | let size = heap::reallocate_inplace(self.ptr() as *mut _, 278 | self.cap * elem_size, 279 | new_alloc_size, 280 | align); 281 | if size >= new_alloc_size { 282 | // We can't directly divide `size`. 283 | self.cap = new_cap; 284 | } 285 | size >= new_alloc_size 286 | } 287 | } 288 | 289 | /// Ensures that the buffer contains at least enough space to hold 290 | /// `used_cap + needed_extra_cap` elements. If it doesn't already, 291 | /// will reallocate the minimum possible amount of memory necessary. 292 | /// Generally this will be exactly the amount of memory necessary, 293 | /// but in principle the allocator is free to give back more than 294 | /// we asked for. 295 | /// 296 | /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate 297 | /// the requested space. This is not really unsafe, but the unsafe 298 | /// code *you* write that relies on the behavior of this function may break. 299 | /// 300 | /// # Panics 301 | /// 302 | /// * Panics if the requested capacity exceeds `usize::MAX` bytes. 303 | /// * Panics on 32-bit platforms if the requested capacity exceeds 304 | /// `isize::MAX` bytes. 305 | /// 306 | /// # Aborts 307 | /// 308 | /// Aborts on OOM 309 | pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) { 310 | unsafe { 311 | let elem_size = mem::size_of::(); 312 | let align = mem::align_of::(); 313 | 314 | // NOTE: we don't early branch on ZSTs here because we want this 315 | // to actually catch "asking for more than usize::MAX" in that case. 316 | // If we make it past the first branch then we are guaranteed to 317 | // panic. 318 | 319 | // Don't actually need any more capacity. 320 | // Wrapping in case they gave a bad `used_cap`. 321 | if self.cap().wrapping_sub(used_cap) >= needed_extra_cap { 322 | return; 323 | } 324 | 325 | // Nothing we can really do about these checks :( 326 | let new_cap = used_cap.checked_add(needed_extra_cap).expect("capacity overflow"); 327 | let new_alloc_size = new_cap.checked_mul(elem_size).expect("capacity overflow"); 328 | alloc_guard(new_alloc_size); 329 | 330 | let ptr = if self.cap == 0 { 331 | heap::allocate(new_alloc_size, align) 332 | } else { 333 | heap::reallocate(self.ptr() as *mut _, 334 | self.cap * elem_size, 335 | new_alloc_size, 336 | align) 337 | }; 338 | 339 | // If allocate or reallocate fail, we'll get `null` back 340 | if ptr.is_null() { 341 | oom() 342 | } 343 | 344 | self.ptr = Unique::new(ptr as *mut _); 345 | self.cap = new_cap; 346 | } 347 | } 348 | 349 | /// Calculates the buffer's new size given that it'll hold `used_cap + 350 | /// needed_extra_cap` elements. This logic is used in amortized reserve methods. 351 | /// Returns `(new_capacity, new_alloc_size)`. 352 | fn amortized_new_size(&self, used_cap: usize, needed_extra_cap: usize) -> (usize, usize) { 353 | let elem_size = mem::size_of::(); 354 | // Nothing we can really do about these checks :( 355 | let required_cap = used_cap.checked_add(needed_extra_cap) 356 | .expect("capacity overflow"); 357 | // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`. 358 | let double_cap = self.cap * 2; 359 | // `double_cap` guarantees exponential growth. 360 | let new_cap = cmp::max(double_cap, required_cap); 361 | let new_alloc_size = new_cap.checked_mul(elem_size).expect("capacity overflow"); 362 | (new_cap, new_alloc_size) 363 | } 364 | 365 | /// Ensures that the buffer contains at least enough space to hold 366 | /// `used_cap + needed_extra_cap` elements. If it doesn't already have 367 | /// enough capacity, will reallocate enough space plus comfortable slack 368 | /// space to get amortized `O(1)` behavior. Will limit this behavior 369 | /// if it would needlessly cause itself to panic. 370 | /// 371 | /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate 372 | /// the requested space. This is not really unsafe, but the unsafe 373 | /// code *you* write that relies on the behavior of this function may break. 374 | /// 375 | /// This is ideal for implementing a bulk-push operation like `extend`. 376 | /// 377 | /// # Panics 378 | /// 379 | /// * Panics if the requested capacity exceeds `usize::MAX` bytes. 380 | /// * Panics on 32-bit platforms if the requested capacity exceeds 381 | /// `isize::MAX` bytes. 382 | /// 383 | /// # Aborts 384 | /// 385 | /// Aborts on OOM 386 | /// 387 | /// # Examples 388 | /// 389 | /// ```ignore 390 | /// struct MyVec { 391 | /// buf: RawVec, 392 | /// len: usize, 393 | /// } 394 | /// 395 | /// impl MyVec { 396 | /// pub fn push_all(&mut self, elems: &[T]) { 397 | /// self.buf.reserve(self.len, elems.len()); 398 | /// // reserve would have aborted or panicked if the len exceeded 399 | /// // `isize::MAX` so this is safe to do unchecked now. 400 | /// for x in elems { 401 | /// unsafe { 402 | /// ptr::write(self.buf.ptr().offset(self.len as isize), x.clone()); 403 | /// } 404 | /// self.len += 1; 405 | /// } 406 | /// } 407 | /// } 408 | /// ``` 409 | pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) { 410 | unsafe { 411 | let elem_size = mem::size_of::(); 412 | let align = mem::align_of::(); 413 | 414 | // NOTE: we don't early branch on ZSTs here because we want this 415 | // to actually catch "asking for more than usize::MAX" in that case. 416 | // If we make it past the first branch then we are guaranteed to 417 | // panic. 418 | 419 | // Don't actually need any more capacity. 420 | // Wrapping in case they give a bad `used_cap` 421 | if self.cap().wrapping_sub(used_cap) >= needed_extra_cap { 422 | return; 423 | } 424 | 425 | let (new_cap, new_alloc_size) = self.amortized_new_size(used_cap, needed_extra_cap); 426 | // FIXME: may crash and burn on over-reserve 427 | alloc_guard(new_alloc_size); 428 | 429 | let ptr = if self.cap == 0 { 430 | heap::allocate(new_alloc_size, align) 431 | } else { 432 | heap::reallocate(self.ptr() as *mut _, 433 | self.cap * elem_size, 434 | new_alloc_size, 435 | align) 436 | }; 437 | 438 | // If allocate or reallocate fail, we'll get `null` back 439 | if ptr.is_null() { 440 | oom() 441 | } 442 | 443 | self.ptr = Unique::new(ptr as *mut _); 444 | self.cap = new_cap; 445 | } 446 | } 447 | 448 | /// Attempts to ensure that the buffer contains at least enough space to hold 449 | /// `used_cap + needed_extra_cap` elements. If it doesn't already have 450 | /// enough capacity, will reallocate in place enough space plus comfortable slack 451 | /// space to get amortized `O(1)` behaviour. Will limit this behaviour 452 | /// if it would needlessly cause itself to panic. 453 | /// 454 | /// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate 455 | /// the requested space. This is not really unsafe, but the unsafe 456 | /// code *you* write that relies on the behaviour of this function may break. 457 | /// 458 | /// Returns true if the reallocation attempt has succeeded, or false otherwise. 459 | /// 460 | /// # Panics 461 | /// 462 | /// * Panics if the requested capacity exceeds `usize::MAX` bytes. 463 | /// * Panics on 32-bit platforms if the requested capacity exceeds 464 | /// `isize::MAX` bytes. 465 | pub fn reserve_in_place(&mut self, used_cap: usize, needed_extra_cap: usize) -> bool { 466 | unsafe { 467 | let elem_size = mem::size_of::(); 468 | let align = mem::align_of::(); 469 | 470 | // NOTE: we don't early branch on ZSTs here because we want this 471 | // to actually catch "asking for more than usize::MAX" in that case. 472 | // If we make it past the first branch then we are guaranteed to 473 | // panic. 474 | 475 | // Don't actually need any more capacity. If the current `cap` is 0, we can't 476 | // reallocate in place. 477 | // Wrapping in case they give a bad `used_cap` 478 | if self.cap().wrapping_sub(used_cap) >= needed_extra_cap || self.cap == 0 { 479 | return false; 480 | } 481 | 482 | let (_, new_alloc_size) = self.amortized_new_size(used_cap, needed_extra_cap); 483 | // FIXME: may crash and burn on over-reserve 484 | alloc_guard(new_alloc_size); 485 | 486 | let size = heap::reallocate_inplace(self.ptr() as *mut _, 487 | self.cap * elem_size, 488 | new_alloc_size, 489 | align); 490 | if size >= new_alloc_size { 491 | self.cap = new_alloc_size / elem_size; 492 | } 493 | size >= new_alloc_size 494 | } 495 | } 496 | 497 | /// Shrinks the allocation down to the specified amount. If the given amount 498 | /// is 0, actually completely deallocates. 499 | /// 500 | /// # Panics 501 | /// 502 | /// Panics if the given amount is *larger* than the current capacity. 503 | /// 504 | /// # Aborts 505 | /// 506 | /// Aborts on OOM. 507 | pub fn shrink_to_fit(&mut self, amount: usize) { 508 | let elem_size = mem::size_of::(); 509 | let align = mem::align_of::(); 510 | 511 | // Set the `cap` because they might be about to promote to a `Box<[T]>` 512 | if elem_size == 0 { 513 | self.cap = amount; 514 | return; 515 | } 516 | 517 | // This check is my waterloo; it's the only thing Vec wouldn't have to do. 518 | assert!(self.cap >= amount, "Tried to shrink to a larger capacity"); 519 | 520 | if amount == 0 { 521 | mem::replace(self, RawVec::new()); 522 | } else if self.cap != amount { 523 | unsafe { 524 | // Overflow check is unnecessary as the vector is already at 525 | // least this large. 526 | let ptr = heap::reallocate(self.ptr() as *mut _, 527 | self.cap * elem_size, 528 | amount * elem_size, 529 | align); 530 | if ptr.is_null() { 531 | oom() 532 | } 533 | self.ptr = Unique::new(ptr as *mut _); 534 | } 535 | self.cap = amount; 536 | } 537 | } 538 | 539 | /// Converts the entire buffer into `Box<[T]>`. 540 | /// 541 | /// While it is not *strictly* Undefined Behavior to call 542 | /// this procedure while some of the RawVec is unintialized, 543 | /// it cetainly makes it trivial to trigger it. 544 | /// 545 | /// Note that this will correctly reconstitute any `cap` changes 546 | /// that may have been performed. (see description of type for details) 547 | pub unsafe fn into_box(self) -> Box<[T]> { 548 | // NOTE: not calling `cap()` here, actually using the real `cap` field! 549 | let slice = slice::from_raw_parts_mut(self.ptr(), self.cap); 550 | let output: Box<[T]> = Box::from_raw(slice); 551 | mem::forget(self); 552 | output 553 | } 554 | 555 | /// This is a stupid name in the hopes that someone will find this in the 556 | /// not too distant future and remove it with the rest of 557 | /// #[unsafe_no_drop_flag] 558 | pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool { 559 | self.cap != mem::POST_DROP_USIZE 560 | } 561 | } 562 | 563 | impl Drop for RawVec { 564 | #[unsafe_destructor_blind_to_params] 565 | /// Frees the memory owned by the RawVec *without* trying to Drop its contents. 566 | fn drop(&mut self) { 567 | let elem_size = mem::size_of::(); 568 | if elem_size != 0 && self.cap != 0 && self.unsafe_no_drop_flag_needs_drop() { 569 | let align = mem::align_of::(); 570 | 571 | let num_bytes = elem_size * self.cap; 572 | unsafe { 573 | heap::deallocate(*self.ptr as *mut _, num_bytes, align); 574 | } 575 | } 576 | } 577 | } 578 | 579 | 580 | 581 | // We need to guarantee the following: 582 | // * We don't ever allocate `> isize::MAX` byte-size objects 583 | // * We don't overflow `usize::MAX` and actually allocate too little 584 | // 585 | // On 64-bit we just need to check for overflow since trying to allocate 586 | // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add 587 | // an extra guard for this in case we're running on a platform which can use 588 | // all 4GB in user-space. e.g. PAE or x32 589 | 590 | #[inline] 591 | fn alloc_guard(alloc_size: usize) { 592 | if mem::size_of::() < 8 { 593 | assert!(alloc_size <= ::std::isize::MAX as usize, 594 | "capacity overflow"); 595 | } 596 | } 597 | 598 | 599 | #[cfg(test)] 600 | mod tests { 601 | use super::*; 602 | 603 | #[test] 604 | fn reserve_does_not_overallocate() { 605 | { 606 | let mut v: RawVec = RawVec::new(); 607 | // First `reserve` allocates like `reserve_exact` 608 | v.reserve(0, 9); 609 | assert_eq!(9, v.cap()); 610 | } 611 | 612 | { 613 | let mut v: RawVec = RawVec::new(); 614 | v.reserve(0, 7); 615 | assert_eq!(7, v.cap()); 616 | // 97 if more than double of 7, so `reserve` should work 617 | // like `reserve_exact`. 618 | v.reserve(7, 90); 619 | assert_eq!(97, v.cap()); 620 | } 621 | 622 | { 623 | let mut v: RawVec = RawVec::new(); 624 | v.reserve(0, 12); 625 | assert_eq!(12, v.cap()); 626 | v.reserve(12, 3); 627 | // 3 is less than half of 12, so `reserve` must grow 628 | // exponentially. At the time of writing this test grow 629 | // factor is 2, so new capacity is 24, however, grow factor 630 | // of 1.5 is OK too. Hence `>= 18` in assert. 631 | assert!(v.cap() >= 12 + 12 / 2); 632 | } 633 | } 634 | 635 | } 636 | --------------------------------------------------------------------------------