blob: 0a7527849466d84e55466088b9204137a5a8ac06 [file] [log] [blame]
Siarhei Vishniakoua6a660f2022-03-04 15:12:16 -08001/*
2 * Copyright (C) 2022 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#pragma once
18
19#include <map>
20#include <set>
21#include <string>
22
23namespace android {
24
25template <typename T>
26std::string constToString(const T& v) {
27 return std::to_string(v);
28}
29
30/**
31 * Convert a set of integral types to string.
32 */
33template <typename T>
34std::string dumpSet(const std::set<T>& v, std::string (*toString)(const T&) = constToString) {
35 std::string out;
36 for (const T& entry : v) {
37 out += out.empty() ? "{" : ", ";
38 out += toString(entry);
39 }
40 return out.empty() ? "{}" : (out + "}");
41}
42
43/**
44 * Convert a map to string. Both keys and values of the map should be integral type.
45 */
46template <typename K, typename V>
47std::string dumpMap(const std::map<K, V>& map, std::string (*keyToString)(const K&) = constToString,
48 std::string (*valueToString)(const V&) = constToString) {
49 std::string out;
50 for (const auto& [k, v] : map) {
51 if (!out.empty()) {
52 out += "\n";
53 }
54 out += keyToString(k) + ":" + valueToString(v);
55 }
56 return out;
57}
58
59const char* toString(bool value);
60
Siarhei Vishniakou9f330c52022-05-17 05:03:42 -070061/**
62 * Add "prefix" to the beginning of each line in the provided string
63 * "str".
64 * The string 'str' is typically multi-line.
65 * The most common use case for this function is to add some padding
66 * when dumping state.
67 */
68std::string addLinePrefix(std::string str, const std::string& prefix);
69
Siarhei Vishniakoua6a660f2022-03-04 15:12:16 -080070} // namespace android