HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
UT_Format.h File Reference

Type-safe formatting, modeled on the Python str.format function. More...

#include "UT_API.h"
#include "UT_Assert.h"
#include "UT_NonCopyable.h"
#include <SYS/SYS_Types.h>
#include <algorithm>
#include <initializer_list>
#include <iosfwd>
#include <limits>
#include <string>
#include <type_traits>
#include <stdio.h>
#include "UT_FormatImpl.h"
+ Include dependency graph for UT_Format.h:
+ This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  UT::Format::Writer
 
struct  UT::Format::FileWriter
 A specialized Writer class that writes to a stdio FILE buffer. More...
 
struct  UT::Format::StreamWriter
 A specialized Writer class that writes to a std::ostream object. More...
 
struct  UT::Format::CustomWriter
 
struct  UT::Format::Impl::TrueType< typename >
 
struct  UT::Format::HasFormat< T >
 
class  UT::Format::ArgValue
 
struct  UT::Format::ArgValue::SizedString
 
struct  UT::Format::ArgValue::Custom
 
class  UT::Format::Formatter< W >
 

Namespaces

 UT
 
 UT::Format
 
 UT::Format::Impl
 

Macros

#define UT_ENABLE_IF(T)   typename std::enable_if<T>::type * = nullptr
 
#define UT_HAS_FMT(T)   HasFormat<T>::value
 
#define UT_REMOVE_PTR(T)   typename std::remove_pointer<T>::type
 
#define UT_IS_PTR(T)   std::is_pointer<T>::value
 
#define UT_IS_ENUM(T)   std::is_enum<T>::value
 

Functions

Standalone formatting functions

numbers, this only applies to the integer portion of the float.

  • <width> specifies the minimum width of the field. Arguments wider than this value will still be printed out in full. Preceding the width field with 0 will automatically set the alignment to number alignment, and the fill value to 0.
  • <precision> sets the precision for floating point numbers. For other types it specifies the maximum width of the field.
  • <type> is a single character code that specifies how the type should be interpreted. If an argument type is not valid for the formatting type, the formatting type is ignored. The supported types are:
    • b: Output integers as binary numbers.
    • B: Output integers as binary numbers with an upper-case prefix (if using the # option.
    • c: Output integers interpreted as a Unicode code point.
    • d: Output integers as decimal numbers. This is the default for integers.
    • e: Use the exponent notation for floating point numbers.
    • E: Same as e, except the exponent separator is upper-cased.
    • f: Use the fixed point notation for floating point numbers.
    • F: Same as f.
    • g: Format a floating point number as either fixed point or scientific, depending on its magnitude, which mostly results in the shortest form being used. This is the default for floats.
    • G: Same as g, except the exponent separator is upper-cased.
    • o: Output integers as octals.
    • x: Output integers and floats as hexadecimal. For floats this uses the special hexadecimal float output.
    • X: The same as x, except all alphabetic digits and prefix are output in upper-case.
    • %: Takes a floating point number, multiplies it by 100 and outputs it with a percentage sign appended, using fixed point notation. The default precision in this mode is 2.

Example:

UTformat("Number: {}\n", 1);
UTformat("String: {}\n", "foobar");
UTformat("Field : {:=^20}\n", 1);
UTformat("Index : {3} {0} {2} {1}\n", 'A', 'B', 'C', 'D');
UTformat("Perc : {:.1%}\n", 0.1234);

Result:

Number: 1
String: foobar
Field : =========1==========
Index : D A C B
Perc : 12.3%

Printf Grammar

The UTprintf and UT_Format::printf functions use formatting code very similar to the POSIX specification for printf. The code begins with a single % character, followed by zero or more modifiers, ending with the type specifier. Where this implementation of the printf formatting code differs, is that there is no need to add length modifiers. Any length modifers will simply be ignored.

Custom Formatting

Custom types are supported through custom formatting functions. To define a custom formatting function for a specific type, the following function specialization needs to be implemented:

size_t format(char *buffer, size_t buffer_size, const CustomType &val);

Where:

  • buffer is a byte buffer to write the result into. If buffer is a nullptr, then the function should return the number of bytes required to store the final result.
  • buffer_size is the size of the byte buffer passed in via buffer. This should be ignored if buffer is nullptr.
  • is value to custom format. The function should return the number of bytes written out, or, if buffer is nullptr, the amount of bytes needed to write out the entire custom type representation.
template<typename... Args>
size_t UTformat (FILE *file, const char *format, const Args &...args)
 
template<typename... Args>
size_t UTformat (const char *format, const Args &...args)
 
template<typename... Args>
size_t UTformat (std::ostream &os, const char *format, const Args &...args)
 
template<typename... Args>
size_t UTformat (char *buffer, size_t buffer_size, const char *format, const Args &...args)
 
Standalone printf-like functions
template<typename... Args>
size_t UTprintf (FILE *file, const char *format, const Args &...args)
 
template<typename... Args>
size_t UTprintf (const char *format, const Args &...args)
 
template<typename... Args>
size_t UTprintf (std::ostream &os, const char *format, const Args &...args)
 
template<typename... Args>
size_t UTprintf (char *buffer, size_t buffer_size, const char *format, const Args &...args)
 

Detailed Description

Type-safe formatting, modeled on the Python str.format function.

This formatter supports a sub-set of the Python format syntax. Notably, only indexed arguments are supported for now, not named ones.

Like with the printf() formatting, the format string contains replacement fields that will be substituted by the textual representation of the arguments to the various format functions. The replacement fields for this formatter are surrounded by curly braces {}, rather than prefixed with a %.

Note the string {{ or }} will result in a single { or } being output.

Format Grammar

The grammar for the replacement field is as follows:

{[<index>][:<spec>]}

The <index> is an optional integer value, which refers to the position of the argument after the format string. If the <index> is omitted for all replacement fields, then they are automatically substituted with 0, 1, 2, ... It is not permitted to mix indexed and non-indexed.

If a colon separator is found, the string after that is interpreted as a formatting specification. The grammar for the <spec> field is as follows:

[[<fill>]<align>][<sign>][#][,][0][<width>][.<precision>][<type>]

Where:

  • <fill> is the fill character to use when the width of the field is greater than the length of the argument value being printed.
  • <align> is a single character code which sets the alignment of the value within the field:
    • <: The field is left-aligned. This is the default for non-numeric values.
    • >: The field is right-aligned. This is the default for numeric values.
    • ^: The field is center-aligned.
    • =: The field is number aligned. This is the same as right-aligned, except the fill value is inserted between the sign indicator and the numeric value. This alignment is only available for numeric values.
  • <sign> is a single character that specifies how the sign is printed for numeric values:
    • +: Always print a sign, whether positive or negative.
    • -: Only print a sign when the number is negative.
    • <space>: Use a leading space on positive numbers, minus sign for negative.
  • The '#' option is only available for binary, octal or hexadecimal output. It indicates that they should be prefixed with '0b', '0' and '0x', respectively.
  • The ',' option will add digit grouping to numerical outputs. For float

Definition in file UT_Format.h.

Macro Definition Documentation

#define UT_ENABLE_IF (   T)    typename std::enable_if<T>::type * = nullptr

Definition at line 451 of file UT_Format.h.

#define UT_HAS_FMT (   T)    HasFormat<T>::value

Definition at line 452 of file UT_Format.h.

#define UT_IS_ENUM (   T)    std::is_enum<T>::value

Definition at line 455 of file UT_Format.h.

#define UT_IS_PTR (   T)    std::is_pointer<T>::value

Definition at line 454 of file UT_Format.h.

#define UT_REMOVE_PTR (   T)    typename std::remove_pointer<T>::type

Definition at line 453 of file UT_Format.h.

Function Documentation

template<typename... Args>
size_t UTformat ( FILE *  file,
const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string to the FILE pointer.

Parameters
fileThe FILE pointer to write to. The FILE must be opened in write or append mode.
formatThe formatting codes, as defined in Format Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1083 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTformat ( const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string to stdout.

Parameters
formatThe formatting codes, as defined in Format Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1113 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTformat ( std::ostream &  os,
const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string to the output stream object.

Parameters
osThe output stream to write to.
formatThe formatting codes, as defined in Format Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1120 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTformat ( char *  buffer,
size_t  buffer_size,
const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string into the buffer provided. If buffer is nullptr, then nothing is written out, but the number of bytes needed to store the entire formatted string is returned. A termination byte is not written out to the buffer. If termination is required, the caller must take care of it.

Parameters
bufferThe character buffer to write the formatted string to.
buffer_sizeThe size of the character buffer.
formatThe formatting codes, as defined in Format Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1130 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTprintf ( FILE *  file,
const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string to the FILE pointer.

Parameters
fileThe FILE pointer to write to. The FILE must be opened in write or append mode.
formatThe formatting codes, as defined in Printf Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1144 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTprintf ( const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string to stdout.

Parameters
formatThe formatting codes, as defined in Printf Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1174 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTprintf ( std::ostream &  os,
const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string to the output stream object.

Parameters
osThe output stream to write to.
formatThe formatting codes, as defined in Printf Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1181 of file UT_FormatImpl.h.

template<typename... Args>
size_t UTprintf ( char *  buffer,
size_t  buffer_size,
const char *  format,
const Args &...  args 
)

Takes a formatting string and a set of arguments and writes out the formatted string into the buffer provided. If buffer is nullptr, then nothing is written out, but the number of bytes needed to store the entire formatted string is returned. A termination byte is not written out to the buffer. If termination is required, the caller must take care of it.

Parameters
bufferThe character buffer to write the formatted string to.
buffer_sizeThe size of the character buffer.
formatThe formatting codes, as defined in Printf Grammar.
argsThe arguments to the formatting.
Returns
The number of bytes successfully written out.

Definition at line 1191 of file UT_FormatImpl.h.