scale_info/
utils.rs

1// Copyright 2019-2022 Parity Technologies (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/// Returns `true` if the given string is a proper Rust identifier.
16pub fn is_rust_identifier(s: &str) -> bool {
17    // Only ascii encoding is allowed.
18    // Note: Maybe this check is superseded by the `head` and `tail` check.
19    if !s.is_ascii() {
20        return false;
21    }
22    // Trim valid raw identifier prefix
23    let trimmed = s.trim_start_matches("r#");
24    if let Some((&head, tail)) = trimmed.as_bytes().split_first() {
25        // Check if head and tail make up a proper Rust identifier.
26        let head_ok = head == b'_' || head.is_ascii_lowercase() || head.is_ascii_uppercase();
27        let tail_ok = tail.iter().all(|&ch| {
28            ch == b'_' || ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch.is_ascii_digit()
29        });
30        head_ok && tail_ok
31    } else {
32        // String is empty and thus not a valid Rust identifier.
33        false
34    }
35}