Dominik Laskowski | e70461a | 2022-08-30 14:42:01 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 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 <optional> |
| 20 | #include <string> |
| 21 | #include <string_view> |
| 22 | |
| 23 | namespace android::utils { |
| 24 | |
| 25 | // Dumps variables by appending their name and value to the output string. A variable is formatted |
| 26 | // as "name=value". If the name or value is empty, the format is "value" or "name=", respectively. |
| 27 | // A value of user-defined type T is stringified via `std::string to_string(const T&)`, which must |
| 28 | // be defined in the same namespace as T per the rules of ADL (argument-dependent lookup). |
| 29 | // |
| 30 | // TODO(b/249828573): Consolidate with <compositionengine/impl/DumpHelpers.h> |
| 31 | class Dumper { |
| 32 | public: |
| 33 | explicit Dumper(std::string& out) : mOut(out) {} |
| 34 | |
| 35 | void eol() { mOut += '\n'; } |
| 36 | |
| 37 | void dump(std::string_view name, std::string_view value = {}) { |
| 38 | using namespace std::string_view_literals; |
| 39 | |
| 40 | for (int i = mIndent; i-- > 0;) mOut += " "sv; |
| 41 | mOut += name; |
| 42 | if (!name.empty()) mOut += '='; |
| 43 | mOut += value; |
| 44 | eol(); |
| 45 | } |
| 46 | |
| 47 | void dump(std::string_view name, bool value) { |
| 48 | using namespace std::string_view_literals; |
| 49 | dump(name, value ? "true"sv : "false"sv); |
| 50 | } |
| 51 | |
| 52 | template <typename T> |
| 53 | void dump(std::string_view name, const std::optional<T>& value) { |
| 54 | using namespace std::string_view_literals; |
| 55 | using std::to_string; |
| 56 | dump(name, value ? to_string(*value) : "nullopt"sv); |
| 57 | } |
| 58 | |
| 59 | struct Indent { |
| 60 | explicit Indent(Dumper& dumper) : dumper(dumper) { dumper.mIndent++; } |
| 61 | ~Indent() { dumper.mIndent--; } |
| 62 | |
| 63 | Dumper& dumper; |
| 64 | }; |
| 65 | |
| 66 | private: |
| 67 | std::string& mOut; |
| 68 | int mIndent = 0; |
| 69 | }; |
| 70 | |
| 71 | } // namespace android::utils |