How do I determine the current stack frame depth?
fn print_depths() {
println!("stack frame depth {}", stack_frame_depth());
fn print_depth2() {
println!("stack frame depth {}", stack_frame_depth());
}
print_depth2();
}
pub fn main() {
print_depths();
}
would print
stack frame depth 1
stack frame depth 2
I know main has callers so the particular numbers might be different.
I have tried stacker::remaining_stack. However, that prints a count of bytes remaining in the stack. Since the arguments passed to a function affect the stack byte "height" then it is not possible to derive a simple function call "height". I want a count of the current function call height.
If, having noted all the caveats in Peter Hall's answer, it is still desirable to obtain the actual stack depth, consider backtrace::Backtrace:
#[inline]
fn stack_frame_depth() -> usize {
Backtrace::new_unresolved().frames().len()
}
See it on the playground.
If you want to avoid the allocation involved in instantiating a Backtrace, consider backtrace::trace instead:
#[inline]
fn stack_frame_depth() -> usize {
let mut depth = 0;
backtrace::trace(|_| {
depth += 1;
true
});
depth
}
Both of the above approaches require std for thread-safety, however. If your crate is no_std and/or you are ensuring synchronization some other way, there's backtrace::trace_unsynchronized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With