├── .cargo └── config.toml ├── .gitignore ├── .rustfmt.toml ├── Cargo.toml ├── LICENSE-APACHE.txt ├── LICENSE-MIT.txt ├── README.md ├── azure-pipelines.yml └── src └── lib.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [env] 2 | RUST_TEST_THREADS = "1" 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = true 2 | imports_layout = "Horizontal" 3 | merge_imports = true 4 | fn_args_layout = "Compressed" 5 | use_field_init_shorthand = true 6 | 7 | # To enable when stable 8 | # wrap_comments = true # https://github.com/rust-lang/rustfmt/issues/3347 9 | # reorder_impl_items = true # https://github.com/rust-lang/rustfmt/issues/3363 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cap" 3 | version = "0.1.2" 4 | license = "MIT OR Apache-2.0" 5 | authors = ["Alec Mocatta "] 6 | categories = [] 7 | keywords = [] 8 | description = """ 9 | An allocator that can track and limit memory usage. 10 | 11 | This crate provides a generic allocator that wraps another allocator, tracking memory usage and enabling limits to be set. 12 | """ 13 | repository = "https://github.com/alecmocatta/cap" 14 | homepage = "https://github.com/alecmocatta/cap" 15 | documentation = "https://docs.rs/cap" 16 | readme = "README.md" 17 | edition = "2018" 18 | exclude = ["/azure-pipelines.yml"] 19 | 20 | [badges] 21 | azure-devops = { project = "alecmocatta/cap", pipeline = "tests" } 22 | maintenance = { status = "passively-maintained" } 23 | 24 | [features] 25 | nightly = [] 26 | stats = [] 27 | 28 | [dependencies] 29 | -------------------------------------------------------------------------------- /LICENSE-APACHE.txt: -------------------------------------------------------------------------------- 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.txt: -------------------------------------------------------------------------------- 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 | # cap 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/cap.svg?maxAge=86400)](https://crates.io/crates/cap) 4 | [![MIT / Apache 2.0 licensed](https://img.shields.io/crates/l/cap.svg?maxAge=2592000)](#License) 5 | [![Build Status](https://dev.azure.com/alecmocatta/cap/_apis/build/status/tests?branchName=master)](https://dev.azure.com/alecmocatta/cap/_build/latest?branchName=master) 6 | 7 | [Docs](https://docs.rs/cap/0.1) 8 | 9 | An allocator that can track and limit memory usage. 10 | 11 | This crate provides a generic allocator that wraps another allocator, tracking memory usage and enabling limits to be set. 12 | 13 | ## Example 14 | 15 | It can be used by declaring a static and marking it with the `#[global_allocator]` attribute: 16 | 17 | ```rust 18 | use std::alloc; 19 | use cap::Cap; 20 | 21 | #[global_allocator] 22 | static ALLOCATOR: Cap = Cap::new(alloc::System, usize::max_value()); 23 | 24 | fn main() { 25 | // Set the limit to 30MiB. 26 | ALLOCATOR.set_limit(30 * 1024 * 1024).unwrap(); 27 | // ... 28 | println!("Currently allocated: {}B", ALLOCATOR.allocated()); 29 | } 30 | ``` 31 | 32 | ## License 33 | Licensed under either of 34 | 35 | * Apache License, Version 2.0, ([LICENSE-APACHE.txt](LICENSE-APACHE.txt) or http://www.apache.org/licenses/LICENSE-2.0) 36 | * MIT license ([LICENSE-MIT.txt](LICENSE-MIT.txt) or http://opensource.org/licenses/MIT) 37 | 38 | at your option. 39 | 40 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 41 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | trigger: ["master"] 2 | pr: ["master"] 3 | 4 | resources: 5 | repositories: 6 | - repository: templates 7 | type: github 8 | name: alecmocatta/azure-pipeline-templates 9 | endpoint: alecmocatta 10 | 11 | jobs: 12 | - template: rust.yml@templates 13 | parameters: 14 | endpoint: alecmocatta 15 | default: 16 | rust_toolchain: nightly 17 | rust_lint_toolchain: nightly-2023-03-09 18 | rust_flags: '' 19 | rust_features: ';stats' 20 | rust_target_check: '' 21 | rust_target_build: '' 22 | rust_target_run: '' 23 | matrix: 24 | windows: 25 | imageName: 'windows-2019' 26 | rust_target_run: 'x86_64-pc-windows-msvc i686-pc-windows-msvc' # currently broken building crate-type=lib: x86_64-pc-windows-gnu i686-pc-windows-gnu 27 | mac: 28 | imageName: 'macOS-10.15' 29 | rust_target_run: 'x86_64-apple-darwin' 30 | linux: 31 | imageName: 'ubuntu-18.04' 32 | rust_target_run: 'x86_64-unknown-linux-gnu i686-unknown-linux-gnu x86_64-unknown-linux-musl i686-unknown-linux-musl' 33 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! An allocator that can track and limit memory usage. 2 | //! 3 | //! **[Crates.io](https://crates.io/crates/cap) │ [Repo](https://github.com/alecmocatta/cap)** 4 | //! 5 | //! This crate provides a generic allocator that wraps another allocator, tracking memory usage and enabling limits to be set. 6 | //! 7 | //! # Example 8 | //! 9 | //! It can be used by declaring a static and marking it with the `#[global_allocator]` attribute: 10 | //! 11 | //! ``` 12 | //! use std::alloc; 13 | //! use cap::Cap; 14 | //! 15 | //! #[global_allocator] 16 | //! static ALLOCATOR: Cap = Cap::new(alloc::System, usize::max_value()); 17 | //! 18 | //! fn main() { 19 | //! // Set the limit to 30MiB. 20 | //! ALLOCATOR.set_limit(30 * 1024 * 1024).unwrap(); 21 | //! // ... 22 | //! println!("Currently allocated: {}B", ALLOCATOR.allocated()); 23 | //! } 24 | //! ``` 25 | 26 | #![cfg_attr(feature = "nightly", feature(allocator_api))] 27 | #![cfg_attr( 28 | all(test, feature = "nightly"), 29 | feature(try_reserve, test, custom_test_frameworks) 30 | )] 31 | #![cfg_attr(all(test, feature = "nightly"), test_runner(tests::runner))] 32 | #![warn( 33 | missing_copy_implementations, 34 | missing_debug_implementations, 35 | missing_docs, 36 | trivial_casts, 37 | trivial_numeric_casts, 38 | unused_import_braces, 39 | unused_qualifications, 40 | unused_results, 41 | clippy::pedantic 42 | )] // from https://github.com/rust-unofficial/patterns/blob/master/anti_patterns/deny-warnings.md 43 | #![allow( 44 | clippy::result_unit_err, 45 | clippy::let_underscore_untyped, 46 | clippy::missing_errors_doc 47 | )] 48 | 49 | #[cfg(feature = "nightly")] 50 | use std::alloc::{Alloc, AllocErr, CannotReallocInPlace}; 51 | use std::{ 52 | alloc::{GlobalAlloc, Layout}, ptr, sync::atomic::{AtomicUsize, Ordering} 53 | }; 54 | 55 | /// A struct that wraps another allocator and limits the number of bytes that can be allocated. 56 | #[derive(Debug)] 57 | pub struct Cap { 58 | allocator: H, 59 | remaining: AtomicUsize, 60 | limit: AtomicUsize, 61 | #[cfg(feature = "stats")] 62 | total_allocated: AtomicUsize, 63 | #[cfg(feature = "stats")] 64 | max_allocated: AtomicUsize, 65 | } 66 | 67 | impl Cap { 68 | /// Create a new allocator, wrapping the supplied allocator and enforcing the specified limit. 69 | /// 70 | /// For no limit, simply set the limit to the theoretical maximum `usize::max_value()`. 71 | pub const fn new(allocator: H, limit: usize) -> Self { 72 | Self { 73 | allocator, 74 | remaining: AtomicUsize::new(limit), 75 | limit: AtomicUsize::new(limit), 76 | #[cfg(feature = "stats")] 77 | total_allocated: AtomicUsize::new(0), 78 | #[cfg(feature = "stats")] 79 | max_allocated: AtomicUsize::new(0), 80 | } 81 | } 82 | 83 | /// Return the number of bytes remaining within the limit. 84 | /// 85 | /// i.e. `limit - allocated` 86 | pub fn remaining(&self) -> usize { 87 | self.remaining.load(Ordering::Relaxed) 88 | } 89 | 90 | /// Return the limit in bytes. 91 | pub fn limit(&self) -> usize { 92 | self.limit.load(Ordering::Relaxed) 93 | } 94 | 95 | /// Set the limit in bytes. 96 | /// 97 | /// For no limit, simply set the limit to the theoretical maximum `usize::max_value()`. 98 | /// 99 | /// This method will return `Err` if the specified limit is less than the number of bytes already allocated. 100 | pub fn set_limit(&self, limit: usize) -> Result<(), ()> { 101 | loop { 102 | let limit_old = self.limit.load(Ordering::Relaxed); 103 | if limit < limit_old { 104 | if self 105 | .remaining 106 | .fetch_sub(limit_old - limit, Ordering::Relaxed) 107 | < limit_old - limit 108 | { 109 | let _ = self 110 | .remaining 111 | .fetch_add(limit_old - limit, Ordering::Relaxed); 112 | break Err(()); 113 | } 114 | if self 115 | .limit 116 | .compare_exchange(limit_old, limit, Ordering::Relaxed, Ordering::Relaxed) 117 | .is_err() 118 | { 119 | continue; 120 | } 121 | } else { 122 | if self 123 | .limit 124 | .compare_exchange(limit_old, limit, Ordering::Relaxed, Ordering::Relaxed) 125 | .is_err() 126 | { 127 | continue; 128 | } 129 | let _ = self 130 | .remaining 131 | .fetch_add(limit - limit_old, Ordering::Relaxed); 132 | } 133 | break Ok(()); 134 | } 135 | } 136 | 137 | /// Return the number of bytes allocated. Always less than the limit. 138 | pub fn allocated(&self) -> usize { 139 | // Make reasonable effort to get valid output 140 | loop { 141 | let limit_old = self.limit.load(Ordering::SeqCst); 142 | let remaining = self.remaining.load(Ordering::SeqCst); 143 | let limit = self.limit.load(Ordering::SeqCst); 144 | if limit_old == limit && limit >= remaining { 145 | break limit - remaining; 146 | } 147 | } 148 | } 149 | 150 | /// Get total amount of allocated memory. This includes already deallocated memory. 151 | #[cfg(feature = "stats")] 152 | pub fn total_allocated(&self) -> usize { 153 | self.total_allocated.load(Ordering::Relaxed) 154 | } 155 | 156 | /// Get maximum amount of memory that was allocated at any point in time. 157 | #[cfg(feature = "stats")] 158 | pub fn max_allocated(&self) -> usize { 159 | self.max_allocated.load(Ordering::Relaxed) 160 | } 161 | 162 | fn update_stats(&self, size: usize) { 163 | #[cfg(feature = "stats")] 164 | { 165 | let _ = self.total_allocated.fetch_add(size, Ordering::Relaxed); 166 | // If max_allocated is less than currently allocated, then it will be updated to limit - remaining. 167 | // Otherwise, it will remain unchanged. 168 | let _ = self 169 | .max_allocated 170 | .fetch_max(self.allocated(), Ordering::Relaxed); 171 | } 172 | #[cfg(not(feature = "stats"))] 173 | { 174 | let _ = (self, size); 175 | } 176 | } 177 | } 178 | 179 | unsafe impl GlobalAlloc for Cap 180 | where 181 | H: GlobalAlloc, 182 | { 183 | unsafe fn alloc(&self, l: Layout) -> *mut u8 { 184 | let size = l.size(); 185 | let res = if self.remaining.fetch_sub(size, Ordering::Acquire) >= size { 186 | self.allocator.alloc(l) 187 | } else { 188 | ptr::null_mut() 189 | }; 190 | if res.is_null() { 191 | let _ = self.remaining.fetch_add(size, Ordering::Release); 192 | } else { 193 | self.update_stats(size); 194 | } 195 | res 196 | } 197 | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { 198 | let size = layout.size(); 199 | self.allocator.dealloc(ptr, layout); 200 | let _ = self.remaining.fetch_add(size, Ordering::Release); 201 | } 202 | unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 { 203 | let size = l.size(); 204 | let res = if self.remaining.fetch_sub(size, Ordering::Acquire) >= size { 205 | self.allocator.alloc_zeroed(l) 206 | } else { 207 | ptr::null_mut() 208 | }; 209 | if res.is_null() { 210 | let _ = self.remaining.fetch_add(size, Ordering::Release); 211 | } else { 212 | self.update_stats(size); 213 | } 214 | res 215 | } 216 | unsafe fn realloc(&self, ptr: *mut u8, old_l: Layout, new_s: usize) -> *mut u8 { 217 | let new_l = Layout::from_size_align_unchecked(new_s, old_l.align()); 218 | let (old_size, new_size) = (old_l.size(), new_l.size()); 219 | let res = if new_size > old_size { 220 | let res = if self 221 | .remaining 222 | .fetch_sub(new_size - old_size, Ordering::Acquire) 223 | >= new_size - old_size 224 | { 225 | self.allocator.realloc(ptr, old_l, new_s) 226 | } else { 227 | ptr::null_mut() 228 | }; 229 | if res.is_null() { 230 | let _ = self 231 | .remaining 232 | .fetch_add(new_size - old_size, Ordering::Release); 233 | } 234 | res 235 | } else { 236 | let res = self.allocator.realloc(ptr, old_l, new_s); 237 | if !res.is_null() { 238 | let _ = self 239 | .remaining 240 | .fetch_add(old_size - new_size, Ordering::Release); 241 | } 242 | // Although this might just deaalocate, I will still update the stats as if it allocates to be on "the safe side" 243 | res 244 | }; 245 | if !res.is_null() { 246 | self.update_stats(new_size); 247 | } 248 | res 249 | } 250 | } 251 | 252 | #[cfg(feature = "nightly")] 253 | unsafe impl Alloc for Cap 254 | where 255 | H: Alloc, 256 | { 257 | unsafe fn alloc(&mut self, l: Layout) -> Result, AllocErr> { 258 | let size = self.allocator.usable_size(&l).1; 259 | let res = if self.remaining.fetch_sub(size, Ordering::Acquire) >= size { 260 | self.allocator.alloc(l) 261 | } else { 262 | Err(AllocErr) 263 | }; 264 | if res.is_err() { 265 | let _ = self.remaining.fetch_add(size, Ordering::Release); 266 | } else { 267 | self.update_stats(size); 268 | } 269 | res 270 | } 271 | unsafe fn dealloc(&mut self, item: ptr::NonNull, l: Layout) { 272 | let size = self.allocator.usable_size(&l).1; 273 | self.allocator.dealloc(item, l); 274 | let _ = self.remaining.fetch_add(size, Ordering::Release); 275 | } 276 | fn usable_size(&self, layout: &Layout) -> (usize, usize) { 277 | self.allocator.usable_size(layout) 278 | } 279 | unsafe fn realloc( 280 | &mut self, ptr: ptr::NonNull, old_l: Layout, new_s: usize, 281 | ) -> Result, AllocErr> { 282 | let new_l = Layout::from_size_align_unchecked(new_s, old_l.align()); 283 | let (old_size, new_size) = ( 284 | self.allocator.usable_size(&old_l).1, 285 | self.allocator.usable_size(&new_l).1, 286 | ); 287 | let res = if new_size > old_size { 288 | let res = if self 289 | .remaining 290 | .fetch_sub(new_size - old_size, Ordering::Acquire) 291 | >= new_size - old_size 292 | { 293 | self.allocator.realloc(ptr, old_l, new_s) 294 | } else { 295 | Err(AllocErr) 296 | }; 297 | if res.is_err() { 298 | let _ = self 299 | .remaining 300 | .fetch_add(new_size - old_size, Ordering::Release); 301 | } 302 | res 303 | } else { 304 | let res = self.allocator.realloc(ptr, old_l, new_s); 305 | if res.is_ok() { 306 | let _ = self 307 | .remaining 308 | .fetch_add(old_size - new_size, Ordering::Release); 309 | } 310 | res 311 | }; 312 | if res.is_ok() { 313 | self.update_stats(new_size); 314 | } 315 | res 316 | } 317 | unsafe fn alloc_zeroed(&mut self, l: Layout) -> Result, AllocErr> { 318 | let size = self.allocator.usable_size(&l).1; 319 | let res = if self.remaining.fetch_sub(size, Ordering::Acquire) >= size { 320 | self.allocator.alloc_zeroed(l) 321 | } else { 322 | Err(AllocErr) 323 | }; 324 | if res.is_err() { 325 | let _ = self.remaining.fetch_add(size, Ordering::Release); 326 | } else { 327 | self.update_stats(size); 328 | } 329 | res 330 | } 331 | unsafe fn grow_in_place( 332 | &mut self, ptr: ptr::NonNull, old_l: Layout, new_s: usize, 333 | ) -> Result<(), CannotReallocInPlace> { 334 | let new_l = Layout::from_size_align(new_s, old_l.align()).unwrap(); 335 | let (old_size, new_size) = ( 336 | self.allocator.usable_size(&old_l).1, 337 | self.allocator.usable_size(&new_l).1, 338 | ); 339 | let res = if self 340 | .remaining 341 | .fetch_sub(new_size - old_size, Ordering::Acquire) 342 | >= new_size - old_size 343 | { 344 | self.allocator.grow_in_place(ptr, old_l, new_s) 345 | } else { 346 | Err(CannotReallocInPlace) 347 | }; 348 | if res.is_err() { 349 | let _ = self 350 | .remaining 351 | .fetch_add(new_size - old_size, Ordering::Release); 352 | } else { 353 | self.update_stats(new_size - old_size); 354 | } 355 | res 356 | } 357 | unsafe fn shrink_in_place( 358 | &mut self, ptr: ptr::NonNull, old_l: Layout, new_s: usize, 359 | ) -> Result<(), CannotReallocInPlace> { 360 | let new_l = Layout::from_size_align(new_s, old_l.align()).unwrap(); 361 | let (old_size, new_size) = ( 362 | self.allocator.usable_size(&old_l).1, 363 | self.allocator.usable_size(&new_l).1, 364 | ); 365 | let res = self.allocator.shrink_in_place(ptr, old_l, new_s); 366 | if res.is_ok() { 367 | let _ = self 368 | .remaining 369 | .fetch_add(old_size - new_size, Ordering::Release); 370 | } 371 | res 372 | } 373 | } 374 | 375 | #[cfg(test)] 376 | mod tests { 377 | #[cfg(all(test, feature = "nightly"))] 378 | extern crate test; 379 | #[cfg(all(test, feature = "nightly"))] 380 | use std::collections::TryReserveError; 381 | use std::{alloc, thread}; 382 | #[cfg(all(test, feature = "nightly"))] 383 | use test::{TestDescAndFn, TestFn}; 384 | 385 | use super::Cap; 386 | 387 | #[global_allocator] 388 | static A: Cap = Cap::new(alloc::System, usize::max_value()); 389 | 390 | #[cfg(all(test, feature = "nightly"))] 391 | pub fn runner(tests: &[&TestDescAndFn]) { 392 | for test in tests { 393 | if let TestFn::StaticTestFn(test_fn) = test.testfn { 394 | test_fn(); 395 | } else { 396 | unimplemented!(); 397 | } 398 | } 399 | } 400 | 401 | #[test] 402 | fn concurrent() { 403 | let allocated = A.allocated(); 404 | for _ in 0..100 { 405 | let threads = (0..100) 406 | .map(|_| { 407 | thread::spawn(|| { 408 | for i in 0..1000 { 409 | let _ = (0..i).collect::>(); 410 | let _ = (0..i).flat_map(std::iter::once).collect::>(); 411 | } 412 | }) 413 | }) 414 | .collect::>(); 415 | threads 416 | .into_iter() 417 | .for_each(|thread| thread.join().unwrap()); 418 | let allocated2 = A.allocated(); 419 | #[cfg(feature = "stats")] 420 | let total_allocated = A.total_allocated(); 421 | if cfg!(all(test, feature = "nightly")) { 422 | assert_eq!(allocated, allocated2); 423 | #[cfg(feature = "stats")] 424 | assert!(total_allocated >= allocated); 425 | } 426 | } 427 | #[cfg(feature = "stats")] 428 | assert!(A.max_allocated() < A.total_allocated()); 429 | } 430 | 431 | #[cfg(all(test, not(feature = "nightly")))] 432 | #[test] 433 | fn limit() { 434 | #[cfg(feature = "stats")] 435 | let initial = A.allocated(); 436 | let allocate_amount = 30 * 1024 * 1024; 437 | A.set_limit(A.allocated() + allocate_amount).unwrap(); 438 | for _ in 0..10 { 439 | let mut vec = Vec::::with_capacity(0); 440 | if let Err(_e) = vec.try_reserve_exact(allocate_amount + 1) { 441 | } else { 442 | A.set_limit(usize::max_value()).unwrap(); 443 | panic!("{}", A.remaining()); 444 | }; 445 | assert_eq!(vec.try_reserve_exact(allocate_amount), Ok(())); 446 | let mut vec2 = Vec::::with_capacity(0); 447 | assert!(vec2.try_reserve_exact(1).is_err()); 448 | } 449 | // Might have additional allocations of errors and what not along the way. 450 | #[cfg(feature = "stats")] 451 | { 452 | assert!(A.total_allocated() >= initial + 10 * allocate_amount); 453 | assert_eq!(A.max_allocated(), initial + allocate_amount); 454 | } 455 | } 456 | 457 | #[cfg(all(test, feature = "nightly"))] 458 | #[test] 459 | fn limit() { 460 | let allocate_amount = 30 * 1024 * 1024; 461 | A.set_limit(A.allocated() + allocate_amount).unwrap(); 462 | for _ in 0..10 { 463 | let mut vec = Vec::::with_capacity(0); 464 | if let Err(TryReserveError::AllocError { .. }) = 465 | vec.try_reserve_exact(allocate_amount + 1) 466 | { 467 | } else { 468 | A.set_limit(usize::max_value()).unwrap(); 469 | panic!("{}", A.remaining()) 470 | }; 471 | assert_eq!(vec.try_reserve_exact(allocate_amount), Ok(())); 472 | let mut vec2 = Vec::::with_capacity(0); 473 | assert!(vec2.try_reserve_exact(1).is_err()); 474 | } 475 | assert_eq!(A.total_allocated(), 10 * allocate_amount); 476 | assert_eq!(A.max_allocated(), allocate_amount) 477 | } 478 | } 479 | --------------------------------------------------------------------------------