1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
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 
16 #include "color_parser.h"
17 
18 #include <cstdlib>
19 
20 namespace OHOS {
21 namespace Rosen {
Parse(const std::string & colorStr,uint32_t & colorValue)22 bool ColorParser::Parse(const std::string& colorStr, uint32_t& colorValue)
23 {
24     if (colorStr.empty()) {
25         return false;
26     }
27 
28     if (colorStr[0] == '#') { // start with '#'
29         std::string color = colorStr.substr(1);
30         if (!IsValidHexString(color)) {
31             return false;
32         }
33         constexpr int HEX = 16;
34         colorValue = std::strtoul(color.c_str(), 0, HEX); // convert hex string to number
35         if (colorStr.size() == 7) { // 7 is color string length.#RRGGBB: RRGGBB -> AARRGGBB
36             colorValue |= 0xff000000;
37             return true;
38         }
39         if (colorStr.size() == 9) { // 9 is color string length.#AARRGGBB
40             return true;
41         }
42     }
43     return false;
44 }
45 
IsValidHexString(const std::string & colorStr)46 bool ColorParser::IsValidHexString(const std::string& colorStr)
47 {
48     if (colorStr.empty()) {
49         return false;
50     }
51     for (char ch : colorStr) {
52         if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) {
53             continue;
54         }
55         return false;
56     }
57     return true;
58 }
59 } // namespace Rosen
60 } // namespace OHOS
61