1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 #include <google/protobuf/util/internal/utility.h>
32
33 #include <algorithm>
34 #include <cmath>
35 #include <limits>
36
37 #include <google/protobuf/stubs/callback.h>
38 #include <google/protobuf/stubs/common.h>
39 #include <google/protobuf/stubs/logging.h>
40 #include <google/protobuf/wrappers.pb.h>
41 #include <google/protobuf/descriptor.pb.h>
42 #include <google/protobuf/descriptor.h>
43 #include <google/protobuf/util/internal/constants.h>
44 #include <google/protobuf/stubs/strutil.h>
45 #include <google/protobuf/stubs/map_util.h>
46
47 // clang-format off
48 #include <google/protobuf/port_def.inc>
49 // clang-format on
50
51 namespace google {
52 namespace protobuf {
53 namespace util {
54 namespace converter {
55
GetBoolOptionOrDefault(const RepeatedPtrField<google::protobuf::Option> & options,StringPiece option_name,bool default_value)56 bool GetBoolOptionOrDefault(
57 const RepeatedPtrField<google::protobuf::Option>& options,
58 StringPiece option_name, bool default_value) {
59 const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
60 if (opt == nullptr) {
61 return default_value;
62 }
63 return GetBoolFromAny(opt->value());
64 }
65
GetInt64OptionOrDefault(const RepeatedPtrField<google::protobuf::Option> & options,StringPiece option_name,int64 default_value)66 int64 GetInt64OptionOrDefault(
67 const RepeatedPtrField<google::protobuf::Option>& options,
68 StringPiece option_name, int64 default_value) {
69 const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
70 if (opt == nullptr) {
71 return default_value;
72 }
73 return GetInt64FromAny(opt->value());
74 }
75
GetDoubleOptionOrDefault(const RepeatedPtrField<google::protobuf::Option> & options,StringPiece option_name,double default_value)76 double GetDoubleOptionOrDefault(
77 const RepeatedPtrField<google::protobuf::Option>& options,
78 StringPiece option_name, double default_value) {
79 const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
80 if (opt == nullptr) {
81 return default_value;
82 }
83 return GetDoubleFromAny(opt->value());
84 }
85
GetStringOptionOrDefault(const RepeatedPtrField<google::protobuf::Option> & options,StringPiece option_name,StringPiece default_value)86 std::string GetStringOptionOrDefault(
87 const RepeatedPtrField<google::protobuf::Option>& options,
88 StringPiece option_name, StringPiece default_value) {
89 const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
90 if (opt == nullptr) {
91 return std::string(default_value);
92 }
93 return GetStringFromAny(opt->value());
94 }
95
96 template <typename T>
ParseFromAny(const std::string & data,T * result)97 void ParseFromAny(const std::string& data, T* result) {
98 result->ParseFromString(data);
99 }
100
101 // Returns a boolean value contained in Any type.
102 // TODO(skarvaje): Add type checking & error messages here.
GetBoolFromAny(const google::protobuf::Any & any)103 bool GetBoolFromAny(const google::protobuf::Any& any) {
104 google::protobuf::BoolValue b;
105 ParseFromAny(any.value(), &b);
106 return b.value();
107 }
108
GetInt64FromAny(const google::protobuf::Any & any)109 int64 GetInt64FromAny(const google::protobuf::Any& any) {
110 google::protobuf::Int64Value i;
111 ParseFromAny(any.value(), &i);
112 return i.value();
113 }
114
GetDoubleFromAny(const google::protobuf::Any & any)115 double GetDoubleFromAny(const google::protobuf::Any& any) {
116 google::protobuf::DoubleValue i;
117 ParseFromAny(any.value(), &i);
118 return i.value();
119 }
120
GetStringFromAny(const google::protobuf::Any & any)121 std::string GetStringFromAny(const google::protobuf::Any& any) {
122 google::protobuf::StringValue s;
123 ParseFromAny(any.value(), &s);
124 return s.value();
125 }
126
GetTypeWithoutUrl(StringPiece type_url)127 const StringPiece GetTypeWithoutUrl(StringPiece type_url) {
128 if (type_url.size() > kTypeUrlSize && type_url[kTypeUrlSize] == '/') {
129 return type_url.substr(kTypeUrlSize + 1);
130 } else {
131 size_t idx = type_url.rfind('/');
132 if (idx != type_url.npos) {
133 type_url.remove_prefix(idx + 1);
134 }
135 return type_url;
136 }
137 }
138
GetFullTypeWithUrl(StringPiece simple_type)139 const std::string GetFullTypeWithUrl(StringPiece simple_type) {
140 return StrCat(kTypeServiceBaseUrl, "/", simple_type);
141 }
142
FindOptionOrNull(const RepeatedPtrField<google::protobuf::Option> & options,StringPiece option_name)143 const google::protobuf::Option* FindOptionOrNull(
144 const RepeatedPtrField<google::protobuf::Option>& options,
145 StringPiece option_name) {
146 for (int i = 0; i < options.size(); ++i) {
147 const google::protobuf::Option& opt = options.Get(i);
148 if (opt.name() == option_name) {
149 return &opt;
150 }
151 }
152 return nullptr;
153 }
154
FindFieldInTypeOrNull(const google::protobuf::Type * type,StringPiece field_name)155 const google::protobuf::Field* FindFieldInTypeOrNull(
156 const google::protobuf::Type* type, StringPiece field_name) {
157 if (type != nullptr) {
158 for (int i = 0; i < type->fields_size(); ++i) {
159 const google::protobuf::Field& field = type->fields(i);
160 if (field.name() == field_name) {
161 return &field;
162 }
163 }
164 }
165 return nullptr;
166 }
167
FindJsonFieldInTypeOrNull(const google::protobuf::Type * type,StringPiece json_name)168 const google::protobuf::Field* FindJsonFieldInTypeOrNull(
169 const google::protobuf::Type* type, StringPiece json_name) {
170 if (type != nullptr) {
171 for (int i = 0; i < type->fields_size(); ++i) {
172 const google::protobuf::Field& field = type->fields(i);
173 if (field.json_name() == json_name) {
174 return &field;
175 }
176 }
177 }
178 return nullptr;
179 }
180
FindFieldInTypeByNumberOrNull(const google::protobuf::Type * type,int32 number)181 const google::protobuf::Field* FindFieldInTypeByNumberOrNull(
182 const google::protobuf::Type* type, int32 number) {
183 if (type != nullptr) {
184 for (int i = 0; i < type->fields_size(); ++i) {
185 const google::protobuf::Field& field = type->fields(i);
186 if (field.number() == number) {
187 return &field;
188 }
189 }
190 }
191 return nullptr;
192 }
193
FindEnumValueByNameOrNull(const google::protobuf::Enum * enum_type,StringPiece enum_name)194 const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
195 const google::protobuf::Enum* enum_type, StringPiece enum_name) {
196 if (enum_type != nullptr) {
197 for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
198 const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
199 if (enum_value.name() == enum_name) {
200 return &enum_value;
201 }
202 }
203 }
204 return nullptr;
205 }
206
FindEnumValueByNumberOrNull(const google::protobuf::Enum * enum_type,int32 value)207 const google::protobuf::EnumValue* FindEnumValueByNumberOrNull(
208 const google::protobuf::Enum* enum_type, int32 value) {
209 if (enum_type != nullptr) {
210 for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
211 const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
212 if (enum_value.number() == value) {
213 return &enum_value;
214 }
215 }
216 }
217 return nullptr;
218 }
219
FindEnumValueByNameWithoutUnderscoreOrNull(const google::protobuf::Enum * enum_type,StringPiece enum_name)220 const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
221 const google::protobuf::Enum* enum_type, StringPiece enum_name) {
222 if (enum_type != nullptr) {
223 for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
224 const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
225 std::string enum_name_without_underscore = enum_value.name();
226
227 // Remove underscore from the name.
228 enum_name_without_underscore.erase(
229 std::remove(enum_name_without_underscore.begin(),
230 enum_name_without_underscore.end(), '_'),
231 enum_name_without_underscore.end());
232 // Make the name uppercase.
233 for (std::string::iterator it = enum_name_without_underscore.begin();
234 it != enum_name_without_underscore.end(); ++it) {
235 *it = ascii_toupper(*it);
236 }
237
238 if (enum_name_without_underscore == enum_name) {
239 return &enum_value;
240 }
241 }
242 }
243 return nullptr;
244 }
245
EnumValueNameToLowerCamelCase(StringPiece input)246 std::string EnumValueNameToLowerCamelCase(StringPiece input) {
247 std::string input_string(input);
248 std::transform(input_string.begin(), input_string.end(), input_string.begin(),
249 ::tolower);
250 return ToCamelCase(input_string);
251 }
252
ToCamelCase(StringPiece input)253 std::string ToCamelCase(StringPiece input) {
254 bool capitalize_next = false;
255 bool was_cap = true;
256 bool is_cap = false;
257 bool first_word = true;
258 std::string result;
259 result.reserve(input.size());
260
261 for (size_t i = 0; i < input.size(); ++i, was_cap = is_cap) {
262 is_cap = ascii_isupper(input[i]);
263 if (input[i] == '_') {
264 capitalize_next = true;
265 if (!result.empty()) first_word = false;
266 continue;
267 } else if (first_word) {
268 // Consider when the current character B is capitalized,
269 // first word ends when:
270 // 1) following a lowercase: "...aB..."
271 // 2) followed by a lowercase: "...ABc..."
272 if (!result.empty() && is_cap &&
273 (!was_cap ||
274 (i + 1 < input.size() && ascii_islower(input[i + 1])))) {
275 first_word = false;
276 result.push_back(input[i]);
277 } else {
278 result.push_back(ascii_tolower(input[i]));
279 continue;
280 }
281 } else if (capitalize_next) {
282 capitalize_next = false;
283 if (ascii_islower(input[i])) {
284 result.push_back(ascii_toupper(input[i]));
285 continue;
286 } else {
287 result.push_back(input[i]);
288 continue;
289 }
290 } else {
291 result.push_back(ascii_tolower(input[i]));
292 }
293 }
294 return result;
295 }
296
ToSnakeCase(StringPiece input)297 std::string ToSnakeCase(StringPiece input) {
298 bool was_not_underscore = false; // Initialize to false for case 1 (below)
299 bool was_not_cap = false;
300 std::string result;
301 result.reserve(input.size() << 1);
302
303 for (size_t i = 0; i < input.size(); ++i) {
304 if (ascii_isupper(input[i])) {
305 // Consider when the current character B is capitalized:
306 // 1) At beginning of input: "B..." => "b..."
307 // (e.g. "Biscuit" => "biscuit")
308 // 2) Following a lowercase: "...aB..." => "...a_b..."
309 // (e.g. "gBike" => "g_bike")
310 // 3) At the end of input: "...AB" => "...ab"
311 // (e.g. "GoogleLAB" => "google_lab")
312 // 4) Followed by a lowercase: "...ABc..." => "...a_bc..."
313 // (e.g. "GBike" => "g_bike")
314 if (was_not_underscore && // case 1 out
315 (was_not_cap || // case 2 in, case 3 out
316 (i + 1 < input.size() && // case 3 out
317 ascii_islower(input[i + 1])))) { // case 4 in
318 // We add an underscore for case 2 and case 4.
319 result.push_back('_');
320 }
321 result.push_back(ascii_tolower(input[i]));
322 was_not_underscore = true;
323 was_not_cap = false;
324 } else {
325 result.push_back(input[i]);
326 was_not_underscore = input[i] != '_';
327 was_not_cap = true;
328 }
329 }
330 return result;
331 }
332
333 std::set<std::string>* well_known_types_ = NULL;
334 PROTOBUF_NAMESPACE_ID::internal::once_flag well_known_types_init_;
335 const char* well_known_types_name_array_[] = {
336 "google.protobuf.Timestamp", "google.protobuf.Duration",
337 "google.protobuf.DoubleValue", "google.protobuf.FloatValue",
338 "google.protobuf.Int64Value", "google.protobuf.UInt64Value",
339 "google.protobuf.Int32Value", "google.protobuf.UInt32Value",
340 "google.protobuf.BoolValue", "google.protobuf.StringValue",
341 "google.protobuf.BytesValue", "google.protobuf.FieldMask"};
342
DeleteWellKnownTypes()343 void DeleteWellKnownTypes() { delete well_known_types_; }
344
InitWellKnownTypes()345 void InitWellKnownTypes() {
346 well_known_types_ = new std::set<std::string>;
347 for (int i = 0; i < GOOGLE_ARRAYSIZE(well_known_types_name_array_); ++i) {
348 well_known_types_->insert(well_known_types_name_array_[i]);
349 }
350 google::protobuf::internal::OnShutdown(&DeleteWellKnownTypes);
351 }
352
IsWellKnownType(const std::string & type_name)353 bool IsWellKnownType(const std::string& type_name) {
354 PROTOBUF_NAMESPACE_ID::internal::call_once(well_known_types_init_,
355 InitWellKnownTypes);
356 return ContainsKey(*well_known_types_, type_name);
357 }
358
IsValidBoolString(StringPiece bool_string)359 bool IsValidBoolString(StringPiece bool_string) {
360 return bool_string == "true" || bool_string == "false" ||
361 bool_string == "1" || bool_string == "0";
362 }
363
IsMap(const google::protobuf::Field & field,const google::protobuf::Type & type)364 bool IsMap(const google::protobuf::Field& field,
365 const google::protobuf::Type& type) {
366 return field.cardinality() == google::protobuf::Field::CARDINALITY_REPEATED &&
367 (GetBoolOptionOrDefault(type.options(), "map_entry", false) ||
368 GetBoolOptionOrDefault(type.options(),
369 "google.protobuf.MessageOptions.map_entry",
370 false));
371 }
372
IsMessageSetWireFormat(const google::protobuf::Type & type)373 bool IsMessageSetWireFormat(const google::protobuf::Type& type) {
374 return GetBoolOptionOrDefault(type.options(), "message_set_wire_format",
375 false) ||
376 GetBoolOptionOrDefault(
377 type.options(),
378 "google.protobuf.MessageOptions.message_set_wire_format", false);
379 }
380
DoubleAsString(double value)381 std::string DoubleAsString(double value) {
382 if (value == std::numeric_limits<double>::infinity()) return "Infinity";
383 if (value == -std::numeric_limits<double>::infinity()) return "-Infinity";
384 if (std::isnan(value)) return "NaN";
385
386 return SimpleDtoa(value);
387 }
388
FloatAsString(float value)389 std::string FloatAsString(float value) {
390 if (std::isfinite(value)) return SimpleFtoa(value);
391 return DoubleAsString(value);
392 }
393
SafeStrToFloat(StringPiece str,float * value)394 bool SafeStrToFloat(StringPiece str, float* value) {
395 double double_value;
396 if (!safe_strtod(str, &double_value)) {
397 return false;
398 }
399
400 if (std::isinf(double_value) || std::isnan(double_value)) return false;
401
402 // Fail if the value is not representable in float.
403 if (double_value > std::numeric_limits<float>::max() ||
404 double_value < -std::numeric_limits<float>::max()) {
405 return false;
406 }
407
408 *value = static_cast<float>(double_value);
409 return true;
410 }
411
412 } // namespace converter
413 } // namespace util
414 } // namespace protobuf
415 } // namespace google
416