heapsize-0.4.2/.gitignore010064400007650000024000000000301312631330400135210ustar0000000000000000target Cargo.lock *.swp heapsize-0.4.2/.travis.yml010064400007650000024000000005611323344217600136640ustar0000000000000000language: rust rust: - 1.11.0 - nightly - beta - stable os: - linux - osx notifications: webhooks: http://build.servo.org:54856/travis script: - cargo test - "[ $TRAVIS_RUST_VERSION != nightly ] || cargo test --features unstable" - "[[ $TRAVIS_RUST_VERSION != nightly && $TRAVIS_RUST_VERSION != beta ]] || cargo test --manifest-path derive/Cargo.toml" heapsize-0.4.2/appveyor.yml010064400007650000024000000011041312631330400141240ustar0000000000000000environment: matrix: - FEATURES: "" - FEATURES: "unstable" platform: - i686-pc-windows-gnu - i686-pc-windows-msvc - x86_64-pc-windows-gnu - x86_64-pc-windows-msvc install: - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:PLATFORM}.exe" - rust-nightly-%PLATFORM%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - rustc -V - cargo -V build_script: - cargo build --verbose --features "%FEATURES%" test_script: - cargo test --verbose --features "%FEATURES%" heapsize-0.4.2/build.rs010064400007650000024000000024641312631330400132130ustar0000000000000000use std::env::var; use std::process::Command; use std::str; fn main() { let verbose = Command::new(var("RUSTC").unwrap_or("rustc".into())) .arg("--version") .arg("--verbose") .output() .unwrap() .stdout; let verbose = str::from_utf8(&verbose).unwrap(); let mut commit_date = None; let mut release = None; for line in verbose.lines() { let mut parts = line.split(':'); match parts.next().unwrap().trim() { "commit-date" => commit_date = Some(parts.next().unwrap().trim()), "release" => release = Some(parts.next().unwrap().trim()), _ => {} } } let version = release.unwrap().split('-').next().unwrap();; let mut version_components = version.split('.').map(|s| s.parse::().unwrap()); let version = ( version_components.next().unwrap(), version_components.next().unwrap(), version_components.next().unwrap(), // "unknown" sorts after "2016-02-14", which is what we want to defaut to unprefixed // https://github.com/servo/heapsize/pull/44#issuecomment-187935883 commit_date.unwrap() ); assert_eq!(version_components.next(), None); if version < (1, 8, 0, "2016-02-14") { println!("cargo:rustc-cfg=prefixed_jemalloc"); } } heapsize-0.4.2/Cargo.toml.orig010064400007650000024000000007301323344217600144400ustar0000000000000000[package] name = "heapsize" version = "0.4.2" authors = [ "The Servo Project Developers" ] description = "Infrastructure for measuring the total runtime size of an object on the heap" license = "MIT/Apache-2.0" repository = "https://github.com/servo/heapsize" build = "build.rs" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3.4", features = ["std", "heapapi"] } [features] unstable = [] # https://github.com/servo/heapsize/issues/74 flexible-tests = [] heapsize-0.4.2/Cargo.toml0000644000000016530000000000000107110ustar00# 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] name = "heapsize" version = "0.4.2" authors = ["The Servo Project Developers"] build = "build.rs" description = "Infrastructure for measuring the total runtime size of an object on the heap" license = "MIT/Apache-2.0" repository = "https://github.com/servo/heapsize" [features] flexible-tests = [] unstable = [] [target."cfg(windows)".dependencies.winapi] version = "0.3.4" features = ["std", "heapapi"] heapsize-0.4.2/LICENSE-APACHE010064400007650000024000000261361312631330400134740ustar0000000000000000 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. heapsize-0.4.2/LICENSE-MIT010064400007650000024000000020501312631330400131710ustar0000000000000000Copyright (c) 2015 The Servo Developers 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. heapsize-0.4.2/README.md010064400007650000024000000011601323344217600130260ustar0000000000000000# heapsize In support of measuring heap allocations in Rust programs. [API Documentation](https://docs.rs/heapsize/) ## 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. heapsize-0.4.2/src/lib.rs010064400007650000024000000266401323344217600134640ustar0000000000000000//! Data structure measurement. #[cfg(target_os = "windows")] extern crate winapi; #[cfg(target_os = "windows")] use winapi::um::heapapi::{GetProcessHeap, HeapSize, HeapValidate}; use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, HashSet, HashMap, LinkedList, VecDeque}; use std::hash::BuildHasher; use std::hash::Hash; use std::marker::PhantomData; use std::mem::{size_of, align_of}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::ops::{Range, RangeFrom, RangeFull, RangeTo}; use std::os::raw::c_void; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize}; use std::rc::Rc; /// Get the size of a heap block. /// /// Ideally Rust would expose a function like this in std::rt::heap. /// /// `unsafe` because the caller must ensure that the pointer is from jemalloc. /// FIXME: This probably interacts badly with custom allocators: /// https://doc.rust-lang.org/book/custom-allocators.html pub unsafe fn heap_size_of(ptr: *const T) -> usize { if ptr as usize <= align_of::() { 0 } else { heap_size_of_impl(ptr as *const c_void) } } #[cfg(not(target_os = "windows"))] unsafe fn heap_size_of_impl(ptr: *const c_void) -> usize { // The C prototype is `je_malloc_usable_size(JEMALLOC_USABLE_SIZE_CONST void *ptr)`. On some // platforms `JEMALLOC_USABLE_SIZE_CONST` is `const` and on some it is empty. But in practice // this function doesn't modify the contents of the block that `ptr` points to, so we use // `*const c_void` here. extern "C" { #[cfg_attr(any(prefixed_jemalloc, target_os = "macos", target_os = "ios", target_os = "android"), link_name = "je_malloc_usable_size")] fn malloc_usable_size(ptr: *const c_void) -> usize; } malloc_usable_size(ptr) } #[cfg(target_os = "windows")] unsafe fn heap_size_of_impl(mut ptr: *const c_void) -> usize { let heap = GetProcessHeap(); if HeapValidate(heap, 0, ptr) == 0 { ptr = *(ptr as *const *const c_void).offset(-1); } HeapSize(heap, 0, ptr) as usize } // The simplest trait for measuring the size of heap data structures. More complex traits that // return multiple measurements -- e.g. measure text separately from images -- are also possible, // and should be used when appropriate. // pub trait HeapSizeOf { /// Measure the size of any heap-allocated structures that hang off this value, but not the /// space taken up by the value itself (i.e. what size_of:: measures, more or less); that /// space is handled by the implementation of HeapSizeOf for Box below. fn heap_size_of_children(&self) -> usize; } // There are two possible ways to measure the size of `self` when it's on the heap: compute it // (with `::std::rt::heap::usable_size(::std::mem::size_of::(), 0)`) or measure it directly // using the heap allocator (with `heap_size_of`). We do the latter, for the following reasons. // // * The heap allocator is the true authority for the sizes of heap blocks; its measurement is // guaranteed to be correct. In comparison, size computations are error-prone. (For example, the // `rt::heap::usable_size` function used in some of Rust's non-default allocator implementations // underestimate the true usable size of heap blocks, which is safe in general but would cause // under-measurement here.) // // * If we measure something that isn't a heap block, we'll get a crash. This keeps us honest, // which is important because unsafe code is involved and this can be gotten wrong. // // However, in the best case, the two approaches should give the same results. // impl HeapSizeOf for Box { fn heap_size_of_children(&self) -> usize { // Measure size of `self`. unsafe { heap_size_of(&**self as *const T as *const c_void) + (**self).heap_size_of_children() } } } impl HeapSizeOf for [T] { fn heap_size_of_children(&self) -> usize { self.iter().fold(0, |size, item| size + item.heap_size_of_children()) } } impl HeapSizeOf for String { fn heap_size_of_children(&self) -> usize { unsafe { heap_size_of(self.as_ptr()) } } } impl<'a, T: ?Sized> HeapSizeOf for &'a T { fn heap_size_of_children(&self) -> usize { 0 } } // The implementations for *mut T and *const T are designed for use cases like LinkedHashMap where // you have a data structure which internally maintains an e.g. HashMap parameterized with raw // pointers. We want to be able to rely on the standard HeapSizeOf implementation for `HashMap`, // and can handle the contribution of the raw pointers manually. // // These have to return 0 since we don't know if the pointer is pointing to a heap allocation or // even valid memory. impl HeapSizeOf for *mut T { fn heap_size_of_children(&self) -> usize { 0 } } impl HeapSizeOf for *const T { fn heap_size_of_children(&self) -> usize { 0 } } impl HeapSizeOf for Option { fn heap_size_of_children(&self) -> usize { match *self { None => 0, Some(ref x) => x.heap_size_of_children() } } } impl HeapSizeOf for Result { fn heap_size_of_children(&self) -> usize { match *self { Ok(ref x) => x.heap_size_of_children(), Err(ref e) => e.heap_size_of_children(), } } } impl<'a, B: ?Sized + ToOwned> HeapSizeOf for Cow<'a, B> where B::Owned: HeapSizeOf { fn heap_size_of_children(&self) -> usize { match *self { Cow::Borrowed(_) => 0, Cow::Owned(ref b) => b.heap_size_of_children(), } } } impl HeapSizeOf for () { fn heap_size_of_children(&self) -> usize { 0 } } impl HeapSizeOf for (T1, T2) where T1: HeapSizeOf, T2 :HeapSizeOf { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() + self.1.heap_size_of_children() } } impl HeapSizeOf for (T1, T2, T3) where T1: HeapSizeOf, T2 :HeapSizeOf, T3: HeapSizeOf { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() + self.1.heap_size_of_children() + self.2.heap_size_of_children() } } impl HeapSizeOf for (T1, T2, T3, T4) where T1: HeapSizeOf, T2 :HeapSizeOf, T3: HeapSizeOf, T4: HeapSizeOf { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() + self.1.heap_size_of_children() + self.2.heap_size_of_children() + self.3.heap_size_of_children() } } impl HeapSizeOf for (T1, T2, T3, T4, T5) where T1: HeapSizeOf, T2 :HeapSizeOf, T3: HeapSizeOf, T4: HeapSizeOf, T5: HeapSizeOf { fn heap_size_of_children(&self) -> usize { self.0.heap_size_of_children() + self.1.heap_size_of_children() + self.2.heap_size_of_children() + self.3.heap_size_of_children() + self.4.heap_size_of_children() } } impl HeapSizeOf for Arc { fn heap_size_of_children(&self) -> usize { (**self).heap_size_of_children() } } impl HeapSizeOf for RefCell { fn heap_size_of_children(&self) -> usize { self.borrow().heap_size_of_children() } } impl HeapSizeOf for Cell { fn heap_size_of_children(&self) -> usize { self.get().heap_size_of_children() } } impl HeapSizeOf for Vec { fn heap_size_of_children(&self) -> usize { self.iter().fold( unsafe { heap_size_of(self.as_ptr()) }, |n, elem| n + elem.heap_size_of_children()) } } impl HeapSizeOf for VecDeque { fn heap_size_of_children(&self) -> usize { self.iter().fold( // FIXME: get the buffer pointer for heap_size_of(), capacity() is a lower bound: self.capacity() * size_of::(), |n, elem| n + elem.heap_size_of_children()) } } impl HeapSizeOf for Vec> { fn heap_size_of_children(&self) -> usize { // The fate of measuring Rc is still undecided, but we still want to measure // the space used for storing them. unsafe { heap_size_of(self.as_ptr()) } } } impl HeapSizeOf for HashSet where T: Eq + Hash, S: BuildHasher { fn heap_size_of_children(&self) -> usize { //TODO(#6908) measure actual bucket memory usage instead of approximating let size = self.capacity() * (size_of::() + size_of::()); self.iter().fold(size, |n, value| { n + value.heap_size_of_children() }) } } impl HeapSizeOf for HashMap where K: Eq + Hash, S: BuildHasher { fn heap_size_of_children(&self) -> usize { //TODO(#6908) measure actual bucket memory usage instead of approximating let size = self.capacity() * (size_of::() + size_of::() + size_of::()); self.iter().fold(size, |n, (key, value)| { n + key.heap_size_of_children() + value.heap_size_of_children() }) } } // PhantomData is always 0. impl HeapSizeOf for PhantomData { fn heap_size_of_children(&self) -> usize { 0 } } // A linked list has an overhead of two words per item. impl HeapSizeOf for LinkedList { fn heap_size_of_children(&self) -> usize { let mut size = 0; for item in self { size += 2 * size_of::() + size_of::() + item.heap_size_of_children(); } size } } // FIXME: Overhead for the BTreeMap nodes is not accounted for. impl HeapSizeOf for BTreeMap { fn heap_size_of_children(&self) -> usize { let mut size = 0; for (key, value) in self.iter() { size += size_of::<(K, V)>() + key.heap_size_of_children() + value.heap_size_of_children(); } size } } impl HeapSizeOf for Range where T: HeapSizeOf, { fn heap_size_of_children(&self) -> usize { self.start.heap_size_of_children() + self.end.heap_size_of_children() } } impl HeapSizeOf for RangeFrom where T: HeapSizeOf, { fn heap_size_of_children(&self) -> usize { self.start.heap_size_of_children() } } impl HeapSizeOf for RangeTo where T: HeapSizeOf, { fn heap_size_of_children(&self) -> usize { self.end.heap_size_of_children() } } /// For use on types defined in external crates /// with known heap sizes. #[macro_export] macro_rules! known_heap_size( ($size:expr, $($ty:ty),+) => ( $( impl $crate::HeapSizeOf for $ty { #[inline(always)] fn heap_size_of_children(&self) -> usize { $size } } )+ ); ($size: expr, $($ty:ident<$($gen:ident),+>),+) => ( $( impl<$($gen: $crate::HeapSizeOf),+> $crate::HeapSizeOf for $ty<$($gen),+> { #[inline(always)] fn heap_size_of_children(&self) -> usize { $size } } )+ ); ); known_heap_size!(0, char, str); known_heap_size!(0, u8, u16, u32, u64, usize); known_heap_size!(0, i8, i16, i32, i64, isize); known_heap_size!(0, bool, f32, f64); known_heap_size!(0, AtomicBool, AtomicIsize, AtomicUsize); known_heap_size!(0, Ipv4Addr, Ipv6Addr, RangeFull); heapsize-0.4.2/tests/tests.rs010064400007650000024000000134761323344217600144360ustar0000000000000000#![cfg_attr(feature= "unstable", feature(allocator_api, repr_simd))] extern crate heapsize; use heapsize::{HeapSizeOf, heap_size_of}; /// https://github.com/servo/heapsize/issues/74 #[cfg(feature = "flexible-tests")] macro_rules! assert_size { ($actual: expr, $expected: expr) => { { let actual = $actual; let expected = $expected; assert!(actual >= expected, "expected {:?} >= {:?}", actual, expected) } } } #[cfg(not(feature = "flexible-tests"))] macro_rules! assert_size { ($actual: expr, $expected: expr) => { assert_eq!($actual, $expected) } } #[cfg(feature = "unstable")] mod unstable { use heapsize::heap_size_of; use std::os::raw::c_void; use std::heap::{Heap, Alloc, Layout}; unsafe fn allocate(size: usize, align: usize) -> *mut u8 { Heap.alloc(Layout::from_size_align(size, align).unwrap()).unwrap() } unsafe fn deallocate(ptr: *mut u8, size: usize, align: usize) { Heap.dealloc(ptr, Layout::from_size_align(size, align).unwrap()) } #[repr(simd)] struct OverAligned(u64, u64, u64, u64); #[cfg(not(target_os = "windows"))] #[test] fn test_alloc() { unsafe { // A 64 byte request is allocated exactly. let x = allocate(64, 1); assert_size!(heap_size_of(x as *const c_void), 64); deallocate(x, 64, 1); // A 255 byte request is rounded up to 256 bytes. let x = allocate(255, 1); assert_size!(heap_size_of(x as *const c_void), 256); deallocate(x, 255, 1); // A 1MiB request is allocated exactly. let x = allocate(1024 * 1024, 1); assert_size!(heap_size_of(x as *const c_void), 1024 * 1024); deallocate(x, 1024 * 1024, 1); // An overaligned 1MiB request is allocated exactly. let x = allocate(1024 * 1024, 32); assert_size!(heap_size_of(x as *const c_void), 1024 * 1024); deallocate(x, 1024 * 1024, 32); } } #[cfg(target_os = "windows")] #[test] fn test_alloc() { unsafe { // A 64 byte request is allocated exactly. let x = allocate(64, 1); assert_size!(heap_size_of(x as *const c_void), 64); deallocate(x, 64, 1); // A 255 byte request is allocated exactly. let x = allocate(255, 1); assert_size!(heap_size_of(x as *const c_void), 255); deallocate(x, 255, 1); // A 1MiB request is allocated exactly. let x = allocate(1024 * 1024, 1); assert_size!(heap_size_of(x as *const c_void), 1024 * 1024); deallocate(x, 1024 * 1024, 1); // An overaligned 1MiB request is over-allocated. let x = allocate(1024 * 1024, 32); assert_size!(heap_size_of(x as *const c_void), 1024 * 1024 + 32); deallocate(x, 1024 * 1024, 32); } } #[cfg(not(target_os = "windows"))] #[test] fn test_simd() { let x = Box::new(OverAligned(0, 0, 0, 0)); assert_size!(unsafe { heap_size_of(&*x as *const _ as *const c_void) }, 32); } #[cfg(target_os = "windows")] #[test] fn test_simd() { let x = Box::new(OverAligned(0, 0, 0, 0)); assert_size!(unsafe { heap_size_of(&*x as *const _ as *const c_void) }, 32 + 32); } } #[test] fn test_boxed_str() { let x = "raclette".to_owned().into_boxed_str(); assert_size!(x.heap_size_of_children(), 8); } #[test] fn test_heap_size() { // Note: jemalloc often rounds up request sizes. However, it does not round up for request // sizes of 8 and higher that are powers of two. We take advantage of knowledge here to make // the sizes of various heap-allocated blocks predictable. //----------------------------------------------------------------------- // Start with basic heap block measurement. unsafe { // EMPTY is the special non-null address used to represent zero-size allocations. assert_size!(heap_size_of::<[u64; 0]>(&*Box::new([42_u64; 0])), 0); assert_size!(heap_size_of::<[u8; 0]>(&*Box::new([42_u8; 0])), 0); } //----------------------------------------------------------------------- // Test HeapSizeOf implementations for various built-in types. // Not on the heap; 0 bytes. let x = 0i64; assert_size!(x.heap_size_of_children(), 0); // An i64 is 8 bytes. let x = Box::new(0i64); assert_size!(x.heap_size_of_children(), 8); // An ascii string with 16 chars is 16 bytes in UTF-8. let string = String::from("0123456789abcdef"); assert_size!(string.heap_size_of_children(), 16); let string_ref: (&String, ()) = (&string, ()); assert_size!(string_ref.heap_size_of_children(), 0); let slice: &str = &*string; assert_size!(slice.heap_size_of_children(), 0); // Not on the heap. let x: Option = None; assert_size!(x.heap_size_of_children(), 0); // Not on the heap. let x = Some(0i64); assert_size!(x.heap_size_of_children(), 0); // The `Some` is not on the heap, but the Box is. let x = Some(Box::new(0i64)); assert_size!(x.heap_size_of_children(), 8); // Not on the heap. let x = ::std::sync::Arc::new(0i64); assert_size!(x.heap_size_of_children(), 0); // The `Arc` is not on the heap, but the Box is. let x = ::std::sync::Arc::new(Box::new(0i64)); assert_size!(x.heap_size_of_children(), 8); // Zero elements, no heap storage. let x: Vec = vec![]; assert_size!(x.heap_size_of_children(), 0); // Four elements, 8 bytes per element. let x = vec![0i64, 1i64, 2i64, 3i64]; assert_size!(x.heap_size_of_children(), 32); } #[test] fn test_boxed_slice() { let x = vec![1i64, 2i64].into_boxed_slice(); assert_size!(x.heap_size_of_children(), 16) }