protobuf/reflect/
name.rs

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
pub(crate) fn concat_paths(a: &str, b: &str) -> String {
    if a.is_empty() {
        b.to_owned()
    } else if b.is_empty() {
        b.to_owned()
    } else {
        format!("{}.{}", a, b)
    }
}

pub(crate) fn protobuf_name_starts_with_package<'a>(
    name: &'a str,
    package: &str,
) -> Option<&'a str> {
    assert!(
        !package.starts_with("."),
        "package must not start with dot: {}",
        package
    );

    assert!(
        name.starts_with("."),
        "full name must start with dot: {}",
        name
    );
    let name = &name[1..];
    // assert!(!name.starts_with("."), "full name must not start with dot: {}", name);

    if package.is_empty() {
        Some(name)
    } else {
        if name.starts_with(package) {
            let rem = &name[package.len()..];
            if rem.starts_with(".") {
                Some(&rem[1..])
            } else {
                None
            }
        } else {
            None
        }
    }
}

#[test]
fn test_protobuf_name_starts_with_package() {
    assert_eq!(
        Some("bar"),
        protobuf_name_starts_with_package(".foo.bar", "foo")
    );
    assert_eq!(None, protobuf_name_starts_with_package(".foo", "foo"));
    assert_eq!(Some("foo"), protobuf_name_starts_with_package(".foo", ""));
}