format.hh 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // -*- mode: c++; coding: utf-8 -*-
  2. /// @file format.hh
  3. /// @brief Array output formatting, with some generic ostream sugar.
  4. // (c) Daniel Llorens - 2010, 2016-2018
  5. // This library is free software; you can redistribute it and/or modify it under
  6. // the terms of the GNU General Public License as published by the Free
  7. // Software Foundation; either version 3 of the License, or (at your option) any
  8. // later version.
  9. #pragma once
  10. #include <iterator>
  11. #include <iosfwd>
  12. #include <sstream>
  13. namespace ra {
  14. constexpr char const * esc_bold = "\x1b[01m";
  15. constexpr char const * esc_unbold = "\x1b[0m";
  16. constexpr char const * esc_red = "\x1b[31m";
  17. constexpr char const * esc_green = "\x1b[32m";
  18. constexpr char const * esc_cyan = "\x1b[36m";
  19. constexpr char const * esc_yellow = "\x1b[33m";
  20. constexpr char const * esc_blue = "\x1b[34m";
  21. constexpr char const * esc_white = "\x1b[97m"; // an AIXTERM sequence
  22. constexpr char const * esc_plain = "\x1b[39m";
  23. constexpr char const * esc_reset = "\x1b[39m\x1b[0m"; // plain + unbold
  24. constexpr char const * esc_pink = "\x1b[38;5;225m";
  25. template <class ... A> inline std::string
  26. format(A && ... a)
  27. {
  28. std::ostringstream o; (o << ... << a); return o.str();
  29. }
  30. inline std::string const & format(std::string const & s) { return s; }
  31. enum print_shape_t { defaultshape, withshape, noshape };
  32. template <class A>
  33. struct FormatArray
  34. {
  35. A const & a;
  36. print_shape_t shape;
  37. char const * sep0;
  38. char const * sep1;
  39. char const * sep2;
  40. };
  41. template <class A> inline
  42. FormatArray<A>
  43. format_array(A const & a, char const * sep0=" ", char const * sep1="\n", char const * sep2="\n")
  44. {
  45. return FormatArray<A> { a, defaultshape, sep0, sep1, sep2 };
  46. }
  47. struct shape_manip_t
  48. {
  49. std::ostream & o;
  50. print_shape_t shape;
  51. };
  52. inline shape_manip_t operator<<(std::ostream & o, print_shape_t shape)
  53. {
  54. return shape_manip_t { o, shape };
  55. }
  56. template <class A>
  57. inline std::ostream & operator<<(shape_manip_t const & sm, A const & a)
  58. {
  59. FormatArray<A> fa = format_array(a);
  60. fa.shape = sm.shape;
  61. return sm.o << fa;
  62. }
  63. template <class A>
  64. inline std::ostream & operator<<(shape_manip_t const & sm, FormatArray<A> fa)
  65. {
  66. fa.shape = sm.shape;
  67. return sm.o << fa;
  68. }
  69. } // namespace ra