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 public:
    122     FormattedString(StringRef S, unsigned W, bool R)
    123       : Str(S), Width(W), RightJustify(R) { }
    124 };
    125 
    126 /// left_justify - append spaces after string so total output is
    127 /// \p Width characters.  If \p Str is larger that \p Width, full string
    128 /// is written with no padding.
    129 inline FormattedString left_justify(StringRef Str, unsigned Width) {
    130   return FormattedString(Str, Width, false);
    131 }
    132 
    133 /// right_justify - add spaces before string so total output is
    134 /// \p Width characters.  If \p Str is larger that \p Width, full string
    135 /// is written with no padding.
    136 inline FormattedString right_justify(StringRef Str, unsigned Width) {
    137   return FormattedString(Str, Width, true);
    138 }
    139 
    140 /// This is a helper class used for format_hex() and format_decimal().
    141 class FormattedNumber {
    142   uint64_t HexValue;
    143   int64_t DecValue;
    144   unsigned Width;
    145   bool Hex;
    146   bool Upper;
    147   bool HexPrefix;
    148   friend class raw_ostream;
    149 public:
    150   FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
    151                   bool Prefix)
    152       : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
    153         HexPrefix(Prefix) {}
    154 };
    155 
    156 /// format_hex - Output \p N as a fixed width hexadecimal. If number will not
    157 /// fit in width, full number is still printed.  Examples:
    158 ///   OS << format_hex(255, 4)              => 0xff
    159 ///   OS << format_hex(255, 4, true)        => 0xFF
    160 ///   OS << format_hex(255, 6)              => 0x00ff
    161 ///   OS << format_hex(255, 2)              => 0xff
    162 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
    163                                   bool Upper = false) {
    164   assert(Width <= 18 && "hex width must be <= 18");
    165   return FormattedNumber(N, 0, Width, true, Upper, true);
    166 }
    167 
    168 /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
    169 /// prepend '0x' to the outputted string.  If number will not fit in width,
    170 /// full number is still printed.  Examples:
    171 ///   OS << format_hex_no_prefix(255, 4)              => ff
    172 ///   OS << format_hex_no_prefix(255, 4, true)        => FF
    173 ///   OS << format_hex_no_prefix(255, 6)              => 00ff
    174 ///   OS << format_hex_no_prefix(255, 2)              => ff
    175 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
    176                                             bool Upper = false) {
    177   assert(Width <= 18 && "hex width must be <= 18");
    178   return FormattedNumber(N, 0, Width, true, Upper, false);
    179 }
    180 
    181 /// format_decimal - Output \p N as a right justified, fixed-width decimal. If
    182 /// number will not fit in width, full number is still printed.  Examples:
    183 ///   OS << format_decimal(0, 5)     => "    0"
    184 ///   OS << format_decimal(255, 5)   => "  255"
    185 ///   OS << format_decimal(-1, 3)    => " -1"
    186 ///   OS << format_decimal(12345, 3) => "12345"
    187 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
    188   return FormattedNumber(0, N, Width, false, false, false);
    189 }
    190 
    191 
    192 } // end namespace llvm
    193 
    194 #endif
    195