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
pub(crate) fn append_path(name: &mut String, append: &str) {
    if !append.is_empty() {
        if !name.is_empty() {
            name.push('.');
        }
        name.push_str(append);
    }
}

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 compute_full_name(package: &str, path_to_package: &str, name: &str) -> String {
    assert!(!name.is_empty());

    let mut full_name = package.to_owned();
    append_path(&mut full_name, path_to_package);
    append_path(&mut full_name, name);
    full_name
}

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", ""));
}