xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-cov/RenderingSupport.h (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1 //===- RenderingSupport.h - output stream rendering support functions  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_COV_RENDERINGSUPPORT_H
10 #define LLVM_COV_RENDERINGSUPPORT_H
11 
12 #include "llvm/Support/raw_ostream.h"
13 #include <utility>
14 
15 namespace llvm {
16 
17 /// A helper class that resets the output stream's color if needed
18 /// when destroyed.
19 class ColoredRawOstream {
20   ColoredRawOstream(const ColoredRawOstream &OS) = delete;
21 
22 public:
23   raw_ostream &OS;
24   bool IsColorUsed;
25 
26   ColoredRawOstream(raw_ostream &OS, bool IsColorUsed)
27       : OS(OS), IsColorUsed(IsColorUsed) {}
28 
29   ColoredRawOstream(ColoredRawOstream &&Other)
30       : OS(Other.OS), IsColorUsed(Other.IsColorUsed) {
31     // Reset the other IsColorUsed so that the other object won't reset the
32     // color when destroyed.
33     Other.IsColorUsed = false;
34   }
35 
36   ~ColoredRawOstream() {
37     if (IsColorUsed)
38       OS.resetColor();
39   }
40 };
41 
42 template <typename T>
43 inline raw_ostream &operator<<(const ColoredRawOstream &OS, T &&Value) {
44   return OS.OS << std::forward<T>(Value);
45 }
46 
47 /// Change the color of the output stream if the `IsColorUsed` flag
48 /// is true. Returns an object that resets the color when destroyed.
49 inline ColoredRawOstream colored_ostream(raw_ostream &OS,
50                                          raw_ostream::Colors Color,
51                                          bool IsColorUsed = true,
52                                          bool Bold = false, bool BG = false) {
53   if (IsColorUsed)
54     OS.changeColor(Color, Bold, BG);
55   return ColoredRawOstream(OS, IsColorUsed);
56 }
57 
58 } // namespace llvm
59 
60 #endif // LLVM_COV_RENDERINGSUPPORT_H
61