File: ctfe-collatz-multi-rec.rs

package info (click to toggle)
rustc-web 1.85.0%2Bdfsg3-1~deb12u3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,759,988 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,056; lisp: 29; perl: 29; ruby: 19; sql: 11
file content (43 lines) | stat: -rw-r--r-- 1,028 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//@ run-pass
#![expect(incomplete_features)]
#![feature(explicit_tail_calls)]

/// A very unnecessarily complicated "implementation" of the Collatz conjecture.
/// Returns the number of steps to reach `1`.
///
/// This is just a test for tail calls, which involves multiple functions calling each other.
///
/// Panics if `x == 0`.
const fn collatz(x: u32) -> u32 {
    assert!(x > 0);

    const fn switch(x: u32, steps: u32) -> u32 {
        match x {
            1 => steps,
            _ if x & 1 == 0 => become div2(x, steps + 1),
            _ => become mul3plus1(x, steps + 1),
        }
    }

    const fn div2(x: u32, steps: u32) -> u32 {
        become switch(x >> 1, steps)
    }

    const fn mul3plus1(x: u32, steps: u32) -> u32 {
        become switch(3 * x + 1, steps)
    }

    switch(x, 0)
}

const ASSERTS: () = {
    assert!(collatz(1) == 0);
    assert!(collatz(2) == 1);
    assert!(collatz(3) == 7);
    assert!(collatz(4) == 2);
    assert!(collatz(6171) == 261);
};

fn main() {
    let _ = ASSERTS;
}