blob: 8ef0e0bc94cf5e832ec52831394ae5053ade6652 [file] [log] [blame]
Mårten Kongstad00cf0452023-05-26 16:48:01 +02001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mårten Kongstadfbd71e22023-05-31 13:29:35 +020017pub fn is_valid_name_ident(s: &str) -> bool {
Mårten Kongstad00cf0452023-05-26 16:48:01 +020018 // Identifiers must match [a-z][a-z0-9_]*
19 let mut chars = s.chars();
20 let Some(first) = chars.next() else {
21 return false;
22 };
23 if !first.is_ascii_lowercase() {
24 return false;
25 }
26 chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
27}
28
Mårten Kongstadfbd71e22023-05-31 13:29:35 +020029pub fn is_valid_package_ident(s: &str) -> bool {
30 s.split('.').all(is_valid_name_ident)
31}
32
Mårten Kongstad00cf0452023-05-26 16:48:01 +020033#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
Mårten Kongstadfbd71e22023-05-31 13:29:35 +020038 fn test_is_valid_name_ident() {
39 assert!(is_valid_name_ident("foo"));
40 assert!(is_valid_name_ident("foo_bar_123"));
Mårten Kongstad00cf0452023-05-26 16:48:01 +020041
Mårten Kongstadfbd71e22023-05-31 13:29:35 +020042 assert!(!is_valid_name_ident(""));
43 assert!(!is_valid_name_ident("123_foo"));
44 assert!(!is_valid_name_ident("foo-bar"));
45 assert!(!is_valid_name_ident("foo-b\u{00e5}r"));
46 }
47
48 #[test]
49 fn test_is_valid_package_ident() {
50 assert!(is_valid_package_ident("foo"));
51 assert!(is_valid_package_ident("foo_bar_123"));
52 assert!(is_valid_package_ident("foo.bar"));
53 assert!(is_valid_package_ident("foo.bar.a123"));
54
55 assert!(!is_valid_package_ident(""));
56 assert!(!is_valid_package_ident("123_foo"));
57 assert!(!is_valid_package_ident("foo-bar"));
58 assert!(!is_valid_package_ident("foo-b\u{00e5}r"));
59 assert!(!is_valid_package_ident("foo.bar.123"));
60 assert!(!is_valid_package_ident(".foo.bar"));
61 assert!(!is_valid_package_ident("foo.bar."));
62 assert!(!is_valid_package_ident("."));
63 assert!(!is_valid_package_ident("foo..bar"));
Mårten Kongstad00cf0452023-05-26 16:48:01 +020064 }
65}