summaryrefslogtreecommitdiffstats
path: root/library/std/src/sys/common/tests.rs
blob: fb6f5d6af8371d582b001b07713c9467fe02d376 (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
use crate::ffi::CString;
use crate::hint::black_box;
use crate::path::Path;
use crate::sys::common::small_c_string::run_path_with_cstr;
use core::iter::repeat;

#[test]
fn stack_allocation_works() {
    let path = Path::new("abc");
    let result = run_path_with_cstr(path, |p| {
        assert_eq!(p, &*CString::new(path.as_os_str().bytes()).unwrap());
        Ok(42)
    });
    assert_eq!(result.unwrap(), 42);
}

#[test]
fn stack_allocation_fails() {
    let path = Path::new("ab\0");
    assert!(run_path_with_cstr::<(), _>(path, |_| unreachable!()).is_err());
}

#[test]
fn heap_allocation_works() {
    let path = repeat("a").take(384).collect::<String>();
    let path = Path::new(&path);
    let result = run_path_with_cstr(path, |p| {
        assert_eq!(p, &*CString::new(path.as_os_str().bytes()).unwrap());
        Ok(42)
    });
    assert_eq!(result.unwrap(), 42);
}

#[test]
fn heap_allocation_fails() {
    let mut path = repeat("a").take(384).collect::<String>();
    path.push('\0');
    let path = Path::new(&path);
    assert!(run_path_with_cstr::<(), _>(path, |_| unreachable!()).is_err());
}

#[bench]
fn bench_stack_path_alloc(b: &mut test::Bencher) {
    let path = repeat("a").take(383).collect::<String>();
    let p = Path::new(&path);
    b.iter(|| {
        run_path_with_cstr(p, |cstr| {
            black_box(cstr);
            Ok(())
        })
        .unwrap();
    });
}

#[bench]
fn bench_heap_path_alloc(b: &mut test::Bencher) {
    let path = repeat("a").take(384).collect::<String>();
    let p = Path::new(&path);
    b.iter(|| {
        run_path_with_cstr(p, |cstr| {
            black_box(cstr);
            Ok(())
        })
        .unwrap();
    });
}