Corrade::Utility namespace

Utitlities.

This library contains utility classes used by all other Corrade parts, like debug and error output (class Debug), access to configuration files (class Configuration) or compiling data files into the executable (class Resource, see also tutorial).

This library is built if WITH_UTILITY is enabled when building Corrade. To use this library with CMake, you need to request the Utility component of the Corrade package and link to the Corrade::Utility target:

find_package(Corrade REQUIRED Utility)

# ...
target_link_libraries(your-app Corrade::Utility)

See also Downloading and building Corrade and Using Corrade with CMake for more information.

Namespaces

namespace Directory
Filesystem utilities.
namespace String
String utilities.
namespace System
System utilities.
namespace Unicode
Unicode utilities.

Classes

template<std::size_t digestSize>
class AbstractHash
Base template for hashing classes.
class AndroidLogStreamBuffer
Stream buffer that sends the data to Android log.
class Arguments
Command-line argument parser.
class Configuration
Parser and writer for configuration files.
class ConfigurationGroup
Group of values in configuration file.
template<class T>
struct ConfigurationValue
Configuration value parser and writer.
template<>
struct ConfigurationValue<bool>
Configuration value parser and writer for bool type.
template<>
struct ConfigurationValue<char32_t>
Configuration value parser and writer for char32_t type.
template<>
struct ConfigurationValue<double>
Configuration value parser and writer for double type.
template<>
struct ConfigurationValue<float>
Configuration value parser and writer for float type.
template<>
struct ConfigurationValue<int>
Configuration value parser and writer for int type.
template<>
struct ConfigurationValue<long>
Configuration value parser and writer for long type.
template<>
struct ConfigurationValue<long double>
Configuration value parser and writer for long double type.
template<>
struct ConfigurationValue<long long>
Configuration value parser and writer for long long type.
template<>
struct ConfigurationValue<short>
Configuration value parser and writer for short type.
template<>
struct ConfigurationValue<std::string>
Configuration value parser and writer for std::string type.
template<>
struct ConfigurationValue<unsigned int>
Configuration value parser and writer for unsigned int type.
template<>
struct ConfigurationValue<unsigned long>
Configuration value parser and writer for unsigned long type.
template<>
struct ConfigurationValue<unsigned long long>
Configuration value parser and writer for unsigned long long type.
template<>
struct ConfigurationValue<unsigned short>
Configuration value parser and writer for unsigned short type.
class Debug
Debug output handler.
class Endianness
Endianness related functions.
class Error
Error output handler.
class Fatal
Warning output handler.
template<std::size_t size>
class HashDigest
Hash digest.
class MurmurHash2
MurmurHash 2.
class Resource
Data resource management.
class Sha1
SHA-1.
class Warning
Warning output handler.

Enums

enum class ConfigurationValueFlag: std::uint8_t { Oct = 1 << 0, Hex = 1 << 1, Scientific = 1 << 2, Uppercase = 1 << 3 }
Configuration value conversion flag.

Typedefs

using ConfigurationValueFlags = Containers::EnumSet<ConfigurationValueFlag>
Configuration value conversion flags.
template<class T>
using IsIterable = std::integral_constant<bool, implementation-specific>
Traits class for checking whether given type is iterable.

Functions

auto operator<<(Debug& debug, Debug::Color value) -> Debug&
Debug output operator.
template<class... Args>
auto formatString(const char* format, const Args&... args) -> std::string
Format a string.
template<class... Args>
auto formatInto(std::string& string, std::size_t offset, const char* format, const Args&... args) -> std::size_t
Format a string into an existing string.
template<class... Args>
auto formatInto(Containers::ArrayView<char> buffer, const char* format, const Args&... args) -> std::size_t
Format a string into an existing buffer.
template<class... Args>
void formatInto(std::FILE* file, const char* format, const Args&... args)
Format a string into a file.
void sleep(std::size_t ms) deprecated
Sleep for given time.

Type utilities

template<class To, class From>
auto bitCast(const From& from) -> To
Cast type to another of the same size.

Enum documentation

enum class Corrade::Utility::ConfigurationValueFlag: std::uint8_t

Configuration value conversion flag.

Enumerators
Oct

Numeric value as octal

Hex

Numeric value as hexadecimal

Scientific

Floating point values in scientific notation

Uppercase

Use uppercase characters for numeric output

Typedef documentation

template<class T>
using Corrade::Utility::IsIterable = std::integral_constant<bool, implementation-specific>

Traits class for checking whether given type is iterable.

Equivalent to std::true_type if the class is has either begin() / end() members, is usable with free begin() / end() functions or has std::begin() / std::end() overloads. Otherwise equivalent to std::false_type.

Function documentation

Debug& Corrade::Utility::operator<<(Debug& debug, Debug::Color value)

Debug output operator.

template<class... Args>
std::string Corrade::Utility::formatString(const char* format, const Args&... args)

Format a string.

Provides type-safe formatting of arbitrary types into a template string, similar in syntax to Python's format(). Example usage:

std::string s = Utility::formatString("{} version {}.{}.{}, {} MB",
    "vulkan.hpp", 1, 1, 76, 1.79);
// vulkan.hpp version 1.1.76, 1.79 MB

Templating language

Formatting placeholders are denoted by {}, which can have either implicit ordering (as shown above), or be numbered, such as {2}. Zero means first item from args, it's allowed to repeat the numbers. An implicit placeholder following a numbered one will get next position after. Example:

std::string s = Utility::formatString("<{0}><{1}>Good {}, {}!</{1}></{0}>",
    "p", "strong", "afternoon", "ma'am!");
// <p><strong>Good afternoon, ma'am!</strong></p>

Unlike in Python, it's allowed to both have more placeholders than arguments or more arguments than placeholders. Extraneous placeholders are copied to the output verbatim, extraneous arguments are simply ignored.

In order to write a literal curly brace to the output, simply double it:

std::string s = Utility::formatString("union {{ {} a; char data[{}]; }} caster;",
    "float", sizeof(float));
// union { float a; char data[4]; } caster;

Data type support

TypeBehavior
char, unsigned charWritten as an integer (not as a character)
short, unsigned shortWritten as an integer
int, unsigned intWritten as an integer
long, unsigned longWritten as an integer
long long, unsigned long longWritten as an integer
floatWritten as a float with 6 significant digits by default
doubleWritten as a float with 15 significant digits by default
long doubleWritten as a float with 18 significant digits by default
char*Written as a sequence of characters until '\0' (which is not written)
std::stringWritten as a sequence of std::string::size() characters
Containers::ArrayView<char>Written as a sequence of Containers::ArrayView::size() characters

Advanced formatting options

Advanced formatting such as precision or presentation type is possible by putting extra options after a semicolon, following the optional placeholder number, such as {:x} to print an integer value in hexadecimal. In general, the syntax similar to the std::printf()-style formatting, with the addition of {} and : used instead of % — for example, "%.2x" can be translated to "{:.2x}".

The full placeholder syntax is the following, again a subset of the Python format():

{[number][:[.precision][type]]}

The type is a single character specifying output conversion:

ValueMeaning
'd'Decimal integer (base 10). Valid only for integer types. Default for integers if nothing is specified.
'o'Octal integer (base 8). Valid only for integer types.
'x'Hexadecimal integer (base 16) with lowercase letters a–f. Valid only for integer types.
'X'Hexadecimal integer with uppercase letters A–F. Valid only for integer types.
'g'General floating-point, formatting the value either in exponent notation or fixed-point format depending on its magnitude. The exponent e and special values such as nan or inf are printed lowercase. Valid only for floating-point types.
'G'General floating-point. The exponent E and special values such as NAN or INF are printed uppercase. Valid only for floating-point types.
'e'Exponent notation. The exponent e and special values such as nan or inf are printed lowercase. Valid only for floating-point types.
'E'Exponent notation. The exponent E and special values such as NAN or INF are printed uppercase. Valid only for floating-point types.
'f'Fixed point. The exponent e and special values such as nan or inf are printed lowercase. Valid only for floating-point types.
'F'Fixed point. The exponent E and special values such as NAN or INF are printed uppercase. Valid only for floating-point types.
noneDefault based on type, equivalent to 'd' for integral types and 'g' for floating-point types. The only valid specifier for strings.

The precision field specifies a precision of the output. It's interpreted differently based on the data type:

TypeMeaning
IntegersIf the number of decimals is smaller than precision, the integer gets padded with the 0 character from the left. If both the number and precision is 0, nothing is written to the output. Default precision is 1.
Floating-point types with default or 'g' / 'G' type specifierThe number is printed with at most precision significant digits. Default precision depends on data type, see the type support table above.
Floating-point types with 'e' / 'E' type specifierThe number is always printed with exactly one decimal, precision decimal points (including trailing zeros) and the exponent. Default precision depends on data type, see the type support table above.
Floating-point types with 'f' / 'F' type specifierThe number is always printed with exactly precision decimal points including trailing zeros. Default precision depends on data type, see the type support table above.
StringsIf the string length is larger than precision, only the first precision bytes are written to the output. Default precision is unlimited. Note that this doesn't work with UTF-8 at the moment.

Example of formating of CSS colors with correct width:

std::string s = Utility::formatString("path {{ fill: #{:6x}; stroke: #{:6x}; }}",
    0x33ff00, 0x00aa55);
// path { fill: #33ff00; stroke: #00aa55; }

Performance

This function always does exactly one allocation for the output string. See formatInto(std::string&, std::size_t, const char*, const Args&... args) for an ability to write into an existing string (with at most one reallocation) and formatInto(Containers::ArrayView<char>, const char*, const Args&... args) for a completely zero-allocation alternative. There is also formatInto(std::FILE*, const char*, const Args&... args) for writing to files or standard output.

Comparison to Debug

Debug class desired usage is for easy printing of complex nested types, containers, enum values or opaque types for logging and diagnostic purposes, with focus on convenience rather than speed or advanced formatting capabilities. The formatString() family of functions is intended for cases where it's required to have a complete control over the output, for example when serializing text files.

template<class... Args>
std::size_t Corrade::Utility::formatInto(std::string& string, std::size_t offset, const char* format, const Args&... args)

Format a string into an existing string.

Takes an existing string and writes the formatted content starting at offset. If the string is not large enough, does at most one reallocation (by calling std::string::resize()). Returns final written size (which might be less than the string size if inserting in the middle). Does not write any terminating '\0' character. Example usage:

std::vector<float> positions{-0.5f, -0.5f, 0.0f,
                              0.5f, -0.5f, 0.0f,
                              0.0f,  0.5f, 0.0f};
std::string out;
for(std::size_t i = 0; i < positions.size(); i += 3)
    Utility::formatInto(out, out.size(), "{}[{0}, {1}, {2}]",
        out.empty() ? "" : ", ",
        positions[i*3 + 0], positions[i*3 + 1], positions[i*3 + 2]);

// [-0.5, -0.5, 0], [0.5, -0.5, 0], [0.0, 0.5, 0.0]

See formatString() for more information about usage and templating language.

template<class... Args>
std::size_t Corrade::Utility::formatInto(Containers::ArrayView<char> buffer, const char* format, const Args&... args)

Format a string into an existing buffer.

Writes formatted output to given buffer, expecting that it is large enough. The formatting is done completely without any allocation. Returns total amount of bytes written, does not write any terminating '\0' character. Example usage:

char shaderVersion[128]; // large enough
std::size_t size = Utility::formatInto(shaderVersion, "#version {}\n", 430);
addShaderSource({shaderVersion, size});

See formatString() for more information about usage and templating language.

template<class... Args>
void Corrade::Utility::formatInto(std::FILE* file, const char* format, const Args&... args)

Format a string into a file.

Writes formatted output to file, which can be either an arbitrary file opened using std::fopen() or stdout / stderr. Does not allocate on its own (though the underlying file writing routines might), does not write any terminating '\0' character. Example usage:

Utility::formatInto(stdout, "Hello, {}!", "world");

See formatString() for more information about usage and templating language.

void Corrade::Utility::sleep(std::size_t ms)

Sleep for given time.

template<class To, class From>
To Corrade::Utility::bitCast(const From& from)

Cast type to another of the same size.

Unlike reinterpret_cast this doesn't break strict-aliasing rules.