about summary refs log tree commit diff
path: root/src/tools/clippy/tests/ui/manual_option_as_slice.rs
blob: e1a97a6b271159b0aebddcc29d12420e6f5cb085 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#![warn(clippy::manual_option_as_slice)]
#![allow(clippy::redundant_closure, clippy::unwrap_or_default)]

fn check(x: Option<u32>) {
    _ = match x.as_ref() {
        //~^ manual_option_as_slice
        Some(f) => std::slice::from_ref(f),
        None => &[],
    };

    _ = if let Some(f) = x.as_ref() {
        //~^ manual_option_as_slice

        std::slice::from_ref(f)
    } else {
        &[]
    };

    _ = x.as_ref().map_or(&[][..], std::slice::from_ref);
    //~^ manual_option_as_slice

    _ = x.as_ref().map_or_else(Default::default, std::slice::from_ref);
    //~^ manual_option_as_slice

    _ = x.as_ref().map(std::slice::from_ref).unwrap_or_default();
    //~^ manual_option_as_slice

    _ = x.as_ref().map_or_else(|| &[42][..0], std::slice::from_ref);
    //~^ manual_option_as_slice

    {
        use std::slice::from_ref;
        _ = x.as_ref().map_or_else(<&[_]>::default, from_ref);
        //~^ manual_option_as_slice
    }

    // possible false positives
    let y = x.as_ref();
    _ = match y {
        // as_ref outside
        Some(f) => &[f][..],
        None => &[][..],
    };
    _ = match x.as_ref() {
        Some(f) => std::slice::from_ref(f),
        None => &[0],
    };
    _ = match x.as_ref() {
        Some(42) => &[23],
        Some(f) => std::slice::from_ref(f),
        None => &[],
    };
    let b = &[42];
    _ = if let Some(_f) = x.as_ref() {
        std::slice::from_ref(b)
    } else {
        &[]
    };
    _ = x.as_ref().map_or(&[42][..], std::slice::from_ref);
    _ = x.as_ref().map_or_else(|| &[42][..1], std::slice::from_ref);
    _ = x.as_ref().map(|f| std::slice::from_ref(f)).unwrap_or_default();
}

#[clippy::msrv = "1.74"]
fn check_msrv(x: Option<u32>) {
    _ = x.as_ref().map_or(&[][..], std::slice::from_ref);
}

fn main() {
    check(Some(1));
    check_msrv(Some(175));
}