1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "perfetto/test/traced_value_test_support.h"
18
19 #include "protos/perfetto/trace/track_event/debug_annotation.gen.h"
20 #include "protos/perfetto/trace/track_event/debug_annotation.pb.h"
21
22 #include <sstream>
23
24 namespace perfetto {
25
26 namespace internal {
27
28 namespace {
29
WriteAsJSON(const protos::DebugAnnotation & value,std::stringstream & ss)30 void WriteAsJSON(const protos::DebugAnnotation& value, std::stringstream& ss) {
31 if (value.has_bool_value()) {
32 if (value.bool_value()) {
33 ss << "true";
34 } else {
35 ss << "false";
36 }
37 } else if (value.has_uint_value()) {
38 ss << value.uint_value();
39 } else if (value.has_int_value()) {
40 ss << value.int_value();
41 } else if (value.has_double_value()) {
42 ss << value.double_value();
43 } else if (value.has_string_value()) {
44 ss << value.string_value();
45 } else if (value.has_pointer_value()) {
46 // Printing pointer values via ostream is really platform-specific, so do
47 // not try to convert it to void* before printing.
48 ss << "0x" << std::hex << value.pointer_value() << std::dec;
49 } else if (value.dict_entries_size() > 0) {
50 ss << "{";
51 for (int i = 0; i < value.dict_entries_size(); ++i) {
52 if (i > 0)
53 ss << ",";
54 auto item = value.dict_entries(i);
55 ss << item.name();
56 ss << ":";
57 WriteAsJSON(item, ss);
58 }
59 ss << "}";
60 } else if (value.array_values_size() > 0) {
61 ss << "[";
62 for (int i = 0; i < value.array_values_size(); ++i) {
63 auto item = value.array_values(i);
64 if (i > 0)
65 ss << ",";
66 WriteAsJSON(item, ss);
67 }
68 ss << "]";
69 } else {
70 ss << "{}";
71 }
72 }
73
74 } // namespace
75
DebugAnnotationToString(const std::string & data)76 std::string DebugAnnotationToString(const std::string& data) {
77 std::stringstream ss;
78 protos::DebugAnnotation result;
79 result.ParseFromString(data);
80 WriteAsJSON(result, ss);
81 return ss.str();
82 }
83
84 } // namespace internal
85 } // namespace perfetto
86