xref: /aosp_15_r20/external/perfetto/src/trace_processor/importers/json/json_utils.h (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2020 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 #ifndef SRC_TRACE_PROCESSOR_IMPORTERS_JSON_JSON_UTILS_H_
18 #define SRC_TRACE_PROCESSOR_IMPORTERS_JSON_JSON_UTILS_H_
19 
20 #include <cstdint>
21 #include <optional>
22 #include <string>
23 
24 #include "perfetto/base/build_config.h"
25 #include "perfetto/ext/base/string_view.h"
26 #include "src/trace_processor/importers/common/args_tracker.h"
27 #include "src/trace_processor/storage/trace_storage.h"
28 
29 #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON)
30 #include <json/value.h>
31 #else
32 namespace Json {
33 class Value {};
34 }  // namespace Json
35 #endif
36 
37 namespace perfetto::trace_processor::json {
38 
39 // Returns whether JSON related functioanlity is supported with the current
40 // build flags.
IsJsonSupported()41 constexpr bool IsJsonSupported() {
42 #if PERFETTO_BUILDFLAG(PERFETTO_TP_JSON)
43   return true;
44 #else
45   return false;
46 #endif
47 }
48 
49 std::optional<int64_t> CoerceToTs(const Json::Value& value);
50 std::optional<int64_t> CoerceToTs(const std::string& value);
51 std::optional<int64_t> CoerceToInt64(const Json::Value& value);
52 std::optional<uint32_t> CoerceToUint32(const Json::Value& value);
53 
54 // Parses the given JSON string into a JSON::Value object.
55 // This function should only be called if |IsJsonSupported()| returns true.
56 std::optional<Json::Value> ParseJsonString(base::StringView raw_string);
57 
58 // Flattens the given Json::Value and adds each leaf node to the bound args
59 // inserter. Note:
60 //  * |flat_key| and |key| should be non-empty and will be used to prefix the
61 //    keys of all leaf nodes in the JSON.
62 //  * |storage| is used to intern all strings (e.g. keys and values).
63 //  * This function should only be called if |IsJsonSupported()| returns true.
64 bool AddJsonValueToArgs(const Json::Value& value,
65                         base::StringView flat_key,
66                         base::StringView key,
67                         TraceStorage* storage,
68                         ArgsTracker::BoundInserter* inserter);
69 
70 }  // namespace perfetto::trace_processor::json
71 
72 #endif  // SRC_TRACE_PROCESSOR_IMPORTERS_JSON_JSON_UTILS_H_
73