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 || (i + 1 < input.size() && ascii_islower(input[i + 1])))) {
274         first_word = false;
275         result.push_back(input[i]);
276       } else {
277         result.push_back(ascii_tolower(input[i]));
278         continue;
279       }
280     } else if (capitalize_next) {
281       capitalize_next = false;
282       if (ascii_islower(input[i])) {
283         result.push_back(ascii_toupper(input[i]));
284         continue;
285       } else {
286         result.push_back(input[i]);
287         continue;
288       }
289     } else {
290       result.push_back(ascii_tolower(input[i]));
291     }
292   }
293   return result;
294 }
295 
ToSnakeCase(StringPiece input)296 std::string ToSnakeCase(StringPiece input) {
297   bool was_not_underscore = false;  // Initialize to false for case 1 (below)
298   bool was_not_cap = false;
299   std::string result;
300   result.reserve(input.size() << 1);
301 
302   for (size_t i = 0; i < input.size(); ++i) {
303     if (ascii_isupper(input[i])) {
304       // Consider when the current character B is capitalized:
305       // 1) At beginning of input:   "B..." => "b..."
306       //    (e.g. "Biscuit" => "biscuit")
307       // 2) Following a lowercase:   "...aB..." => "...a_b..."
308       //    (e.g. "gBike" => "g_bike")
309       // 3) At the end of input:     "...AB" => "...ab"
310       //    (e.g. "GoogleLAB" => "google_lab")
311       // 4) Followed by a lowercase: "...ABc..." => "...a_bc..."
312       //    (e.g. "GBike" => "g_bike")
313       if (was_not_underscore &&               //            case 1 out
314           (was_not_cap ||                     // case 2 in, case 3 out
315            (i + 1 < input.size() &&           //            case 3 out
316             ascii_islower(input[i + 1])))) {  // case 4 in
317         // We add an underscore for case 2 and case 4.
318         result.push_back('_');
319       }
320       result.push_back(ascii_tolower(input[i]));
321       was_not_underscore = true;
322       was_not_cap = false;
323     } else {
324       result.push_back(input[i]);
325       was_not_underscore = input[i] != '_';
326       was_not_cap = true;
327     }
328   }
329   return result;
330 }
331 
332 std::set<std::string>* well_known_types_ = NULL;
333 PROTOBUF_NAMESPACE_ID::internal::once_flag well_known_types_init_;
334 const char* well_known_types_name_array_[] = {
335     "google.protobuf.Timestamp",   "google.protobuf.Duration",
336     "google.protobuf.DoubleValue", "google.protobuf.FloatValue",
337     "google.protobuf.Int64Value",  "google.protobuf.UInt64Value",
338     "google.protobuf.Int32Value",  "google.protobuf.UInt32Value",
339     "google.protobuf.BoolValue",   "google.protobuf.StringValue",
340     "google.protobuf.BytesValue",  "google.protobuf.FieldMask"};
341 
DeleteWellKnownTypes()342 void DeleteWellKnownTypes() { delete well_known_types_; }
343 
InitWellKnownTypes()344 void InitWellKnownTypes() {
345   well_known_types_ = new std::set<std::string>;
346   for (int i = 0; i < GOOGLE_ARRAYSIZE(well_known_types_name_array_); ++i) {
347     well_known_types_->insert(well_known_types_name_array_[i]);
348   }
349   google::protobuf::internal::OnShutdown(&DeleteWellKnownTypes);
350 }
351 
IsWellKnownType(const std::string & type_name)352 bool IsWellKnownType(const std::string& type_name) {
353   PROTOBUF_NAMESPACE_ID::internal::call_once(well_known_types_init_,
354                                              InitWellKnownTypes);
355   return ContainsKey(*well_known_types_, type_name);
356 }
357 
IsValidBoolString(StringPiece bool_string)358 bool IsValidBoolString(StringPiece bool_string) {
359   return bool_string == "true" || bool_string == "false" ||
360          bool_string == "1" || bool_string == "0";
361 }
362 
IsMap(const google::protobuf::Field & field,const google::protobuf::Type & type)363 bool IsMap(const google::protobuf::Field& field,
364            const google::protobuf::Type& type) {
365   return field.cardinality() == google::protobuf::Field::CARDINALITY_REPEATED &&
366          (GetBoolOptionOrDefault(type.options(), "map_entry", false) ||
367           GetBoolOptionOrDefault(type.options(),
368                                  "google.protobuf.MessageOptions.map_entry",
369                                  false));
370 }
371 
IsMessageSetWireFormat(const google::protobuf::Type & type)372 bool IsMessageSetWireFormat(const google::protobuf::Type& type) {
373   return GetBoolOptionOrDefault(type.options(), "message_set_wire_format",
374                                 false) ||
375          GetBoolOptionOrDefault(
376              type.options(),
377              "google.protobuf.MessageOptions.message_set_wire_format", false);
378 }
379 
DoubleAsString(double value)380 std::string DoubleAsString(double value) {
381   if (value == std::numeric_limits<double>::infinity()) return "Infinity";
382   if (value == -std::numeric_limits<double>::infinity()) return "-Infinity";
383   if (std::isnan(value)) return "NaN";
384 
385   return SimpleDtoa(value);
386 }
387 
FloatAsString(float value)388 std::string FloatAsString(float value) {
389   if (std::isfinite(value)) return SimpleFtoa(value);
390   return DoubleAsString(value);
391 }
392 
SafeStrToFloat(StringPiece str,float * value)393 bool SafeStrToFloat(StringPiece str, float* value) {
394   double double_value;
395   if (!safe_strtod(str, &double_value)) {
396     return false;
397   }
398 
399   if (std::isinf(double_value) || std::isnan(double_value)) return false;
400 
401   // Fail if the value is not representable in float.
402   if (double_value > std::numeric_limits<float>::max() ||
403       double_value < -std::numeric_limits<float>::max()) {
404     return false;
405   }
406 
407   *value = static_cast<float>(double_value);
408   return true;
409 }
410 
411 }  // namespace converter
412 }  // namespace util
413 }  // namespace protobuf
414 }  // namespace google
415