Rust macro to make recursive function run on the heap (i.e. no stack overflow).

Related tags

Utilities decurse
Overview

Decurse

crates.io crates.io

Example

#[decurse::decurse] // πŸ‘ˆ Slap this on your recursive function and stop worrying about stack overflow!
fn factorial(x: u32) -> u32 {
	if x == 0 {
		1
	} else {
		x * factorial(x - 1)
	}
}

println!("{}", factorial(10));

More examples (fibonacci, DFS, ...) are in the examples directory.

Functionality

The macros provided by this crate make your recursive functions run on the heap instead. Works on stable Rust (1.56 at the time of writing).

Here's an example to illustrate the mechanism.

fn factorial(x: u32) -> u32 {
	// πŸ…
	if x == 0 {
		1
	} else {
		
		let rec = {
			// πŸ…‘
			factorial(x - 1)
		};

		// πŸ…’
		rec * x
	}
}

If we call factorial(1), the following would happen:

  • We run the code in the function starting at point πŸ….
  • When we reach point πŸ…‘, we don't immediately call factorial(0), instead, we save the information that we have to call factorial(0)1.
  • Once that information is saved, we pause the execution of factorial(1), storing the state on the heap2.
  • We then execute factorial(0). During this, the "stack state" of factorial(1) is not on the stack. It is stored on the heap.
  • Once we got the result of factorial(0), we resume factorial(1) giving it the result of factorial(0)3.
  • The execution continues at point πŸ…’ and on.

1 To send this information out of the function, we put it in a thread local.

2 This is accomplished by converting your function into an async function, and awaiting to pause it. It is somewhat of a hack using async/await.

3 This again use thread local.


Click to show an example of what the macro expands to
fn factorial(arg_0: u32) -> u32 {
	async fn factorial(x: u32) -> u32 {
		if x == 0 {
			1
		} else {
			x * ({
				// Save what we have to do next.
				::decurse::for_macro_only::sound::set_next(factorial(x - 1));
				// Pause the current function.
				::decurse::for_macro_only::sound::PendOnce::new().await;
				// Once resumed, get the result.
				::decurse::for_macro_only::sound::get_result(factorial)
			})
		}
	}
	::decurse::for_macro_only::sound::execute(factorial(arg_0))
}

Usage

This crate provides two macros: decurse and decurse_unsound. Simply put them on top of your function.

#[decurse::decurse]
fn some_function(...) -> ...
#[decurse::decurse_unsound]
fn some_function(...) -> ...

decurse

This is the version you should prefer. This does not use unsafe code and is thus safe.

However, it does not work on functions with lifetimed types (&T, SomeStruct<'a>, etc.) in the argument.

decurse_unsound

This macro can cause unsoundness (see example). My (unproven) believe is that if a function compiles without #[decurse_unsound], then putting #[decurse_unsound] on it should be safe.

This version does not suffer from the limitation of the safe version. Arguments can be lifetimed just as in any functions.

Limitations

  • As mentioned, the safe variant only works on functions without lifetimed type arguments.

    • The owning_ref crate is great for working around this.
    • You can use the "unsound" variant, of course. But it might cause problems.
  • This is not tail-call optimization. Also you can still blow up your heap (although it is much harder).

  • One function only. Alternating recursion (f calls g then g calls f) is not supported. Calling the same function but with different generic parameters is not supported.

  • Async function are not supported.

  • Struct methods are not supported. Freestanding function only.

  • The macro only understand recursive calls that are written literally.

     // This would work:
     recursive(x - 1);
    
     // The macro wouldn't understand this:
     let f = recursive;
     f(x - 1);
  • The function must have no more than 12 arguments.

    • This is actually a limitation of the pfn crate.
  • impl Trait in argument position is not supported.

    • You can use normal, named, generics.
  • This is still very experimental. The safe variant doesn't contain unsafe code but even then you should still be careful.

  • Multithreading is not supported.

Benchmarks

Benchmarking recursive linear search. See the code.

Vec Size Time (decurse) (s) Time (normal) (s) decurse/normal
20000 0.65 0.19 3.45
40000 1.29 0.43 2.96
60000 2.11 0.78 2.69
80000 2.81 1.24 2.27
100000 3.49 Stack Overflow N/A
120000 4.32 Stack Overflow N/A
140000 5.23 Stack Overflow N/A
160000 5.99 Stack Overflow N/A
180000 6.72 Stack Overflow N/A

decurse version runs at about 35% the performance of the normal version.


Same benchmark with the slow(8723) call uncommented for both linear_search and stack_linear_search. slow() is an artificial computation to mimick real use cases where the recursive function actually does something.

Vec Size Time (decurse) (s) Time (normal) (s) decurse/normal
20000 2.87 2.56 1.12
40000 5.74 5.18 1.11
60000 8.64 7.80 1.11
80000 11.57 10.49 1.10
100000 14.59 Stack Overflow N/A
120000 17.60 Stack Overflow N/A
140000 20.59 Stack Overflow N/A
160000 23.60 Stack Overflow N/A
180000 26.61 Stack Overflow N/A

decurse version runs at about 90% the performance of the normal version.


Anyway, you should do your own benchmarks for your own use cases. The recursive linear search implemented here isn't even something anyone would use!

I would still love to see what the numbers look like for your use cases. Please share!

Credits

This blog post by hurryabit inspired me to make this. The main idea is basically the same. Mine is more hacky because I want to avoid generators (which require nightly and won't be stabilized anytime soon), so I use async/await instead.

You might also like...
A Bancho implementation made in Rust for the *cursed* stack.

cu.rs A Bancho implementation made in Rust for the cursed stack. THIS PROJECT IS REALLY UNFINISHED AND IN ITS EARLY STAGES A drag and drop replacement

A stack for rust trait objects that minimizes allocations

dynstack A stack for trait objects that minimizes allocations COMPATIBILITY NOTE: dynstack relies on an underspecified fat pointer representation. Tho

Awesome full-stack template using Yew and Rust
Awesome full-stack template using Yew and Rust

Docker + Actix + Yew Full Stack Template πŸ‘¨β€πŸ’» YouTube videos Full Stack Rust App Template using Yew + Actix! https://youtu.be/oCiGjrpGk4A Add Docker

A stack-allocated box that stores trait objects.

This crate allows saving DST objects in the provided buffer. It allows users to create global dynamic objects on a no_std environment without a global allocator.

A memory efficient immutable string type that can store up to 24* bytes on the stack

compact_str A memory efficient immutable string type that can store up to 24* bytes on the stack. * 12 bytes for 32-bit architectures About A CompactS

Make ELF formatted apps configurable
Make ELF formatted apps configurable

elfredo `elfredo` is a library that allows you to patch executables after they were compiled. It utilize an extra embedded section to store data/confi

cargo, make me a project
cargo, make me a project

cargo-generate cargo, make me a project cargo-generate is a developer tool to help you get up and running quickly with a new Rust project by leveragin

Make any NixOS system netbootable with 10s cycle times.

nix-netboot-serve Dynamically generate netboot images for arbitrary NixOS system closures, profiles, or configurations with 10s iteration times. Usage

A lite tool to make systemd work in any container(Windows Subsystem for Linux 2, Docker, Podman, etc.)

Angea Naming from hydrangea(γ‚’γ‚Έγ‚΅γ‚€) A lite tool to make systemd work in any container(Windows Subsystem for Linux 2, Docker, Podman, etc.) WSL1 is not s

Owner
Wisha W.
Wisha W.
Demonstration of flexible function calls in Rust with function overloading and optional arguments

Table of Contents Table of Contents flexible-fn-rs What is this trying to demo? How is the code structured? Named/Unnamed and Optional arguments Mecha

Tien Duc (TiDu) Nguyen 81 Nov 3, 2022
Pass Rust strings to C with potentially not needing heap allocation

cfixed-string is used for passing Rust string to C with potentially not needing to do a heap allocation. A problem with using the standard library CSt

Daniel Collin 11 Dec 2, 2022
A Rust-based tool to analyze an application's heap.

Heap analysis tool for Rust Heap analysis is a pure-Rust implementation to track memory allocations on the heap. Usage Heap analysis provides a custom

Moritz Hoffmann 8 May 9, 2022
Full tutorial on coding AI function calling in Rust programming by [Jeremy Chone](https://youtube.com/jeremychone)

Full tutorial on coding AI function calling in Rust programming by Jeremy Chone. We will be using the OpenAI API, but similar approaches can be applie

null 14 May 26, 2024
Async variant of Tonic's `interceptor` function

Tonic Async Interceptor This crate contains AsyncInterceptor, an async variant of Tonic's Interceptor. Other than accepting an async interceptor funct

Arcanyx Technical Wizardry LLC 4 Dec 20, 2022
Select any exported function in a dll as the new dll's entry point.

Description This tool will patch the entry point of the input dll and replace it with the RVA of another exported function in that same dll. This allo

Kurosh Dabbagh Escalante 43 Jun 7, 2023
The lambda-chaos-extension allows you to inject faults into Lambda functions without modifying the function code.

Chaos Extension - Seamless, Universal & Lightning-Fast The lambda-chaos-extension allows you to inject faults into Lambda functions without modifying

AWS CLI Tools 5 Aug 2, 2023
Asynchronous runtime abstractions for implicit function decoloring.

decolor Asynchronous runtime abstractions for implicit function decoloring. Decolor is in beta Install | User Docs | Crate Docs | Reference | Contribu

refcell.eth 11 Oct 26, 2023
Rust + Yew + Axum + Tauri, full-stack Rust development for Desktop apps.

rust-yew-axum-tauri-desktop template Rust + Yew + Axum + Tauri, full-stack Rust development for Desktop apps. Crates frontend: Yew frontend app for de

Jet Li 54 Dec 23, 2022
Stack unwinding library in Rust

Unwinding library in Rust and for Rust This library serves two purposes: Provide a pure Rust alternative to libgcc_eh or libunwind. Provide easier unw

Gary Guo 51 Nov 4, 2022