memuse-0.2.1/.cargo_vcs_info.json0000644000000001120000000000000123200ustar { "git": { "sha1": "8ddcbcb4a26098a73b79764b4550ae62b2632dac" } } memuse-0.2.1/.github/workflows/ci.yml000064400000000000000000000037620000000000000156170ustar 00000000000000name: CI checks on: [push, pull_request] jobs: test: name: Test on ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: 1.51.0 override: true - name: Run tests uses: actions-rs/cargo@v1 with: command: test args: --verbose --release --all --all-features build: name: Build target ${{ matrix.target }} runs-on: ubuntu-latest strategy: matrix: target: - wasm32-unknown-unknown - wasm32-wasi steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: 1.51.0 override: true - name: Add target run: rustup target add ${{ matrix.target }} - name: cargo build uses: actions-rs/cargo@v1 with: command: build args: --all-features doc-links: name: Intra-doc links runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: 1.51.0 override: true - name: cargo fetch uses: actions-rs/cargo@v1 with: command: fetch # Ensure intra-documentation links all resolve correctly # Requires #![deny(intra_doc_link_resolution_failure)] in crates. - name: Check intra-doc links uses: actions-rs/cargo@v1 with: command: doc args: --all --document-private-items fmt: name: Rustfmt timeout-minutes: 30 runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: 1.51.0 override: true - run: rustup component add rustfmt - uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check memuse-0.2.1/.github/workflows/lints-beta.yml000064400000000000000000000013100000000000000172510ustar 00000000000000name: Beta lints # These lints are only informative, so we only run them directly on branches # and not trial-merges of PRs, to reduce noise. on: push jobs: clippy-beta: name: Clippy (beta) timeout-minutes: 30 runs-on: ubuntu-latest continue-on-error: true steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: beta components: clippy override: true - name: Run Clippy (beta) uses: actions-rs/clippy-check@v1 continue-on-error: true with: name: Clippy (beta) token: ${{ secrets.GITHUB_TOKEN }} args: --all-features --all-targets -- -W clippy::all memuse-0.2.1/.github/workflows/lints-stable.yml000064400000000000000000000011220000000000000176110ustar 00000000000000name: Stable lints # We only run these lints on trial-merges of PRs to reduce noise. on: pull_request jobs: clippy: name: Clippy (1.51.0) timeout-minutes: 30 runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: 1.51.0 components: clippy override: true - name: Run clippy uses: actions-rs/clippy-check@v1 with: name: Clippy (1.51.0) token: ${{ secrets.GITHUB_TOKEN }} args: --all-features --all-targets -- -D warnings memuse-0.2.1/.gitignore000064400000000000000000000000230000000000000130570ustar 00000000000000/target Cargo.lock memuse-0.2.1/CHANGELOG.md000064400000000000000000000016650000000000000127150ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to Rust's notion of [Semantic Versioning](https://semver.org/spec/v2.0.0.html). All versions prior to 1.0.0 are beta releases. ## [0.2.1] - 2022-09-24 ### Added - `impl_no_dynamic_usage!()` helper macro to implement `DynamicUsage` for simple types that don't allocate. ## [0.2.0] - 2021-09-14 ### Added - `memuse::DynamicUsage` impls for the following types: - `()` - `str` - `[T: DynamicUsage]` - `Box` - `Result` ### Removed - `memuse::DynamicUsage` impls for `&str` and `&[T]` (replaced by the impls on `str` and `[T]`). - `memuse::NoDynamicUsage` trait (which was causing trait inference problems that prevented `&T` and `Box` from working). ## [0.1.0] - 2021-09-05 Initial release! memuse-0.2.1/Cargo.toml0000644000000020350000000000000103240ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "memuse" version = "0.2.1" authors = ["Jack Grigg "] description = "Traits for measuring dynamic memory usage of types" homepage = "https://github.com/str4d/memuse" documentation = "https://docs.rs/memuse/" readme = "README.md" keywords = ["heap", "allocation", "measurement"] categories = ["development-tools::profiling", "memory-management"] license = "MIT/Apache-2.0" repository = "https://github.com/str4d/memuse" [dependencies.nonempty] version = "0.7" optional = true memuse-0.2.1/Cargo.toml.orig000064400000000000000000000010300000000000000137550ustar 00000000000000[package] name = "memuse" description = "Traits for measuring dynamic memory usage of types" version = "0.2.1" authors = ["Jack Grigg "] documentation = "https://docs.rs/memuse/" homepage = "https://github.com/str4d/memuse" repository = "https://github.com/str4d/memuse" license = "MIT/Apache-2.0" edition = "2018" readme = "README.md" keywords = ["heap", "allocation", "measurement"] categories = ["development-tools::profiling", "memory-management"] [dependencies] nonempty = { version = "0.7", optional = true } memuse-0.2.1/LICENSE-APACHE000064400000000000000000000251400000000000000130220ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. memuse-0.2.1/LICENSE-MIT000064400000000000000000000020650000000000000125330ustar 00000000000000The MIT License (MIT) Copyright (c) 2021 Jack Grigg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. memuse-0.2.1/README.md000064400000000000000000000041330000000000000123540ustar 00000000000000# memuse This crate contains traits for measuring the dynamic memory usage of Rust types. ## About Memory-tracking is a common activity in large applications, particularly ones that receive data from a network and store it in memory. By monitoring how much memory is used by different areas of the application, memory pressure can be alleviated by ignoring new packets, or implementing random drop logic for DoS mitigation. Measuring memory use on the stack is easy, with [`std::mem::size_of`] and friends. Measuring memory allocated on the heap is more tricky. Applications can use a custom global allocator to track the memory usage of different areas. This isn't an option for reusable library code however, and the nearest alternative (using custom allocators for individual types) is currently only an experimental feature in nightly Rust ([`allocator_api`]). [`std::mem::size_of`]: https://doc.rust-lang.org/stable/std/mem/fn.size_of.html [`allocator_api`]: https://github.com/rust-lang/rust/issues/32838 This crate takes a different approach: it provides traits that library authors can use to expose dynamic memory usage information on their types. By composing these implementations, we gain the ability to query the amount of heap-allocated memory in use by specific instances of types at any point in time, without any changes to the way in which these types are constructed. ## Minimum Supported Rust Version Rust **1.51** or newer. In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this crate's SemVer guarantees), however when we do it will be accompanied by a minor version bump. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution 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. memuse-0.2.1/rust-toolchain000064400000000000000000000000070000000000000137670ustar 000000000000001.51.0 memuse-0.2.1/src/hash.rs000064400000000000000000000111640000000000000131570ustar 00000000000000//! `DynamicUsage` impls for `HashMap` and `HashSet`. //! //! Rust's `HashMap` and `HashSet` are backed by the the `hashbrown` crate. use core::mem; use std::{ alloc::Layout, collections::{HashMap, HashSet}, }; use crate::DynamicUsage; // The widths are sourced from here: // https://github.com/rust-lang/hashbrown/blob/dbd6dbe30a4076c0ea65ca5bd57036c27f3cc7c9/src/raw/mod.rs#L15-L36 // https://github.com/rust-lang/hashbrown/blob/dbd6dbe30a4076c0ea65ca5bd57036c27f3cc7c9/src/raw/generic.rs#L5-L21 // https://github.com/rust-lang/hashbrown/blob/dbd6dbe30a4076c0ea65ca5bd57036c27f3cc7c9/src/raw/sse2.rs#L14-L19 #[cfg(all(target_feature = "sse2", target_arch = "x86", not(miri)))] pub(crate) const WIDTH: usize = mem::size_of::(); #[cfg(all(target_feature = "sse2", target_arch = "x86_64", not(miri)))] pub(crate) const WIDTH: usize = mem::size_of::(); #[cfg(all( any(not(target_feature = "sse2"), miri), any( target_pointer_width = "64", target_arch = "aarch64", target_arch = "x86_64", target_arch = "wasm32", ) ))] pub(crate) const WIDTH: usize = mem::size_of::(); #[cfg(all( any(not(target_feature = "sse2"), miri), target_pointer_width = "32", not(target_arch = "aarch64"), not(target_arch = "x86_64"), not(target_arch = "wasm32"), ))] pub(crate) const WIDTH: usize = mem::size_of::(); fn dynamic_usage_for_capacity(cap: usize) -> usize { // The bucket calculation is sourced from here: // https://github.com/rust-lang/hashbrown/blob/dbd6dbe30a4076c0ea65ca5bd57036c27f3cc7c9/src/raw/mod.rs#L187-L216 // // hashbrown's RawTable::buckets is not accessible via the std HashMap, and // HashMap::capacity is a lower bound. However, hashbrown has an invariant that // the number of buckets is a power of two, so usually we'll calculate the correct // memory usage, and occasionally we'll undercount by around a factor of two. let buckets = { if cap < 8 { return if cap < 4 { 4 } else { 8 }; } let adjusted_cap = (cap * 8) / 7; adjusted_cap.next_power_of_two() }; // The memory usage calculation is sourced from here: // https://github.com/rust-lang/hashbrown/blob/dbd6dbe30a4076c0ea65ca5bd57036c27f3cc7c9/src/raw/mod.rs#L240-L265 let layout = Layout::new::<(K, V)>(); let size = layout.size(); let ctrl_align = usize::max(layout.align(), WIDTH); let ctrl_offset = (size * buckets + ctrl_align - 1) & !(ctrl_align - 1); ctrl_offset + buckets + WIDTH } impl DynamicUsage for HashMap { fn dynamic_usage(&self) -> usize { dynamic_usage_for_capacity::(self.capacity()) + self .iter() .map(|(k, v)| k.dynamic_usage() + v.dynamic_usage()) .sum::() } fn dynamic_usage_bounds(&self) -> (usize, Option) { ( dynamic_usage_for_capacity::(self.capacity()) + self .iter() .map(|(k, v)| k.dynamic_usage_bounds().0 + v.dynamic_usage_bounds().0) .sum::(), None, ) } } impl DynamicUsage for HashSet { fn dynamic_usage(&self) -> usize { // HashSet is just HashMap dynamic_usage_for_capacity::(self.capacity()) + self.iter().map(DynamicUsage::dynamic_usage).sum::() } fn dynamic_usage_bounds(&self) -> (usize, Option) { ( dynamic_usage_for_capacity::(self.capacity()) + self .iter() .map(|k| k.dynamic_usage_bounds().0) .sum::(), None, ) } } #[cfg(test)] mod tests { use super::*; #[test] fn hashmap() { let h: HashMap = HashMap::with_capacity(12); // - Capacity of 12 -> 16 buckets // - Overhead is 1 byte per bucket // - Fixed overhead of WIDTH let lower = 16 * (mem::size_of::<(u16, u32)>() + 1) + WIDTH; assert_eq!(h.dynamic_usage(), lower); assert_eq!(h.dynamic_usage_bounds(), (lower, None)); } #[test] fn hashset() { let h: HashSet = HashSet::with_capacity(17); // - Capacity of 17 -> 32 buckets // - Overhead is 1 byte per bucket // - Fixed overhead of WIDTH let lower = 32 * (mem::size_of::() + 1) + WIDTH; assert_eq!(h.dynamic_usage(), lower); assert_eq!(h.dynamic_usage_bounds(), (lower, None)); } } memuse-0.2.1/src/lib.rs000064400000000000000000000326000000000000000130000ustar 00000000000000//! Measure dynamic memory usage of your types! //! //! ## About //! //! Memory-tracking is a common activity in large applications, particularly ones //! that receive data from a network and store it in memory. By monitoring how much //! memory is used by different areas of the application, memory pressure can be //! alleviated by ignoring new packets, or implementing random drop logic for DoS //! mitigation. //! //! Measuring memory use on the stack is easy, with [`std::mem::size_of`] and //! friends. Measuring memory allocated on the heap is more tricky. Applications can //! use a custom global allocator to track the memory usage of different areas. This //! isn't an option for reusable library code however, and the nearest alternative //! (using custom allocators for individual types) is currently only an experimental //! feature in nightly Rust ([`allocator_api`]). //! //! [`allocator_api`]: https://github.com/rust-lang/rust/issues/32838 //! //! This crate takes a different approach: it provides traits that library authors //! can use to expose dynamic memory usage information on their types. By composing //! these implementations, we gain the ability to query the amount of heap-allocated //! memory in use by specific instances of types at any point in time, without any //! changes to the way in which these types are constructed. //! //! ## Minimum Supported Rust Version //! //! Requires Rust **1.51** or newer. //! //! In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this //! crate's SemVer guarantees), however when we do it will be accompanied by a minor //! version bump. //! //! ## Usage //! //! ``` //! # use std::collections::HashMap; //! use memuse::DynamicUsage; //! //! // Simple types don't allocate memory on the heap. //! assert_eq!(7u64.dynamic_usage(), 0); //! assert_eq!("I'm simple!".dynamic_usage(), 0); //! //! // When a type allocates memory, we can see it! //! assert_eq!(vec![7u64; 2].dynamic_usage(), 16); //! //! // We see the memory the type has allocated, even if it isn't being used. //! let empty: Vec = Vec::with_capacity(100); //! assert_eq!(empty.len(), 0); //! assert_eq!(empty.dynamic_usage(), 400); //! //! // For some types, we can't measure the exact memory usage, so we return a best //! // estimate. If you need precision, call `dynamic_usage_bounds` which returns a //! // lower bound, and (if known) an upper bound. //! let map: HashMap = HashMap::with_capacity(27); //! let (lower, upper): (usize, Option) = map.dynamic_usage_bounds(); //! assert!(upper.is_none()); //! ``` #![forbid(unsafe_code)] // Catch documentation errors caused by code changes. #![deny(broken_intra_doc_links)] use core::mem; use std::collections::{BinaryHeap, LinkedList, VecDeque}; /// Trait for measuring the dynamic memory usage of types. pub trait DynamicUsage { /// Returns a best estimate of the amount of heap-allocated memory used by this type. /// /// For most types, this will return an exact value. However, for types that use a /// complex allocation strategy (such as a `HashMap`), `memuse` cannot provide an /// exact heap allocation value, as it does not have access to the internal details /// and can only infer allocations from observable properties (such as the number of /// elements in a collection, or constants extracted from the implementation of the /// type). In those cases, this method returns a "best estimate" inferred from the /// implemented behaviour of the type. As more crates implement this trait themselves, /// the estimates will become more precise. /// /// The value returned by this method will always fall between the bounds returned by /// [`DynamicUsage::dynamic_usage_bounds`]: /// /// ``` /// use std::collections::HashMap; /// use memuse::DynamicUsage; /// /// let a: HashMap = HashMap::with_capacity(27); /// let usage = a.dynamic_usage(); /// let (lower, upper) = a.dynamic_usage_bounds(); /// /// assert!(lower <= usage); /// if let Some(upper) = upper { /// assert!(usage <= upper); /// } /// ``` fn dynamic_usage(&self) -> usize; /// Returns the lower and upper bounds on the amount of heap-allocated memory used by /// this type. /// /// The lower bound is always precise; a type cannot allocate fewer than zero bytes, /// and a collection cannot allocate fewer than the number of bytes required to store /// the entries it holds. /// /// The upper bound is only present if some property of the type ensures that its /// allocations do not exceed the bound, and is `None` otherwise (to indicate an /// unlimited upper bound). /// /// If the type's allocated memory is precisely known, then the lower and upper bounds /// will be equal. fn dynamic_usage_bounds(&self) -> (usize, Option); } // // Helper macros // /// Helper to implement [`DynamicUsage`] for simple types that don't allocate. /// /// # Examples /// /// ``` /// // Must be imported so it is accessible to the macro. /// use memuse::DynamicUsage; /// /// struct RegisterByte(u8); /// struct RegisterWord(u16); /// /// memuse::impl_no_dynamic_usage!(RegisterByte, RegisterWord); /// ``` /// /// The above is equivalent to: /// ``` /// use memuse::DynamicUsage; /// /// struct RegisterByte(u8); /// struct RegisterWord(u16); /// /// impl DynamicUsage for RegisterByte { /// #[inline(always)] /// fn dynamic_usage(&self) -> usize { /// 0 /// } /// /// #[inline(always)] /// fn dynamic_usage_bounds(&self) -> (usize, Option) { /// (0, Some(0)) /// } /// } /// /// impl DynamicUsage for RegisterWord { /// #[inline(always)] /// fn dynamic_usage(&self) -> usize { /// 0 /// } /// /// #[inline(always)] /// fn dynamic_usage_bounds(&self) -> (usize, Option) { /// (0, Some(0)) /// } /// } /// ``` #[macro_export] macro_rules! impl_no_dynamic_usage { ($($type:ty),+) => { $( impl DynamicUsage for $type { #[inline(always)] fn dynamic_usage(&self) -> usize { 0 } #[inline(always)] fn dynamic_usage_bounds(&self) -> (usize, Option) { (0, Some(0)) } } )+ }; } macro_rules! impl_iterable_dynamic_usage { ($type:ty, $base_usage:expr) => { impl DynamicUsage for $type { fn dynamic_usage(&self) -> usize { $base_usage(self) + self.iter().map(DynamicUsage::dynamic_usage).sum::() } fn dynamic_usage_bounds(&self) -> (usize, Option) { let base = $base_usage(self); let (lower, upper) = self.iter().map(DynamicUsage::dynamic_usage_bounds).fold( (0, Some(0)), |(acc_lower, acc_upper), (lower, upper)| { (acc_lower + lower, acc_upper.zip(upper).map(|(a, b)| a + b)) }, ); (base + lower, upper.map(|u| base + u)) } } }; } // // Primitives // impl_no_dynamic_usage!(()); impl_no_dynamic_usage!(i8, i16, i32, i64, i128, isize); impl_no_dynamic_usage!(u8, u16, u32, u64, u128, usize); impl_no_dynamic_usage!(f32, f64, bool); impl_no_dynamic_usage!(char, str); // Tuples are handled below (so they render more nicely in docs) impl DynamicUsage for [T; N] { fn dynamic_usage(&self) -> usize { self.iter().map(DynamicUsage::dynamic_usage).sum::() } fn dynamic_usage_bounds(&self) -> (usize, Option) { self.iter().map(DynamicUsage::dynamic_usage_bounds).fold( (0, Some(0)), |(acc_lower, acc_upper), (lower, upper)| { (acc_lower + lower, acc_upper.zip(upper).map(|(a, b)| a + b)) }, ) } } impl_iterable_dynamic_usage!([T], |_| 0); // // Structs // impl DynamicUsage for String { fn dynamic_usage(&self) -> usize { self.capacity() } fn dynamic_usage_bounds(&self) -> (usize, Option) { let usage = self.capacity(); (usage, Some(usage)) } } // // Containers // impl DynamicUsage for Box { fn dynamic_usage(&self) -> usize { mem::size_of::() + self.as_ref().dynamic_usage() } fn dynamic_usage_bounds(&self) -> (usize, Option) { let box_size = mem::size_of::(); let (inner_lower, inner_upper) = self.as_ref().dynamic_usage_bounds(); (box_size + inner_lower, inner_upper.map(|u| box_size + u)) } } impl DynamicUsage for Option { fn dynamic_usage(&self) -> usize { self.as_ref().map(DynamicUsage::dynamic_usage).unwrap_or(0) } fn dynamic_usage_bounds(&self) -> (usize, Option) { self.as_ref() .map(DynamicUsage::dynamic_usage_bounds) .unwrap_or((0, Some(0))) } } impl DynamicUsage for Result { fn dynamic_usage(&self) -> usize { match self { Ok(t) => t.dynamic_usage(), Err(e) => e.dynamic_usage(), } } fn dynamic_usage_bounds(&self) -> (usize, Option) { match self { Ok(t) => t.dynamic_usage_bounds(), Err(e) => e.dynamic_usage_bounds(), } } } // // Collections // impl_iterable_dynamic_usage!(Vec, |c: &Vec| c.capacity() * mem::size_of::()); impl_iterable_dynamic_usage!(BinaryHeap, |c: &BinaryHeap| { // BinaryHeap is a wrapper around Vec c.capacity() * mem::size_of::() }); impl_iterable_dynamic_usage!(LinkedList, |c: &LinkedList| { c.len() * mem::size_of::() }); impl_iterable_dynamic_usage!(VecDeque, |c: &VecDeque| { // +1 since the ringbuffer always leaves one space empty. (c.capacity() + 1) * mem::size_of::() }); mod hash; // // External crate types (provided for helpfulness, since `DynamicUsage` can only be // implemented either here or in the external crate). // #[cfg(feature = "nonempty")] impl_iterable_dynamic_usage!(nonempty::NonEmpty, |c: &nonempty::NonEmpty| { // NonEmpty stores its head element separately from its tail Vec. (c.capacity() - 1) * mem::size_of::() }); // // Larger definitions (placed at the end so they render more nicely in docs). // mod tuple; #[cfg(test)] mod tests { use super::*; #[test] fn standard_types() { assert_eq!(129u8.dynamic_usage(), 0); assert_eq!(3i128.dynamic_usage(), 0); assert_eq!(7.0f32.dynamic_usage(), 0); assert_eq!("foobar".dynamic_usage(), 0); assert_eq!(129u8.dynamic_usage_bounds(), (0, Some(0))); assert_eq!(3i128.dynamic_usage_bounds(), (0, Some(0))); assert_eq!(7.0f32.dynamic_usage_bounds(), (0, Some(0))); assert_eq!("foobar".dynamic_usage_bounds(), (0, Some(0))); } #[test] fn string() { assert_eq!(String::new().dynamic_usage(), 0); assert_eq!("foobar".to_string().dynamic_usage(), 6); assert_eq!(String::new().dynamic_usage_bounds(), (0, Some(0))); assert_eq!("foobar".to_string().dynamic_usage_bounds(), (6, Some(6))); } #[test] fn boxed() { let a: u64 = 7; assert_eq!(a.dynamic_usage(), 0); assert_eq!(a.dynamic_usage_bounds(), (0, Some(0))); let b: Box = Box::new(42); assert_eq!(b.dynamic_usage(), 8); assert_eq!(b.dynamic_usage_bounds(), (8, Some(8))); let capacity = 7; let c: Box> = Box::new(Vec::with_capacity(capacity)); let expected = mem::size_of::>() + capacity * mem::size_of::(); assert_eq!(c.dynamic_usage(), expected); assert_eq!(c.dynamic_usage_bounds(), (expected, Some(expected))); } #[test] fn option() { let a: Option> = None; let b: Option> = Some(vec![7u8; 4]); assert_eq!(a.dynamic_usage(), 0); assert_eq!(a.dynamic_usage_bounds(), (0, Some(0))); assert_eq!(b.dynamic_usage(), 4); assert_eq!(b.dynamic_usage_bounds(), (4, Some(4))); } #[test] fn array() { let a = [7; 42]; assert_eq!(a.dynamic_usage(), 0); assert_eq!(a.dynamic_usage_bounds(), (0, Some(0))); let mut b = [None, None, None, None]; assert_eq!(b.dynamic_usage(), 0); assert_eq!(b.dynamic_usage_bounds(), (0, Some(0))); b[0] = Some(vec![4u8; 20]); assert_eq!(b.dynamic_usage(), 20); assert_eq!(b.dynamic_usage_bounds(), (20, Some(20))); } #[test] fn vec() { let capacity = 7; let mut a = Vec::with_capacity(capacity); a.push(42u64); let expected = capacity * mem::size_of::(); assert_eq!(a.dynamic_usage(), expected); assert_eq!(a.dynamic_usage_bounds(), (expected, Some(expected))); } #[cfg(feature = "nonempty")] #[test] fn nonempty() { let a = nonempty::NonEmpty::new(42); assert_eq!(a.dynamic_usage(), 0); assert_eq!(a.dynamic_usage_bounds(), (0, Some(0))); const CAPACITY: usize = 7; let b = nonempty::NonEmpty::from_slice(&[27u128; CAPACITY]).unwrap(); let expected = (CAPACITY - 1) * mem::size_of::(); assert_eq!(b.dynamic_usage(), expected); assert_eq!(b.dynamic_usage_bounds(), (expected, Some(expected))); } } memuse-0.2.1/src/tuple.rs000064400000000000000000000064160000000000000133710ustar 00000000000000use std::array; use crate::DynamicUsage; macro_rules! tuple_impls { ($( $Tuple:ident { $(($idx:tt) -> $T:ident)+ } )+) => { $( impl<$($T),+> DynamicUsage for ($($T,)+) where $($T: DynamicUsage),+ { fn dynamic_usage(&self) -> usize { array::IntoIter::new([$(self.$idx.dynamic_usage()),+]).sum::() } fn dynamic_usage_bounds(&self) -> (usize, Option) { array::IntoIter::new([$(self.$idx.dynamic_usage_bounds()),+]) .fold( (0, Some(0)), |(acc_lower, acc_upper), (lower, upper)| { (acc_lower + lower, acc_upper.zip(upper).map(|(a, b)| a + b)) }, ) } } )+ }; () => {}; } tuple_impls! { Tuple1 { (0) -> A } Tuple2 { (0) -> A (1) -> B } Tuple3 { (0) -> A (1) -> B (2) -> C } Tuple4 { (0) -> A (1) -> B (2) -> C (3) -> D } Tuple5 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E } Tuple6 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F } Tuple7 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G } Tuple8 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H } Tuple9 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I } Tuple10 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I (9) -> J } Tuple11 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I (9) -> J (10) -> K } Tuple12 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I (9) -> J (10) -> K (11) -> L } } #[cfg(test)] mod tests { use std::collections::HashSet; use super::*; use crate::hash::WIDTH as HASH_WIDTH; #[test] fn tuples() { let a = (0u8, 0u16, 0u32); assert_eq!(a.dynamic_usage(), 0); assert_eq!(a.dynamic_usage_bounds(), (0, Some(0))); let b = (Vec::::with_capacity(10), Vec::::with_capacity(2)); assert_eq!(b.dynamic_usage(), 26); assert_eq!(b.dynamic_usage_bounds(), (26, Some(26))); let c = ( HashSet::::with_capacity(10), Vec::::with_capacity(2), ); // HashSet has capacity 10 -> 16 buckets let lower_bound = 32 + HASH_WIDTH + 16; assert_eq!(c.dynamic_usage(), lower_bound); assert_eq!(c.dynamic_usage_bounds(), (lower_bound, None)); } }