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