• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 <optional>
21 #include <set>
22 #include <string>
23 
24 namespace android {
25 
26 template <typename T>
constToString(const T & v)27 std::string constToString(const T& v) {
28     return std::to_string(v);
29 }
30 
31 /**
32  * Convert an optional type to string.
33  */
34 template <typename T>
35 std::string toString(const std::optional<T>& optional,
36                      std::string (*toString)(const T&) = constToString) {
37     return optional ? toString(*optional) : "<not set>";
38 }
39 
40 /**
41  * Convert a set of integral types to string.
42  */
43 template <typename T>
44 std::string dumpSet(const std::set<T>& v, std::string (*toString)(const T&) = constToString) {
45     std::string out;
46     for (const T& entry : v) {
47         out += out.empty() ? "{" : ", ";
48         out += toString(entry);
49     }
50     return out.empty() ? "{}" : (out + "}");
51 }
52 
53 /**
54  * Convert a map to string. Both keys and values of the map should be integral type.
55  */
56 template <typename K, typename V>
57 std::string dumpMap(const std::map<K, V>& map, std::string (*keyToString)(const K&) = constToString,
58                     std::string (*valueToString)(const V&) = constToString) {
59     std::string out;
60     for (const auto& [k, v] : map) {
61         if (!out.empty()) {
62             out += "\n";
63         }
64         out += keyToString(k) + ":" + valueToString(v);
65     }
66     return out;
67 }
68 
69 const char* toString(bool value);
70 
71 /**
72  * Add "prefix" to the beginning of each line in the provided string
73  * "str".
74  * The string 'str' is typically multi-line.
75  * The most common use case for this function is to add some padding
76  * when dumping state.
77  */
78 std::string addLinePrefix(std::string str, const std::string& prefix);
79 
80 } // namespace android