diff --git a/Cargo.toml b/Cargo.toml index 720512a6..bbd60b84 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,3 +73,8 @@ default-features = false optional = true version = "1" default-features = false + +[dev-dependencies] + +[dev-dependencies.dhat] +version = "0.3.3" diff --git a/src/bigint.rs b/src/bigint.rs index b4f84b9e..38ee9887 100644 --- a/src/bigint.rs +++ b/src/bigint.rs @@ -1153,6 +1153,15 @@ impl BigInt { // The top bit may have been cleared, so normalize self.normalize(); } + + /// Returns the total amount of memory allocated internally by the + /// big int, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + pub fn allocation_size(&self) -> usize { + self.data.allocation_size() + } } impl num_traits::FromBytes for BigInt { diff --git a/src/biguint.rs b/src/biguint.rs index 196fa323..b4e6a03b 100644 --- a/src/biguint.rs +++ b/src/biguint.rs @@ -1042,6 +1042,15 @@ impl BigUint { self.normalize(); } } + + /// Returns the total amount of memory allocated internally by the + /// big uint, in bytes. + /// + /// The returned number is informational only. It is intended to be + /// primarily used for memory profiling. + pub fn allocation_size(&self) -> usize { + self.data.capacity() * std::mem::size_of::() + } } impl num_traits::FromBytes for BigUint { diff --git a/tests/bigint_allocation_size.rs b/tests/bigint_allocation_size.rs new file mode 100644 index 00000000..af9df665 --- /dev/null +++ b/tests/bigint_allocation_size.rs @@ -0,0 +1,12 @@ +use num_bigint::BigInt; + +#[global_allocator] +static ALLOC: dhat::Alloc = dhat::Alloc; + +#[test] +fn test_biguint_allocation_size() { + let _profiler = dhat::Profiler::builder().testing().build(); + let big: BigInt = "-1234567898765432123456789876543212345678987654321".parse().unwrap(); + let stats = dhat::HeapStats::get(); + assert_eq!(stats.curr_bytes, big.allocation_size()); +} diff --git a/tests/biguint_allocation_size.rs b/tests/biguint_allocation_size.rs new file mode 100644 index 00000000..fb33b703 --- /dev/null +++ b/tests/biguint_allocation_size.rs @@ -0,0 +1,12 @@ +use num_bigint::BigUint; + +#[global_allocator] +static ALLOC: dhat::Alloc = dhat::Alloc; + +#[test] +fn test_biguint_allocation_size() { + let _profiler = dhat::Profiler::builder().testing().build(); + let big: BigUint = "1234567898765432123456789876543212345678987654321".parse().unwrap(); + let stats = dhat::HeapStats::get(); + assert_eq!(stats.curr_bytes, big.allocation_size()); +}