~jplatte/turbo.fish

ref: d1706d2d4dfdcd47b8aa5e70cf92c957ee5405f9 turbo.fish/src/random.rs -rw-r--r-- 1.1 KiB
d1706d2d — Jonas Platte Add FUNDING.yml 1 year, 3 months ago
                                                                                
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
44
45
46
47
48
49
50
51
52
53
54
55
use rand::seq::SliceRandom;

const RECURSION_LIMIT: u8 = 1;

static TYPES: &[(&str, usize)] = &[
    ("_", 0),
    ("bool", 0),
    ("char", 0),
    ("i8", 0),
    ("i16", 0),
    ("i32", 0),
    ("i64", 0),
    ("isize", 0),
    ("u8", 0),
    ("u16", 0),
    ("u32", 0),
    ("u64", 0),
    ("usize", 0),
    ("f32", 0),
    ("f64", 0),
    ("&str", 0),
    ("String", 0),
    ("()", 0),
    ("Vec", 1),
    ("HashSet", 1),
    ("HashMap", 2),
    ("Box", 1),
    ("Result", 2),
];

pub fn random_type() -> String {
    random_type_depth(0)
}

fn random_type_depth(depth: u8) -> String {
    let (type_name, generics) = TYPES.choose(&mut rand::thread_rng()).unwrap();
    if *generics == 0 {
        type_name.to_string()
    } else if depth == RECURSION_LIMIT {
        format!(
            "{}<{}>",
            type_name,
            (0..*generics).map(|_| "_").collect::<Vec<_>>().join(", ")
        )
    } else {
        format!(
            "{}<{}>",
            type_name,
            (0..*generics)
                .map(|_| random_type_depth(depth + 1))
                .collect::<Vec<_>>()
                .join(", ")
        )
    }
}