1 // Copyright 2017 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "testing/libfuzzer/proto/json_proto_converter.h" 6 7 namespace json_proto { 8 AppendArray(const ArrayValue & array_value)9void JsonProtoConverter::AppendArray(const ArrayValue& array_value) { 10 data_ << '['; 11 bool need_comma = false; 12 for (const auto& value : array_value.value()) { 13 // Trailing comma inside of an array makes JSON invalid, avoid adding that. 14 if (need_comma) 15 data_ << ','; 16 else 17 need_comma = true; 18 19 AppendValue(value); 20 } 21 data_ << ']'; 22 } 23 AppendNumber(const NumberValue & number_value)24void JsonProtoConverter::AppendNumber(const NumberValue& number_value) { 25 if (number_value.has_float_value()) { 26 data_ << number_value.float_value().value(); 27 } else if (number_value.has_exponent_value()) { 28 auto value = number_value.exponent_value(); 29 data_ << value.base(); 30 data_ << (value.use_uppercase() ? 'E' : 'e'); 31 data_ << value.exponent(); 32 } else if (number_value.has_exponent_frac_value()) { 33 auto value = number_value.exponent_value(); 34 data_ << value.base(); 35 data_ << (value.use_uppercase() ? 'E' : 'e'); 36 data_ << value.exponent(); 37 } else { 38 data_ << number_value.integer_value().value(); 39 } 40 } 41 AppendObject(const JsonObject & json_object)42void JsonProtoConverter::AppendObject(const JsonObject& json_object) { 43 data_ << '{'; 44 bool leading_comma = false; 45 for (const auto& field : json_object.field()) { 46 if (leading_comma) { 47 data_ << ","; 48 } 49 leading_comma = true; 50 data_ << '"' << field.name() << '"' << ':'; 51 AppendValue(field.value()); 52 } 53 data_ << '}'; 54 } 55 AppendValue(const JsonValue & json_value)56void JsonProtoConverter::AppendValue(const JsonValue& json_value) { 57 if (json_value.has_object_value()) { 58 AppendObject(json_value.object_value()); 59 } else if (json_value.has_array_value()) { 60 AppendArray(json_value.array_value()); 61 } else if (json_value.has_number_value()) { 62 AppendNumber(json_value.number_value()); 63 } else if (json_value.has_string_value()) { 64 data_ << '"' << json_value.string_value().value() << '"'; 65 } else if (json_value.has_boolean_value()) { 66 data_ << (json_value.boolean_value().value() ? "true" : "false"); 67 } else { 68 data_ << "null"; 69 } 70 } 71 Convert(const JsonValue & json_value)72std::string JsonProtoConverter::Convert(const JsonValue& json_value) { 73 AppendValue(json_value); 74 return data_.str(); 75 } 76 Convert(const JsonObject & json_object)77std::string JsonProtoConverter::Convert(const JsonObject& json_object) { 78 AppendObject(json_object); 79 return data_.str(); 80 } 81 Convert(const json_proto::ArrayValue & json_array)82std::string JsonProtoConverter::Convert( 83 const json_proto::ArrayValue& json_array) { 84 AppendArray(json_array); 85 return data_.str(); 86 } 87 88 } // namespace json_proto 89