blob: 55f730b28705833d0762c710798fda7ea46f50dc [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>
Prabir Pradhanc13ff082022-09-08 22:03:30 +000020#include <optional>
Siarhei Vishniakoua6a660f2022-03-04 15:12:16 -080021#include <set>
22#include <string>
23
24namespace android {
25
26template <typename T>
27std::string constToString(const T& v) {
28 return std::to_string(v);
29}
30
31/**
Prabir Pradhanc13ff082022-09-08 22:03:30 +000032 * Convert an optional type to string.
33 */
34template <typename T>
35std::string toString(const std::optional<T>& optional,
36 std::string (*toString)(const T&) = constToString) {
37 return optional ? toString(*optional) : "<not set>";
38}
39
40/**
Siarhei Vishniakoua6a660f2022-03-04 15:12:16 -080041 * Convert a set of integral types to string.
42 */
43template <typename T>
44std::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 */
56template <typename K, typename V>
57std::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
69const char* toString(bool value);
70
Siarhei Vishniakou9f330c52022-05-17 05:03:42 -070071/**
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 */
78std::string addLinePrefix(std::string str, const std::string& prefix);
79
Siarhei Vishniakoua6a660f2022-03-04 15:12:16 -080080} // namespace android