blob: 38ec9c465ec2b85a7d686896a20c6dcb0e72cce3 [file] [log] [blame]
Adam Lesinski66ea8402017-06-28 11:44:11 -07001/*
2 * Copyright (C) 2017 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
17#include "text/Unicode.h"
18
19#include <algorithm>
20#include <array>
21
22#include "text/Utf8Iterator.h"
23
24using ::android::StringPiece;
25
26namespace aapt {
27namespace text {
28
29namespace {
30
31struct CharacterProperties {
32 enum : uint32_t {
33 kXidStart = 1 << 0,
34 kXidContinue = 1 << 1,
35 };
36
37 char32_t first_char;
38 char32_t last_char;
39 uint32_t properties;
40};
41
42// Incude the generated data table.
43#include "text/Unicode_data.cpp"
44
45bool CompareCharacterProperties(const CharacterProperties& a, char32_t codepoint) {
46 return a.last_char < codepoint;
47}
48
49uint32_t FindCharacterProperties(char32_t codepoint) {
50 const auto iter_end = sCharacterProperties.end();
51 const auto iter = std::lower_bound(sCharacterProperties.begin(), iter_end, codepoint,
52 CompareCharacterProperties);
53 if (iter != iter_end && codepoint >= iter->first_char) {
54 return iter->properties;
55 }
56 return 0u;
57}
58
59} // namespace
60
61bool IsXidStart(char32_t codepoint) {
62 return FindCharacterProperties(codepoint) & CharacterProperties::kXidStart;
63}
64
65bool IsXidContinue(char32_t codepoint) {
66 return FindCharacterProperties(codepoint) & CharacterProperties::kXidContinue;
67}
68
69bool IsJavaIdentifier(const StringPiece& str) {
70 Utf8Iterator iter(str);
71
72 // Check the first character.
73 if (!iter.HasNext()) {
74 return false;
75 }
76
77 if (!IsXidStart(iter.Next())) {
78 return false;
79 }
80
81 while (iter.HasNext()) {
82 const char32_t codepoint = iter.Next();
83 if (!IsXidContinue(codepoint) && codepoint != U'$') {
84 return false;
85 }
86 }
87 return true;
88}
89
90bool IsValidResourceEntryName(const StringPiece& str) {
91 Utf8Iterator iter(str);
92
93 // Check the first character.
94 if (!iter.HasNext()) {
95 return false;
96 }
97
98 // Resources are allowed to start with '_'
99 const char32_t first_codepoint = iter.Next();
100 if (!IsXidStart(first_codepoint) && first_codepoint != U'_') {
101 return false;
102 }
103
104 while (iter.HasNext()) {
105 const char32_t codepoint = iter.Next();
106 if (!IsXidContinue(codepoint) && codepoint != U'.' && codepoint != U'-') {
107 return false;
108 }
109 }
110 return true;
111}
112
113} // namespace text
114} // namespace aapt