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 
35 #include <google/protobuf/stubs/callback.h>
36 #include <google/protobuf/stubs/common.h>
37 #include <google/protobuf/stubs/logging.h>
38 #include <google/protobuf/wrappers.pb.h>
39 #include <google/protobuf/descriptor.pb.h>
40 #include <google/protobuf/descriptor.h>
41 #include <google/protobuf/util/internal/constants.h>
42 #include <google/protobuf/stubs/strutil.h>
43 #include <google/protobuf/stubs/map_util.h>
44 #include <google/protobuf/stubs/mathlimits.h>
45 
46 namespace google {
47 namespace protobuf {
48 namespace util {
49 namespace converter {
50 
GetBoolOptionOrDefault(const google::protobuf::RepeatedPtrField<google::protobuf::Option> & options,const string & option_name,bool default_value)51 bool GetBoolOptionOrDefault(
52     const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
53     const string& option_name, bool default_value) {
54   const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
55   if (opt == NULL) {
56     return default_value;
57   }
58   return GetBoolFromAny(opt->value());
59 }
60 
GetInt64OptionOrDefault(const google::protobuf::RepeatedPtrField<google::protobuf::Option> & options,const string & option_name,int64 default_value)61 int64 GetInt64OptionOrDefault(
62     const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
63     const string& option_name, int64 default_value) {
64   const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
65   if (opt == NULL) {
66     return default_value;
67   }
68   return GetInt64FromAny(opt->value());
69 }
70 
GetDoubleOptionOrDefault(const google::protobuf::RepeatedPtrField<google::protobuf::Option> & options,const string & option_name,double default_value)71 double GetDoubleOptionOrDefault(
72     const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
73     const string& option_name, double default_value) {
74   const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
75   if (opt == NULL) {
76     return default_value;
77   }
78   return GetDoubleFromAny(opt->value());
79 }
80 
GetStringOptionOrDefault(const google::protobuf::RepeatedPtrField<google::protobuf::Option> & options,const string & option_name,const string & default_value)81 string GetStringOptionOrDefault(
82     const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
83     const string& option_name, const string& default_value) {
84   const google::protobuf::Option* opt = FindOptionOrNull(options, option_name);
85   if (opt == NULL) {
86     return default_value;
87   }
88   return GetStringFromAny(opt->value());
89 }
90 
91 template <typename T>
ParseFromAny(const string & data,T * result)92 void ParseFromAny(const string& data, T* result) {
93   result->ParseFromString(data);
94 }
95 
96 // Returns a boolean value contained in Any type.
97 // TODO(skarvaje): Add type checking & error messages here.
GetBoolFromAny(const google::protobuf::Any & any)98 bool GetBoolFromAny(const google::protobuf::Any& any) {
99   google::protobuf::BoolValue b;
100   ParseFromAny(any.value(), &b);
101   return b.value();
102 }
103 
GetInt64FromAny(const google::protobuf::Any & any)104 int64 GetInt64FromAny(const google::protobuf::Any& any) {
105   google::protobuf::Int64Value i;
106   ParseFromAny(any.value(), &i);
107   return i.value();
108 }
109 
GetDoubleFromAny(const google::protobuf::Any & any)110 double GetDoubleFromAny(const google::protobuf::Any& any) {
111   google::protobuf::DoubleValue i;
112   ParseFromAny(any.value(), &i);
113   return i.value();
114 }
115 
GetStringFromAny(const google::protobuf::Any & any)116 string GetStringFromAny(const google::protobuf::Any& any) {
117   google::protobuf::StringValue s;
118   ParseFromAny(any.value(), &s);
119   return s.value();
120 }
121 
GetTypeWithoutUrl(StringPiece type_url)122 const StringPiece GetTypeWithoutUrl(StringPiece type_url) {
123   if (type_url.size() > kTypeUrlSize && type_url[kTypeUrlSize] == '/') {
124     return type_url.substr(kTypeUrlSize + 1);
125   } else {
126     size_t idx = type_url.rfind('/');
127     if (idx != type_url.npos) {
128       type_url.remove_prefix(idx + 1);
129     }
130     return type_url;
131   }
132 }
133 
GetFullTypeWithUrl(StringPiece simple_type)134 const string GetFullTypeWithUrl(StringPiece simple_type) {
135   return StrCat(kTypeServiceBaseUrl, "/", simple_type);
136 }
137 
FindOptionOrNull(const google::protobuf::RepeatedPtrField<google::protobuf::Option> & options,const string & option_name)138 const google::protobuf::Option* FindOptionOrNull(
139     const google::protobuf::RepeatedPtrField<google::protobuf::Option>& options,
140     const string& option_name) {
141   for (int i = 0; i < options.size(); ++i) {
142     const google::protobuf::Option& opt = options.Get(i);
143     if (opt.name() == option_name) {
144       return &opt;
145     }
146   }
147   return NULL;
148 }
149 
FindFieldInTypeOrNull(const google::protobuf::Type * type,StringPiece field_name)150 const google::protobuf::Field* FindFieldInTypeOrNull(
151     const google::protobuf::Type* type, StringPiece field_name) {
152   if (type != NULL) {
153     for (int i = 0; i < type->fields_size(); ++i) {
154       const google::protobuf::Field& field = type->fields(i);
155       if (field.name() == field_name) {
156         return &field;
157       }
158     }
159   }
160   return NULL;
161 }
162 
FindJsonFieldInTypeOrNull(const google::protobuf::Type * type,StringPiece json_name)163 const google::protobuf::Field* FindJsonFieldInTypeOrNull(
164     const google::protobuf::Type* type, StringPiece json_name) {
165   if (type != NULL) {
166     for (int i = 0; i < type->fields_size(); ++i) {
167       const google::protobuf::Field& field = type->fields(i);
168       if (field.json_name() == json_name) {
169         return &field;
170       }
171     }
172   }
173   return NULL;
174 }
175 
FindFieldInTypeByNumberOrNull(const google::protobuf::Type * type,int32 number)176 const google::protobuf::Field* FindFieldInTypeByNumberOrNull(
177     const google::protobuf::Type* type, int32 number) {
178   if (type != NULL) {
179     for (int i = 0; i < type->fields_size(); ++i) {
180       const google::protobuf::Field& field = type->fields(i);
181       if (field.number() == number) {
182         return &field;
183       }
184     }
185   }
186   return NULL;
187 }
188 
FindEnumValueByNameOrNull(const google::protobuf::Enum * enum_type,StringPiece enum_name)189 const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
190     const google::protobuf::Enum* enum_type, StringPiece enum_name) {
191   if (enum_type != NULL) {
192     for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
193       const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
194       if (enum_value.name() == enum_name) {
195         return &enum_value;
196       }
197     }
198   }
199   return NULL;
200 }
201 
FindEnumValueByNumberOrNull(const google::protobuf::Enum * enum_type,int32 value)202 const google::protobuf::EnumValue* FindEnumValueByNumberOrNull(
203     const google::protobuf::Enum* enum_type, int32 value) {
204   if (enum_type != NULL) {
205     for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
206       const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
207       if (enum_value.number() == value) {
208         return &enum_value;
209       }
210     }
211   }
212   return NULL;
213 }
214 
FindEnumValueByNameWithoutUnderscoreOrNull(const google::protobuf::Enum * enum_type,StringPiece enum_name)215 const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
216     const google::protobuf::Enum* enum_type, StringPiece enum_name) {
217   if (enum_type != NULL) {
218     for (int i = 0; i < enum_type->enumvalue_size(); ++i) {
219       const google::protobuf::EnumValue& enum_value = enum_type->enumvalue(i);
220       string enum_name_without_underscore = enum_value.name();
221 
222       // Remove underscore from the name.
223       enum_name_without_underscore.erase(
224           std::remove(enum_name_without_underscore.begin(),
225                       enum_name_without_underscore.end(), '_'),
226           enum_name_without_underscore.end());
227       // Make the name uppercase.
228       for (string::iterator it = enum_name_without_underscore.begin();
229            it != enum_name_without_underscore.end(); ++it) {
230         *it = ascii_toupper(*it);
231       }
232 
233       if (enum_name_without_underscore == enum_name) {
234         return &enum_value;
235       }
236     }
237   }
238   return NULL;
239 }
240 
ToCamelCase(const StringPiece input)241 string ToCamelCase(const StringPiece input) {
242   bool capitalize_next = false;
243   bool was_cap = true;
244   bool is_cap = false;
245   bool first_word = true;
246   string result;
247   result.reserve(input.size());
248 
249   for (size_t i = 0; i < input.size(); ++i, was_cap = is_cap) {
250     is_cap = ascii_isupper(input[i]);
251     if (input[i] == '_') {
252       capitalize_next = true;
253       if (!result.empty()) first_word = false;
254       continue;
255     } else if (first_word) {
256       // Consider when the current character B is capitalized,
257       // first word ends when:
258       // 1) following a lowercase:   "...aB..."
259       // 2) followed by a lowercase: "...ABc..."
260       if (!result.empty() && is_cap &&
261           (!was_cap || (i + 1 < input.size() && ascii_islower(input[i + 1])))) {
262         first_word = false;
263         result.push_back(input[i]);
264       } else {
265         result.push_back(ascii_tolower(input[i]));
266         continue;
267       }
268     } else if (capitalize_next) {
269       capitalize_next = false;
270       if (ascii_islower(input[i])) {
271         result.push_back(ascii_toupper(input[i]));
272         continue;
273       } else {
274         result.push_back(input[i]);
275         continue;
276       }
277     } else {
278       result.push_back(ascii_tolower(input[i]));
279     }
280   }
281   return result;
282 }
283 
ToSnakeCase(StringPiece input)284 string ToSnakeCase(StringPiece input) {
285   bool was_not_underscore = false;  // Initialize to false for case 1 (below)
286   bool was_not_cap = false;
287   string result;
288   result.reserve(input.size() << 1);
289 
290   for (size_t i = 0; i < input.size(); ++i) {
291     if (ascii_isupper(input[i])) {
292       // Consider when the current character B is capitalized:
293       // 1) At beginning of input:   "B..." => "b..."
294       //    (e.g. "Biscuit" => "biscuit")
295       // 2) Following a lowercase:   "...aB..." => "...a_b..."
296       //    (e.g. "gBike" => "g_bike")
297       // 3) At the end of input:     "...AB" => "...ab"
298       //    (e.g. "GoogleLAB" => "google_lab")
299       // 4) Followed by a lowercase: "...ABc..." => "...a_bc..."
300       //    (e.g. "GBike" => "g_bike")
301       if (was_not_underscore &&               //            case 1 out
302           (was_not_cap ||                     // case 2 in, case 3 out
303            (i + 1 < input.size() &&           //            case 3 out
304             ascii_islower(input[i + 1])))) {  // case 4 in
305         // We add an underscore for case 2 and case 4.
306         result.push_back('_');
307       }
308       result.push_back(ascii_tolower(input[i]));
309       was_not_underscore = true;
310       was_not_cap = false;
311     } else {
312       result.push_back(input[i]);
313       was_not_underscore = input[i] != '_';
314       was_not_cap = true;
315     }
316   }
317   return result;
318 }
319 
320 std::set<string>* well_known_types_ = NULL;
321 GOOGLE_PROTOBUF_DECLARE_ONCE(well_known_types_init_);
322 const char* well_known_types_name_array_[] = {
323     "google.protobuf.Timestamp",   "google.protobuf.Duration",
324     "google.protobuf.DoubleValue", "google.protobuf.FloatValue",
325     "google.protobuf.Int64Value",  "google.protobuf.UInt64Value",
326     "google.protobuf.Int32Value",  "google.protobuf.UInt32Value",
327     "google.protobuf.BoolValue",   "google.protobuf.StringValue",
328     "google.protobuf.BytesValue",  "google.protobuf.FieldMask"};
329 
DeleteWellKnownTypes()330 void DeleteWellKnownTypes() { delete well_known_types_; }
331 
InitWellKnownTypes()332 void InitWellKnownTypes() {
333   well_known_types_ = new std::set<string>;
334   for (int i = 0; i < GOOGLE_ARRAYSIZE(well_known_types_name_array_); ++i) {
335     well_known_types_->insert(well_known_types_name_array_[i]);
336   }
337   google::protobuf::internal::OnShutdown(&DeleteWellKnownTypes);
338 }
339 
IsWellKnownType(const string & type_name)340 bool IsWellKnownType(const string& type_name) {
341   InitWellKnownTypes();
342   return ContainsKey(*well_known_types_, type_name);
343 }
344 
IsValidBoolString(const string & bool_string)345 bool IsValidBoolString(const string& bool_string) {
346   return bool_string == "true" || bool_string == "false" ||
347          bool_string == "1" || bool_string == "0";
348 }
349 
IsMap(const google::protobuf::Field & field,const google::protobuf::Type & type)350 bool IsMap(const google::protobuf::Field& field,
351            const google::protobuf::Type& type) {
352   return field.cardinality() ==
353              google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
354          (GetBoolOptionOrDefault(type.options(), "map_entry", false) ||
355           GetBoolOptionOrDefault(type.options(),
356                                  "google.protobuf.MessageOptions.map_entry", false) ||
357           GetBoolOptionOrDefault(type.options(),
358                                  "google.protobuf.MessageOptions.map_entry",
359                                  false));
360 }
361 
IsMessageSetWireFormat(const google::protobuf::Type & type)362 bool IsMessageSetWireFormat(const google::protobuf::Type& type) {
363   return GetBoolOptionOrDefault(type.options(), "message_set_wire_format",
364                                 false) ||
365          GetBoolOptionOrDefault(type.options(),
366                                 "google.protobuf.MessageOptions.message_set_wire_format",
367                                 false) ||
368          GetBoolOptionOrDefault(
369              type.options(),
370              "google.protobuf.MessageOptions.message_set_wire_format", false);
371 }
372 
DoubleAsString(double value)373 string DoubleAsString(double value) {
374   if (MathLimits<double>::IsPosInf(value)) return "Infinity";
375   if (MathLimits<double>::IsNegInf(value)) return "-Infinity";
376   if (MathLimits<double>::IsNaN(value)) return "NaN";
377 
378   return SimpleDtoa(value);
379 }
380 
FloatAsString(float value)381 string FloatAsString(float value) {
382   if (MathLimits<float>::IsFinite(value)) return SimpleFtoa(value);
383   return DoubleAsString(value);
384 }
385 
SafeStrToFloat(StringPiece str,float * value)386 bool SafeStrToFloat(StringPiece str, float* value) {
387   double double_value;
388   if (!safe_strtod(str, &double_value)) {
389     return false;
390   }
391 
392   if (MathLimits<double>::IsInf(double_value) ||
393       MathLimits<double>::IsNaN(double_value))
394     return false;
395 
396   // Fail if the value is not representable in float.
397   if (double_value > std::numeric_limits<float>::max() ||
398       double_value < -std::numeric_limits<float>::max()) {
399     return false;
400   }
401 
402   *value = static_cast<float>(double_value);
403   return true;
404 }
405 
406 }  // namespace converter
407 }  // namespace util
408 }  // namespace protobuf
409 }  // namespace google
410