format.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. #pragma once
  2. #include "mem.h"
  3. #include "output.h"
  4. #include <util/datetime/base.h>
  5. #include <util/generic/strbuf.h>
  6. #include <util/generic/flags.h>
  7. #include <util/memory/tempbuf.h>
  8. #include <util/string/cast.h>
  9. enum ENumberFormatFlag {
  10. HF_FULL = 0x01, /**< Output number with leading zeros. */
  11. HF_ADDX = 0x02, /**< Output '0x' or '0b' before hex/bin digits. */
  12. };
  13. Y_DECLARE_FLAGS(ENumberFormat, ENumberFormatFlag);
  14. Y_DECLARE_OPERATORS_FOR_FLAGS(ENumberFormat);
  15. enum ESizeFormat {
  16. SF_QUANTITY, /**< Base 1000, usual suffixes. 1100 gets turned into "1.1K". */
  17. SF_BYTES, /**< Base 1024, byte suffix. 1100 gets turned into "1.07KiB". */
  18. };
  19. namespace NFormatPrivate {
  20. template <size_t Value>
  21. struct TLog2: std::integral_constant<size_t, TLog2<Value / 2>::value + 1> {};
  22. template <>
  23. struct TLog2<1>: std::integral_constant<size_t, 0> {};
  24. template <typename T>
  25. inline void StreamWrite(T& stream, const char* s, size_t size) {
  26. stream.write(s, size);
  27. }
  28. template <>
  29. inline void StreamWrite(IOutputStream& stream, const char* s, size_t size) {
  30. stream.Write(s, size);
  31. }
  32. template <>
  33. inline void StreamWrite(TStringStream& stream, const char* s, size_t size) {
  34. stream.Write(s, size);
  35. }
  36. template <typename T>
  37. static inline void WriteChars(T& os, char c, size_t count) {
  38. if (count == 0)
  39. return;
  40. TTempBuf buf(count);
  41. memset(buf.Data(), c, count);
  42. StreamWrite(os, buf.Data(), count);
  43. }
  44. template <typename T>
  45. struct TLeftPad {
  46. T Value;
  47. size_t Width;
  48. char Padc;
  49. inline TLeftPad(const T& value, size_t width, char padc)
  50. : Value(value)
  51. , Width(width)
  52. , Padc(padc)
  53. {
  54. }
  55. };
  56. template <typename T>
  57. IOutputStream& operator<<(IOutputStream& o, const TLeftPad<T>& lp) {
  58. TTempBuf buf;
  59. TMemoryOutput ss(buf.Data(), buf.Size());
  60. ss << lp.Value;
  61. size_t written = buf.Size() - ss.Avail();
  62. if (lp.Width > written) {
  63. WriteChars(o, lp.Padc, lp.Width - written);
  64. }
  65. o.Write(buf.Data(), written);
  66. return o;
  67. }
  68. template <typename T>
  69. struct TRightPad {
  70. T Value;
  71. size_t Width;
  72. char Padc;
  73. inline TRightPad(const T& value, size_t width, char padc)
  74. : Value(value)
  75. , Width(width)
  76. , Padc(padc)
  77. {
  78. }
  79. };
  80. template <typename T>
  81. IOutputStream& operator<<(IOutputStream& o, const TRightPad<T>& lp) {
  82. TTempBuf buf;
  83. TMemoryOutput ss(buf.Data(), buf.Size());
  84. ss << lp.Value;
  85. size_t written = buf.Size() - ss.Avail();
  86. o.Write(buf.Data(), written);
  87. if (lp.Width > written) {
  88. WriteChars(o, lp.Padc, lp.Width - written);
  89. }
  90. return o;
  91. }
  92. template <typename T, size_t Base>
  93. struct TBaseNumber {
  94. T Value;
  95. ENumberFormat Flags;
  96. template <typename OtherT>
  97. inline TBaseNumber(OtherT value, ENumberFormat flags)
  98. : Value(value)
  99. , Flags(flags)
  100. {
  101. }
  102. };
  103. template <typename T, size_t Base>
  104. using TUnsignedBaseNumber = TBaseNumber<std::make_unsigned_t<std::remove_cv_t<T>>, Base>;
  105. template <typename TStream, typename T, size_t Base>
  106. TStream& ToStreamImpl(TStream& stream, const TBaseNumber<T, Base>& value) {
  107. char buf[8 * sizeof(T) + 1]; /* Add 1 for sign. */
  108. TStringBuf str(buf, IntToString<Base>(value.Value, buf, sizeof(buf)));
  109. if (str[0] == '-') {
  110. stream << '-';
  111. str.Skip(1);
  112. }
  113. if (value.Flags & HF_ADDX) {
  114. if (Base == 16) {
  115. stream << TStringBuf("0x");
  116. } else if (Base == 2) {
  117. stream << TStringBuf("0b");
  118. }
  119. }
  120. if (value.Flags & HF_FULL) {
  121. WriteChars(stream, '0', (8 * sizeof(T) + TLog2<Base>::value - 1) / TLog2<Base>::value - str.size());
  122. }
  123. stream << str;
  124. return stream;
  125. }
  126. template <typename T, size_t Base>
  127. IOutputStream& operator<<(IOutputStream& stream, const TBaseNumber<T, Base>& value) {
  128. return ToStreamImpl(stream, value);
  129. }
  130. template <typename T, size_t Base>
  131. std::ostream& operator<<(std::ostream& stream, const TBaseNumber<T, Base>& value) {
  132. return ToStreamImpl(stream, value);
  133. }
  134. template <typename Char, size_t Base>
  135. struct TBaseText {
  136. TBasicStringBuf<Char> Text;
  137. inline TBaseText(const TBasicStringBuf<Char> text)
  138. : Text(text)
  139. {
  140. }
  141. };
  142. template <typename Char, size_t Base>
  143. IOutputStream& operator<<(IOutputStream& os, const TBaseText<Char, Base>& text) {
  144. for (size_t i = 0; i < text.Text.size(); ++i) {
  145. if (i != 0) {
  146. os << ' ';
  147. }
  148. os << TUnsignedBaseNumber<Char, Base>(text.Text[i], HF_FULL);
  149. }
  150. return os;
  151. }
  152. template <typename T>
  153. struct TFloatPrecision {
  154. using TdVal = std::remove_cv_t<T>;
  155. static_assert(std::is_floating_point<TdVal>::value, "expect std::is_floating_point<TdVal>::value");
  156. TdVal Value;
  157. EFloatToStringMode Mode;
  158. int NDigits;
  159. };
  160. template <typename T>
  161. IOutputStream& operator<<(IOutputStream& o, const TFloatPrecision<T>& prec) {
  162. char buf[512];
  163. size_t count = FloatToString(prec.Value, buf, sizeof(buf), prec.Mode, prec.NDigits);
  164. o << TStringBuf(buf, count);
  165. return o;
  166. }
  167. struct THumanReadableDuration {
  168. TDuration Value;
  169. constexpr THumanReadableDuration(const TDuration& value)
  170. : Value(value)
  171. {
  172. }
  173. };
  174. struct THumanReadableSize {
  175. double Value;
  176. ESizeFormat Format;
  177. };
  178. }
  179. /**
  180. * Output manipulator basically equivalent to `std::setw` and `std::setfill`
  181. * combined.
  182. *
  183. * When written into a `IOutputStream`, writes out padding characters first,
  184. * and then provided value.
  185. *
  186. * Example usage:
  187. * @code
  188. * stream << LeftPad(12345, 10, '0'); // Will output "0000012345"
  189. * @endcode
  190. *
  191. * @param value Value to output.
  192. * @param width Target total width.
  193. * @param padc Character to use for padding.
  194. * @see RightPad
  195. */
  196. template <typename T>
  197. static constexpr ::NFormatPrivate::TLeftPad<T> LeftPad(const T& value, const size_t width, const char padc = ' ') noexcept {
  198. return ::NFormatPrivate::TLeftPad<T>(value, width, padc);
  199. }
  200. template <typename T, int N>
  201. static constexpr ::NFormatPrivate::TLeftPad<const T*> LeftPad(const T (&value)[N], const size_t width, const char padc = ' ') noexcept {
  202. return ::NFormatPrivate::TLeftPad<const T*>(value, width, padc);
  203. }
  204. /**
  205. * Output manipulator similar to `std::setw` and `std::setfill`.
  206. *
  207. * When written into a `IOutputStream`, writes provided value first, and then
  208. * the padding characters.
  209. *
  210. * Example usage:
  211. * @code
  212. * stream << RightPad("column1", 10, ' '); // Will output "column1 "
  213. * @endcode
  214. *
  215. * @param value Value to output.
  216. * @param width Target total width.
  217. * @param padc Character to use for padding.
  218. * @see LeftPad
  219. */
  220. template <typename T>
  221. static constexpr ::NFormatPrivate::TRightPad<T> RightPad(const T& value, const size_t width, const char padc = ' ') noexcept {
  222. return ::NFormatPrivate::TRightPad<T>(value, width, padc);
  223. }
  224. template <typename T, int N>
  225. static constexpr ::NFormatPrivate::TRightPad<const T*> RightPad(const T (&value)[N], const size_t width, const char padc = ' ') noexcept {
  226. return ::NFormatPrivate::TRightPad<const T*>(value, width, padc);
  227. }
  228. /**
  229. * Output manipulator similar to `std::setbase(16)`.
  230. *
  231. * When written into a `IOutputStream`, writes out the provided value in
  232. * hexadecimal form. The value is treated as unsigned, even if its type is in
  233. * fact signed.
  234. *
  235. * Example usage:
  236. * @code
  237. * stream << Hex(-1); // Will output "0xFFFFFFFF"
  238. * stream << Hex(1ull); // Will output "0x0000000000000001"
  239. * @endcode
  240. *
  241. * @param value Value to output.
  242. * @param flags Output flags.
  243. */
  244. template <typename T>
  245. static constexpr ::NFormatPrivate::TUnsignedBaseNumber<T, 16> Hex(const T& value, const ENumberFormat flags = HF_FULL | HF_ADDX) noexcept {
  246. return {value, flags};
  247. }
  248. /**
  249. * Output manipulator similar to `std::setbase(16)`.
  250. *
  251. * When written into a `IOutputStream`, writes out the provided value in
  252. * hexadecimal form.
  253. *
  254. * Example usage:
  255. * @code
  256. * stream << SHex(-1); // Will output "-0x00000001"
  257. * stream << SHex(1ull); // Will output "0x0000000000000001"
  258. * @endcode
  259. *
  260. * @param value Value to output.
  261. * @param flags Output flags.
  262. */
  263. template <typename T>
  264. static constexpr ::NFormatPrivate::TBaseNumber<T, 16> SHex(const T& value, const ENumberFormat flags = HF_FULL | HF_ADDX) noexcept {
  265. return {value, flags};
  266. }
  267. /**
  268. * Output manipulator similar to `std::setbase(2)`.
  269. *
  270. * When written into a `IOutputStream`, writes out the provided value in
  271. * binary form. The value is treated as unsigned, even if its type is in
  272. * fact signed.
  273. *
  274. * Example usage:
  275. * @code
  276. * stream << Bin(-1); // Will output "0b11111111111111111111111111111111"
  277. * stream << Bin(1); // Will output "0b00000000000000000000000000000001"
  278. * @endcode
  279. *
  280. * @param value Value to output.
  281. * @param flags Output flags.
  282. */
  283. template <typename T>
  284. static constexpr ::NFormatPrivate::TUnsignedBaseNumber<T, 2> Bin(const T& value, const ENumberFormat flags = HF_FULL | HF_ADDX) noexcept {
  285. return {value, flags};
  286. }
  287. /**
  288. * Output manipulator similar to `std::setbase(2)`.
  289. *
  290. * When written into a `IOutputStream`, writes out the provided value in
  291. * binary form.
  292. *
  293. * Example usage:
  294. * @code
  295. * stream << SBin(-1); // Will output "-0b00000000000000000000000000000001"
  296. * stream << SBin(1); // Will output "0b00000000000000000000000000000001"
  297. * @endcode
  298. *
  299. * @param value Value to output.
  300. * @param flags Output flags.
  301. */
  302. template <typename T>
  303. static constexpr ::NFormatPrivate::TBaseNumber<T, 2> SBin(const T& value, const ENumberFormat flags = HF_FULL | HF_ADDX) noexcept {
  304. return {value, flags};
  305. }
  306. /**
  307. * Output manipulator for hexadecimal string output.
  308. *
  309. * When written into a `IOutputStream`, writes out the provided characters
  310. * in hexadecimal form divided by space character.
  311. *
  312. * Example usage:
  313. * @code
  314. * stream << HexText(TStringBuf("abcи")); // Will output "61 62 63 D0 B8"
  315. * stream << HexText(TWtringBuf(u"abcи")); // Will output "0061 0062 0063 0438"
  316. * @endcode
  317. *
  318. * @param value String to output.
  319. */
  320. template <typename TChar>
  321. static inline ::NFormatPrivate::TBaseText<TChar, 16> HexText(const TBasicStringBuf<TChar> value) {
  322. return ::NFormatPrivate::TBaseText<TChar, 16>(value);
  323. }
  324. /**
  325. * Output manipulator for binary string output.
  326. *
  327. * When written into a `IOutputStream`, writes out the provided characters
  328. * in binary form divided by space character.
  329. *
  330. * Example usage:
  331. * @code
  332. * stream << BinText(TStringBuf("aaa")); // Will output "01100001 01100001 01100001"
  333. * @endcode
  334. *
  335. * @param value String to output.
  336. */
  337. template <typename TChar>
  338. static inline ::NFormatPrivate::TBaseText<TChar, 2> BinText(const TBasicStringBuf<TChar> value) {
  339. return ::NFormatPrivate::TBaseText<TChar, 2>(value);
  340. }
  341. /**
  342. * Output manipulator for printing `TDuration` values.
  343. *
  344. * When written into a `IOutputStream`, writes out the provided `TDuration`
  345. * in auto-adjusted human-readable format.
  346. *
  347. * Example usage:
  348. * @code
  349. * stream << HumanReadable(TDuration::MicroSeconds(100)); // Will output "100us"
  350. * stream << HumanReadable(TDuration::Seconds(3672)); // Will output "1h 1m 12s"
  351. * @endcode
  352. *
  353. * @param value Value to output.
  354. */
  355. static constexpr ::NFormatPrivate::THumanReadableDuration HumanReadable(const TDuration duration) noexcept {
  356. return ::NFormatPrivate::THumanReadableDuration(duration);
  357. }
  358. /**
  359. * Output manipulator for writing out human-readable number of elements / memory
  360. * amount in `ls -h` style.
  361. *
  362. * When written into a `IOutputStream`, writes out the provided unsigned integer
  363. * variable with small precision and a suffix (like 'K', 'M', 'G' for numbers, or
  364. * 'B', 'KiB', 'MiB', 'GiB' for bytes).
  365. *
  366. * For quantities, base 1000 is used. For bytes, base is 1024.
  367. *
  368. * Example usage:
  369. * @code
  370. * stream << HumanReadableSize(1024, SF_QUANTITY); // Will output "1.02K"
  371. * stream << HumanReadableSize(1024, SF_BYTES); // Will output "1KiB"
  372. * stream << "average usage " << HumanReadableSize(100 / 3., SF_BYTES); // Will output "average usage "33.3B""
  373. * @endcode
  374. *
  375. * @param value Value to output.
  376. * @param format Format to use.
  377. */
  378. static constexpr ::NFormatPrivate::THumanReadableSize HumanReadableSize(const double size, ESizeFormat format) noexcept {
  379. return {size, format};
  380. }
  381. void Time(IOutputStream& l);
  382. void TimeHumanReadable(IOutputStream& l);
  383. /**
  384. * Output manipulator for adjusting precision of floating point values.
  385. *
  386. * When written into a `IOutputStream`, writes out the provided floating point
  387. * variable with given precision. The behavior depends on provided `mode`.
  388. *
  389. * Example usage:
  390. * @code
  391. * stream << Prec(1.2345678901234567, PREC_AUTO); // Will output "1.2345678901234567"
  392. * @endcode
  393. *
  394. * @param value float or double to output.
  395. * @param mode Output mode.
  396. * @param ndigits Number of significant digits (in `PREC_NDIGITS` and `PREC_POINT_DIGITS` mode).
  397. * @see EFloatToStringMode
  398. */
  399. template <typename T>
  400. static constexpr ::NFormatPrivate::TFloatPrecision<T> Prec(const T& value, const EFloatToStringMode mode, const int ndigits = 0) noexcept {
  401. return {value, mode, ndigits};
  402. }
  403. /**
  404. * Output manipulator for adjusting precision of floating point values.
  405. *
  406. * When written into a `IOutputStream`, writes out the provided floating point
  407. * variable with given precision. The behavior is equivalent to `Prec(value, PREC_NDIGITS, ndigits)`.
  408. *
  409. * Example usage:
  410. * @code
  411. * stream << Prec(1.2345678901234567, 3); // Will output "1.23"
  412. * @endcode
  413. *
  414. * @param value float or double to output.
  415. * @param ndigits Number of significant digits.
  416. */
  417. template <typename T>
  418. static constexpr ::NFormatPrivate::TFloatPrecision<T> Prec(const T& value, const int ndigits) noexcept {
  419. return {value, PREC_NDIGITS, ndigits};
  420. }