RenderingSupport.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #ifndef LLVM_COV_RENDERINGSUPPORT_H
  9. #define LLVM_COV_RENDERINGSUPPORT_H
  10. #include "llvm/Support/raw_ostream.h"
  11. #include <utility>
  12. namespace llvm {
  13. /// A helper class that resets the output stream's color if needed
  14. /// when destroyed.
  15. class ColoredRawOstream {
  16. ColoredRawOstream(const ColoredRawOstream &OS) = delete;
  17. public:
  18. raw_ostream &OS;
  19. bool IsColorUsed;
  20. ColoredRawOstream(raw_ostream &OS, bool IsColorUsed)
  21. : OS(OS), IsColorUsed(IsColorUsed) {}
  22. ColoredRawOstream(ColoredRawOstream &&Other)
  23. : OS(Other.OS), IsColorUsed(Other.IsColorUsed) {
  24. // Reset the other IsColorUsed so that the other object won't reset the
  25. // color when destroyed.
  26. Other.IsColorUsed = false;
  27. }
  28. ~ColoredRawOstream() {
  29. if (IsColorUsed)
  30. OS.resetColor();
  31. }
  32. };
  33. template <typename T>
  34. inline raw_ostream &operator<<(const ColoredRawOstream &OS, T &&Value) {
  35. return OS.OS << std::forward<T>(Value);
  36. }
  37. /// Change the color of the output stream if the `IsColorUsed` flag
  38. /// is true. Returns an object that resets the color when destroyed.
  39. inline ColoredRawOstream colored_ostream(raw_ostream &OS,
  40. raw_ostream::Colors Color,
  41. bool IsColorUsed = true,
  42. bool Bold = false, bool BG = false) {
  43. if (IsColorUsed)
  44. OS.changeColor(Color, Bold, BG);
  45. return ColoredRawOstream(OS, IsColorUsed);
  46. }
  47. } // namespace llvm
  48. #endif // LLVM_COV_RENDERINGSUPPORT_H