LLVM  mainline
Format.h
Go to the documentation of this file.
00001 //===- Format.h - Efficient printf-style formatting for streams -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the format() function, which can be used with other
00011 // LLVM subsystems to provide printf-style formatting.  This gives all the power
00012 // and risk of printf.  This can be used like this (with raw_ostreams as an
00013 // example):
00014 //
00015 //    OS << "mynumber: " << format("%4.5f", 1234.412) << '\n';
00016 //
00017 // Or if you prefer:
00018 //
00019 //  OS << format("mynumber: %4.5f\n", 1234.412);
00020 //
00021 //===----------------------------------------------------------------------===//
00022 
00023 #ifndef LLVM_SUPPORT_FORMAT_H
00024 #define LLVM_SUPPORT_FORMAT_H
00025 
00026 #include "llvm/ADT/STLExtras.h"
00027 #include "llvm/ADT/StringRef.h"
00028 #include "llvm/Support/DataTypes.h"
00029 #include <cassert>
00030 #include <cstdio>
00031 #include <tuple>
00032 
00033 namespace llvm {
00034 
00035 /// This is a helper class used for handling formatted output.  It is the
00036 /// abstract base class of a templated derived class.
00037 class format_object_base {
00038 protected:
00039   const char *Fmt;
00040   ~format_object_base() = default; // Disallow polymorphic deletion.
00041   format_object_base(const format_object_base &) = default;
00042   virtual void home(); // Out of line virtual method.
00043 
00044   /// Call snprintf() for this object, on the given buffer and size.
00045   virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
00046 
00047 public:
00048   format_object_base(const char *fmt) : Fmt(fmt) {}
00049 
00050   /// Format the object into the specified buffer.  On success, this returns
00051   /// the length of the formatted string.  If the buffer is too small, this
00052   /// returns a length to retry with, which will be larger than BufferSize.
00053   unsigned print(char *Buffer, unsigned BufferSize) const {
00054     assert(BufferSize && "Invalid buffer size!");
00055 
00056     // Print the string, leaving room for the terminating null.
00057     int N = snprint(Buffer, BufferSize);
00058 
00059     // VC++ and old GlibC return negative on overflow, just double the size.
00060     if (N < 0)
00061       return BufferSize * 2;
00062 
00063     // Other implementations yield number of bytes needed, not including the
00064     // final '\0'.
00065     if (unsigned(N) >= BufferSize)
00066       return N + 1;
00067 
00068     // Otherwise N is the length of output (not including the final '\0').
00069     return N;
00070   }
00071 };
00072 
00073 /// These are templated helper classes used by the format function that
00074 /// capture the object to be formated and the format string. When actually
00075 /// printed, this synthesizes the string into a temporary buffer provided and
00076 /// returns whether or not it is big enough.
00077 
00078 template <typename... Ts>
00079 class format_object final : public format_object_base {
00080   std::tuple<Ts...> Vals;
00081 
00082   template <std::size_t... Is>
00083   int snprint_tuple(char *Buffer, unsigned BufferSize,
00084                     index_sequence<Is...>) const {
00085 #ifdef _MSC_VER
00086     return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
00087 #else
00088     return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
00089 #endif
00090   }
00091 
00092 public:
00093   format_object(const char *fmt, const Ts &... vals)
00094       : format_object_base(fmt), Vals(vals...) {}
00095 
00096   int snprint(char *Buffer, unsigned BufferSize) const override {
00097     return snprint_tuple(Buffer, BufferSize, index_sequence_for<Ts...>());
00098   }
00099 };
00100 
00101 /// These are helper functions used to produce formatted output.  They use
00102 /// template type deduction to construct the appropriate instance of the
00103 /// format_object class to simplify their construction.
00104 ///
00105 /// This is typically used like:
00106 /// \code
00107 ///   OS << format("%0.4f", myfloat) << '\n';
00108 /// \endcode
00109 
00110 template <typename... Ts>
00111 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
00112   return format_object<Ts...>(Fmt, Vals...);
00113 }
00114 
00115 /// This is a helper class used for left_justify() and right_justify().
00116 class FormattedString {
00117   StringRef Str;
00118   unsigned Width;
00119   bool RightJustify;
00120   friend class raw_ostream;
00121 public:
00122     FormattedString(StringRef S, unsigned W, bool R)
00123       : Str(S), Width(W), RightJustify(R) { }
00124 };
00125 
00126 /// left_justify - append spaces after string so total output is
00127 /// \p Width characters.  If \p Str is larger that \p Width, full string
00128 /// is written with no padding.
00129 inline FormattedString left_justify(StringRef Str, unsigned Width) {
00130   return FormattedString(Str, Width, false);
00131 }
00132 
00133 /// right_justify - add spaces before string so total output is
00134 /// \p Width characters.  If \p Str is larger that \p Width, full string
00135 /// is written with no padding.
00136 inline FormattedString right_justify(StringRef Str, unsigned Width) {
00137   return FormattedString(Str, Width, true);
00138 }
00139 
00140 /// This is a helper class used for format_hex() and format_decimal().
00141 class FormattedNumber {
00142   uint64_t HexValue;
00143   int64_t DecValue;
00144   unsigned Width;
00145   bool Hex;
00146   bool Upper;
00147   bool HexPrefix;
00148   friend class raw_ostream;
00149 public:
00150   FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
00151                   bool Prefix)
00152       : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
00153         HexPrefix(Prefix) {}
00154 };
00155 
00156 /// format_hex - Output \p N as a fixed width hexadecimal. If number will not
00157 /// fit in width, full number is still printed.  Examples:
00158 ///   OS << format_hex(255, 4)              => 0xff
00159 ///   OS << format_hex(255, 4, true)        => 0xFF
00160 ///   OS << format_hex(255, 6)              => 0x00ff
00161 ///   OS << format_hex(255, 2)              => 0xff
00162 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
00163                                   bool Upper = false) {
00164   assert(Width <= 18 && "hex width must be <= 18");
00165   return FormattedNumber(N, 0, Width, true, Upper, true);
00166 }
00167 
00168 /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
00169 /// prepend '0x' to the outputted string.  If number will not fit in width,
00170 /// full number is still printed.  Examples:
00171 ///   OS << format_hex_no_prefix(255, 4)              => ff
00172 ///   OS << format_hex_no_prefix(255, 4, true)        => FF
00173 ///   OS << format_hex_no_prefix(255, 6)              => 00ff
00174 ///   OS << format_hex_no_prefix(255, 2)              => ff
00175 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
00176                                             bool Upper = false) {
00177   assert(Width <= 18 && "hex width must be <= 18");
00178   return FormattedNumber(N, 0, Width, true, Upper, false);
00179 }
00180 
00181 /// format_decimal - Output \p N as a right justified, fixed-width decimal. If 
00182 /// number will not fit in width, full number is still printed.  Examples:
00183 ///   OS << format_decimal(0, 5)     => "    0"
00184 ///   OS << format_decimal(255, 5)   => "  255"
00185 ///   OS << format_decimal(-1, 3)    => " -1"
00186 ///   OS << format_decimal(12345, 3) => "12345"
00187 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
00188   return FormattedNumber(0, N, Width, false, false, false);
00189 }
00190 
00191 
00192 } // end namespace llvm
00193 
00194 #endif