aboutsummaryrefslogtreecommitdiff
path: root/tests/index.rs
blob: 50abd6c360760a3cfd219e685d725f8ab5b9864e (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#![cfg(feature = "raw_os_str")]

use std::ops::Index;
use std::panic;
use std::panic::UnwindSafe;

use os_str_bytes::RawOsStr;

mod common;
use common::RAW_WTF8_STRING;

#[test]
fn test_valid_indices() {
    test(0);
    test(1);
    test(2);
    test(3);
    test(6);
    test(10);
    test(11);
    test(12);
    test(13);

    #[track_caller]
    fn test(index: usize) {
        let _ = RAW_WTF8_STRING.index(index..);
    }
}

macro_rules! test {
    ( $name:ident , $index:literal , $code_point:expr ) => {
        // https://github.com/rust-lang/rust/issues/88430
        #[test]
        fn $name() {
            let index_fn = || RAW_WTF8_STRING.index($index..);
            if cfg!(unix) {
                let _ = index_fn();
                return;
            }

            let error = panic::catch_unwind(index_fn)
                .expect_err("test did not panic as expected");
            let error: &String =
                error.downcast_ref().expect("incorrect panic message type");
            assert_eq!(
                concat!(
                    "byte index ",
                    $index,
                    " is not a valid boundary; it is inside ",
                    $code_point
                ),
                error,
            );
        }
    };
}

test!(test_index_4, 4, "U+D83D (bytes 3..6)");

test!(test_index_5, 5, "U+D83D (bytes 3..6)");

test!(test_index_7, 7, "U+1F4A9 (bytes 6..10)");

test!(test_index_8, 8, "U+1F4A9 (bytes 6..10)");

test!(test_index_9, 9, "U+1F4A9 (bytes 6..10)");

#[test]
fn test_index_panics() {
    let string = RawOsStr::from_str("\u{F6}");
    test(|| string.index(1..2));
    test(|| string.index(0..1));
    test(|| string.index(1..));
    test(|| string.index(0..=0));
    test(|| string.index(..1));
    test(|| string.index(..=0));
    test(|| string.split_at(1));

    #[track_caller]
    fn test<F, R>(f: F)
    where
        F: FnOnce() -> R + UnwindSafe,
    {
        assert_eq!(!cfg!(unix), panic::catch_unwind(f).is_err());
    }
}