LLVM API Documentation

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() {} // Disallow polymorphic deletion.
00041   virtual void home(); // Out of line virtual method.
00042 
00043   /// Call snprintf() for this object, on the given buffer and size.
00044   virtual int snprint(char *Buffer, unsigned BufferSize) const = 0;
00045 
00046 public:
00047   format_object_base(const char *fmt) : Fmt(fmt) {}
00048 
00049   /// Format the object into the specified buffer.  On success, this returns
00050   /// the length of the formatted string.  If the buffer is too small, this
00051   /// returns a length to retry with, which will be larger than BufferSize.
00052   unsigned print(char *Buffer, unsigned BufferSize) const {
00053     assert(BufferSize && "Invalid buffer size!");
00054 
00055     // Print the string, leaving room for the terminating null.
00056     int N = snprint(Buffer, BufferSize);
00057 
00058     // VC++ and old GlibC return negative on overflow, just double the size.
00059     if (N < 0)
00060       return BufferSize * 2;
00061 
00062     // Other implementations yield number of bytes needed, not including the
00063     // final '\0'.
00064     if (unsigned(N) >= BufferSize)
00065       return N + 1;
00066 
00067     // Otherwise N is the length of output (not including the final '\0').
00068     return N;
00069   }
00070 };
00071 
00072 /// These are templated helper classes used by the format function that
00073 /// capture the object to be formated and the format string. When actually
00074 /// printed, this synthesizes the string into a temporary buffer provided and
00075 /// returns whether or not it is big enough.
00076 
00077 template <typename... Ts>
00078 class format_object final : public format_object_base {
00079   std::tuple<Ts...> Vals;
00080 
00081   template <std::size_t... Is>
00082   int snprint_tuple(char *Buffer, unsigned BufferSize,
00083                     index_sequence<Is...>) const {
00084 #ifdef _MSC_VER
00085     return _snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
00086 #else
00087     return snprintf(Buffer, BufferSize, Fmt, std::get<Is>(Vals)...);
00088 #endif
00089   }
00090 
00091 public:
00092   format_object(const char *fmt, const Ts &... vals)
00093       : format_object_base(fmt), Vals(vals...) {}
00094 
00095   int snprint(char *Buffer, unsigned BufferSize) const override {
00096     return snprint_tuple(Buffer, BufferSize, index_sequence_for<Ts...>());
00097   }
00098 };
00099 
00100 /// These are helper functions used to produce formatted output.  They use
00101 /// template type deduction to construct the appropriate instance of the
00102 /// format_object class to simplify their construction.
00103 ///
00104 /// This is typically used like:
00105 /// \code
00106 ///   OS << format("%0.4f", myfloat) << '\n';
00107 /// \endcode
00108 
00109 template <typename... Ts>
00110 inline format_object<Ts...> format(const char *Fmt, const Ts &... Vals) {
00111   return format_object<Ts...>(Fmt, Vals...);
00112 }
00113 
00114 /// This is a helper class used for left_justify() and right_justify().
00115 class FormattedString {
00116   StringRef Str;
00117   unsigned Width;
00118   bool RightJustify;
00119   friend class raw_ostream;
00120 public:
00121     FormattedString(StringRef S, unsigned W, bool R)
00122       : Str(S), Width(W), RightJustify(R) { }
00123 };
00124 
00125 /// left_justify - append spaces after string so total output is
00126 /// \p Width characters.  If \p Str is larger that \p Width, full string
00127 /// is written with no padding.
00128 inline FormattedString left_justify(StringRef Str, unsigned Width) {
00129   return FormattedString(Str, Width, false);
00130 }
00131 
00132 /// right_justify - add spaces before string so total output is
00133 /// \p Width characters.  If \p Str is larger that \p Width, full string
00134 /// is written with no padding.
00135 inline FormattedString right_justify(StringRef Str, unsigned Width) {
00136   return FormattedString(Str, Width, true);
00137 }
00138 
00139 /// This is a helper class used for format_hex() and format_decimal().
00140 class FormattedNumber {
00141   uint64_t HexValue;
00142   int64_t DecValue;
00143   unsigned Width;
00144   bool Hex;
00145   bool Upper;
00146   bool HexPrefix;
00147   friend class raw_ostream;
00148 public:
00149   FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U,
00150                   bool Prefix)
00151       : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U),
00152         HexPrefix(Prefix) {}
00153 };
00154 
00155 /// format_hex - Output \p N as a fixed width hexadecimal. If number will not
00156 /// fit in width, full number is still printed.  Examples:
00157 ///   OS << format_hex(255, 4)              => 0xff
00158 ///   OS << format_hex(255, 4, true)        => 0xFF
00159 ///   OS << format_hex(255, 6)              => 0x00ff
00160 ///   OS << format_hex(255, 2)              => 0xff
00161 inline FormattedNumber format_hex(uint64_t N, unsigned Width,
00162                                   bool Upper = false) {
00163   assert(Width <= 18 && "hex width must be <= 18");
00164   return FormattedNumber(N, 0, Width, true, Upper, true);
00165 }
00166 
00167 /// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not
00168 /// prepend '0x' to the outputted string.  If number will not fit in width,
00169 /// full number is still printed.  Examples:
00170 ///   OS << format_hex_no_prefix(255, 4)              => ff
00171 ///   OS << format_hex_no_prefix(255, 4, true)        => FF
00172 ///   OS << format_hex_no_prefix(255, 6)              => 00ff
00173 ///   OS << format_hex_no_prefix(255, 2)              => ff
00174 inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width,
00175                                             bool Upper = false) {
00176   assert(Width <= 18 && "hex width must be <= 18");
00177   return FormattedNumber(N, 0, Width, true, Upper, false);
00178 }
00179 
00180 /// format_decimal - Output \p N as a right justified, fixed-width decimal. If 
00181 /// number will not fit in width, full number is still printed.  Examples:
00182 ///   OS << format_decimal(0, 5)     => "    0"
00183 ///   OS << format_decimal(255, 5)   => "  255"
00184 ///   OS << format_decimal(-1, 3)    => " -1"
00185 ///   OS << format_decimal(12345, 3) => "12345"
00186 inline FormattedNumber format_decimal(int64_t N, unsigned Width) {
00187   return FormattedNumber(0, N, Width, false, false, false);
00188 }
00189 
00190 
00191 } // end namespace llvm
00192 
00193 #endif