Home | History | Annotate | Download | only in Support
      1 //===- Format.h - Efficient printf-style formatting for streams -*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the format() function, which can be used with other
     11 // LLVM subsystems to provide printf-style formatting.  This gives all the power
     12 // and risk of printf.  This can be used like this (with raw_ostreams as an
     13 // example):
     14 //
     15 //    OS << "mynumber: " << format("%4.5f", 1234.412) << '\n';
     16 //
     17 // Or if you prefer:
     18 //
     19 //  OS << format("mynumber: %4.5f\n", 1234.412);
     20 //
     21 //===----------------------------------------------------------------------===//
     22 
     23 #ifndef LLVM_SUPPORT_FORMAT_H
     24 #define LLVM_SUPPORT_FORMAT_H
     25 
     26 #include "llvm/ADT/STLExtras.h"
     27 #include "llvm/ADT/StringRef.h"
     28 #include "llvm/Support/DataTypes.h"
     29 #include <cassert>
     30 #include <cstdio>
     31 #include <tuple>
     32 
     33 namespace llvm {
     34 
     35 /// This is a helper class used for handling formatted output.  It is the
     36 /// abstract base class of a templated derived class.
     37 class format_object_base {
     38 protected:
     39   const char *Fmt;
     40   ~format_object_base() = default; // Disallow polymorphic deletion.
     41   format_object_base(const format_object_base &) = default;
     42   virtual void home(); // Out of line virtual method.
     43 
     44   /// Call snprintf() for this object, on the given buffer and size.
     45   virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
     46 
     47 public:
     48   format_object_base(const char *fmt) : Fmt(fmt) {}
     49 
     50   /// Format the object into the specified buffer.  On success, this returns
     51   /// the length of the formatted string.  If the buffer is too small, this
     52   /// returns a length to retry with, which will be larger than BufferSize.
     53   unsigned print(char *Buffer, unsigned BufferSize) const {
     54     assert(BufferSize && "Invalid buffer size!");
     55 
     56     // Print the string, leaving room for the terminating null.
     57     int N = snprint(Buffer, BufferSize);
     58 
     59     // VC++ and old GlibC return negative on overflow, just double the size.
     60     if (N < 0)
     61       return BufferSize * 2;
     62 
     63     // Other implementations yield number of bytes needed, not including the
     64     // final '\0'.
     65     if (unsigned(N) >= BufferSize)
     66       return N + 1;
     67 
     68     // Otherwise N is the length of output (not including the final '\0').
     69     return N;
     70   }
     71 };
     72 
     73 /// These are templated helper classes used by the format function that
     74 /// capture the object to be formated and the format string. When actually
     75 /// printed, this synthesizes the string into a temporary buffer provided and
     76 /// returns whether or not it is big enough.
     77 
     78 template <typename... Ts>
     79 class format_object final : public format_object_base {
     80   std::tuple<Ts...> Vals;
     81 
     82   template <std::size_t... Is>
     83   int snprint_tuple(char *Buffer, unsigned BufferSize,
     84                     index_sequence<Is...>) const {
     85 #ifdef _MSC_VER
     86     return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
     87 #else
     88     return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
     89 #endif
     90   }
     91 
     92 public:
     93   format_object(const char *fmt, const Ts &... vals)
     94       : format_object_base(fmt), Vals(vals...) {}
     95 
     96   int snprint(char *Buffer, unsigned BufferSize) const override {
     97     return snprint_tuple(Buffer, BufferSize, index_sequence_for<Ts...>());
     98   }
     99 };
    100 
    101 /// These are helper functions used to produce formatted output.  They use
    102 /// template type deduction to construct the appropriate instance of the
    103 /// format_object class to simplify their construction.
    104 ///
    105 /// This is typically used like:
    106 /// \code
    107 ///   OS << format("%0.4f", myfloat) << '\n';
    108 /// \endcode
    109 
    110 template <typename... Ts>
    111 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
    112   return format_object<Ts...>(Fmt, Vals...);
    113 }
    114 
    115 /// This is a helper class used for left_justify() and right_justify().
    116 class FormattedString {
    117   StringRef Str;
    118   unsigned Width;
    119   bool RightJustify;
    120   friend class raw_ostream;
    121 
    122 public:
    123     FormattedString(StringRef S, unsigned W, bool R)
    124       : Str(S), Width(W), RightJustify(R) { }
    125 };
    126 
    127 /// left_justify - append spaces after string so total output is
    128 /// \p Width characters.  If \p Str is larger that \p Width, full string
    129 /// is written with no padding.
    130 inline FormattedString left_justify(StringRef Str, unsigned Width) {
    131   return FormattedString(Str, Width, false);
    132 }
    133 
    134 /// right_justify - add spaces before string so total output is
    135 /// \p Width characters.  If \p Str is larger that \p Width, full string
    136 /// is written with no padding.
    137 inline FormattedString right_justify(StringRef Str, unsigned Width) {
    138   return FormattedString(Str, Width, true);
    139 }
    140 
    141 /// This is a helper class used for format_hex() and format_decimal().
    142 class FormattedNumber {
    143   uint64_t HexValue;
    144   int64_t DecValue;
    145   unsigned Width;
    146   bool Hex;
    147   bool Upper;
    148   bool HexPrefix;
    149   friend class raw_ostream;
    150 
    151 public:
    152   FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
    153                   bool Prefix)
    154       : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
    155         HexPrefix(Prefix) {}
    156 };
    157 
    158 /// format_hex - Output \p N as a fixed width hexadecimal. If number will not
    159 /// fit in width, full number is still printed.  Examples:
    160 ///   OS << format_hex(255, 4)              => 0xff
    161 ///   OS << format_hex(255, 4, true)        => 0xFF
    162 ///   OS << format_hex(255, 6)              => 0x00ff
    163 ///   OS << format_hex(255, 2)              => 0xff
    164 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
    165                                   bool Upper = false) {
    166   assert(Width <= 18 && "hex width must be <= 18");
    167   return FormattedNumber(N, 0, Width, true, Upper, true);
    168 }
    169 
    170 /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
    171 /// prepend '0x' to the outputted string.  If number will not fit in width,
    172 /// full number is still printed.  Examples:
    173 ///   OS << format_hex_no_prefix(255, 4)              => ff
    174 ///   OS << format_hex_no_prefix(255, 4, true)        => FF
    175 ///   OS << format_hex_no_prefix(255, 6)              => 00ff
    176 ///   OS << format_hex_no_prefix(255, 2)              => ff
    177 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
    178                                             bool Upper = false) {
    179   assert(Width <= 18 && "hex width must be <= 18");
    180   return FormattedNumber(N, 0, Width, true, Upper, false);
    181 }
    182 
    183 /// format_decimal - Output \p N as a right justified, fixed-width decimal. If
    184 /// number will not fit in width, full number is still printed.  Examples:
    185 ///   OS << format_decimal(0, 5)     => "    0"
    186 ///   OS << format_decimal(255, 5)   => "  255"
    187 ///   OS << format_decimal(-1, 3)    => " -1"
    188 ///   OS << format_decimal(12345, 3) => "12345"
    189 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
    190   return FormattedNumber(0, N, Width, false, false, false);
    191 }
    192 
    193 } // end namespace llvm
    194 
    195 #endif
    196