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