1 //
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 "property_type.h"
18 
19 #include <android-base/parsedouble.h>
20 #include <android-base/parseint.h>
21 #include <android-base/strings.h>
22 
23 using android::base::ParseDouble;
24 using android::base::ParseInt;
25 using android::base::ParseUint;
26 using android::base::Split;
27 
28 namespace android {
29 namespace init {
30 
CheckType(const std::string & type_string,const std::string & value)31 bool CheckType(const std::string& type_string, const std::string& value) {
32     // Always allow clearing a property such that the default value when it is not set takes over.
33     if (value.empty()) {
34         return true;
35     }
36 
37     auto type_strings = Split(type_string, " ");
38     if (type_strings.empty()) {
39         return false;
40     }
41     auto type = type_strings[0];
42 
43     if (type == "string") {
44         return true;
45     }
46     if (type == "bool") {
47         return value == "true" || value == "false" || value == "1" || value == "0";
48     }
49     if (type == "int") {
50         int64_t parsed;
51         return ParseInt(value, &parsed);
52     }
53     if (type == "uint") {
54         uint64_t parsed;
55         if (value.empty() || value.front() == '-') {
56             return false;
57         }
58         return ParseUint(value, &parsed);
59     }
60     if (type == "double") {
61         double parsed;
62         return ParseDouble(value.c_str(), &parsed);
63     }
64     if (type == "size") {
65         auto it = value.begin();
66         while (it != value.end() && isdigit(*it)) {
67             it++;
68         }
69         if (it == value.begin() || it == value.end() || (*it != 'g' && *it != 'k' && *it != 'm')) {
70             return false;
71         }
72         it++;
73         return it == value.end();
74     }
75     if (type == "enum") {
76         for (auto it = std::next(type_strings.begin()); it != type_strings.end(); ++it) {
77             if (*it == value) {
78                 return true;
79             }
80         }
81     }
82     return false;
83 }
84 
85 }  // namespace init
86 }  // namespace android
87