blob: b60ec51c1dec4c0ccf76d78c9d0bda5c7b1b88fa [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
17pub fn is_valid_identifier(s: &str) -> bool {
18 // 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
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn test_is_valid_identifier() {
35 assert!(is_valid_identifier("foo"));
36 assert!(is_valid_identifier("foo_bar_123"));
37
38 assert!(!is_valid_identifier(""));
39 assert!(!is_valid_identifier("123_foo"));
40 assert!(!is_valid_identifier("foo-bar"));
41 assert!(!is_valid_identifier("foo-b\u{00e5}r"));
42 }
43}