Corrade::Utility namespace

Utilities.

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 CORRADE_WITH_UTILITY is enabled when building Corrade. To use this library with CMake, 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 PRIVATE Corrade::Utility)

Parts of this library are additionally available in a form of single-header libraries. See also Downloading and building Corrade and Using Corrade with CMake for more information.

Namespaces

namespace Directory deprecated in Git master
Filesystem utilities.
namespace Endianness
Endianness-related functions.
namespace Path new in Git master
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 a 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<Containers::String> new in Git master
Configuration value parser and writer for Containers::String.
template<>
struct ConfigurationValue<Containers::StringView> new in Git master
Configuration value parser and writer for Containers::StringView.
template<>
struct ConfigurationValue<double>
Configuration value parser and writer for the double type.
template<>
struct ConfigurationValue<float>
Configuration value parser and writer for the float type.
template<>
struct ConfigurationValue<int>
Configuration value parser and writer for the int type.
template<>
struct ConfigurationValue<long>
Configuration value parser and writer for the 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 the long long type.
template<>
struct ConfigurationValue<short>
Configuration value parser and writer for the 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 the unsigned int type.
template<>
struct ConfigurationValue<unsigned long>
Configuration value parser and writer for the unsigned long type.
template<>
struct ConfigurationValue<unsigned long long>
Configuration value parser and writer for the unsigned long long type.
template<>
struct ConfigurationValue<unsigned short>
Configuration value parser and writer for the unsigned short type.
class Debug
Debug output handler.
class Error
Error output handler.
class Fatal
Fatal output handler.
class FileWatcher
File watcher.
template<std::size_t size>
class HashDigest
Hash digest.
class Json new in Git master
JSON parser.
class JsonArrayItem new in Git master
JSON array item.
template<class T>
class JsonIterator new in Git master
JSON iterator.
class JsonObjectItem new in Git master
JSON object item.
class JsonToken new in Git master
A single JSON token.
template<class T>
class JsonView new in Git master
JSON object and array view.
class JsonWriter new in Git master
JSON writer.
class MurmurHash2
MurmurHash 2.
class Resource
Access to compiled-in resources.
class Sha1
SHA-1.
class Tweakable
Tweakable constants.
template<class T>
struct TweakableParser
Parser for Tweakable types.
template<>
struct TweakableParser<bool>
Tweakable constant parser for the bool type.
template<>
struct TweakableParser<char>
Tweakable constant parser for the char type.
template<>
struct TweakableParser<double>
Tweakable constant parser for the double type.
template<>
struct TweakableParser<float>
Tweakable constant parser for the float type.
template<>
struct TweakableParser<int>
Tweakable constant parser for the int type.
template<>
struct TweakableParser<long>
Tweakable constant parser for the long int type.
template<>
struct TweakableParser<long double>
Tweakable constant parser for the long double type.
template<>
struct TweakableParser<long long>
Tweakable constant parser for the long long int type.
template<>
struct TweakableParser<unsigned int>
Tweakable constant parser for the unsigned int type.
template<>
struct TweakableParser<unsigned long>
Tweakable constant parser for the unsigned long int type.
template<>
struct TweakableParser<unsigned long long>
Tweakable constant parser for the unsigned long long int type.
class Warning
Warning output handler.

Enums

enum class ConfigurationValueFlag: unsigned char { Oct = 1 << 0, Hex = 1 << 1, Scientific = 1 << 2, Uppercase = 1 << 3 }
Configuration value conversion flag.
enum class TweakableState: unsigned char { NoChange = 0, Success = 1, Recompile = 2, Error = 3 }
Tweakable state.

Typedefs

using ConfigurationValueFlags = Containers::EnumSet<ConfigurationValueFlag>
Configuration value conversion flags.
using JsonObjectView = JsonView<JsonObjectItem> new in Git master
JSON object view.
using JsonArrayView = JsonView<JsonArrayItem> new in Git master
JSON array view.
template<class T>
using IsIterable = std::integral_constant<bool, implementation-specific>
Traits class for checking whether given type is iterable.
template<class T>
using IsStringLike = std::integral_constant<bool, implementation-specific> new in 2019.10
Traits class for checking whether given type is string-like.

Functions

void copy(Containers::ArrayView<const void> src, Containers::ArrayView<void> dst) new in 2020.06
Copy an array view to another.
template<class T>
void copy(Containers::ArrayView<const T> src, Containers::ArrayView<T> dst) new in 2020.06
Copy an array view to another.
template<unsigned dimensions>
void copy(const Containers::StridedArrayView<dimensions, const char>& src, const Containers::StridedArrayView<dimensions, char>& dst) new in 2020.06
Copy a strided array view to another.
void copy(const Containers::StridedArrayView1D<const char>& src, const Containers::StridedArrayView1D<char>& dst) new in 2020.06
void copy(const Containers::StridedArrayView2D<const char>& src, const Containers::StridedArrayView2D<char>& dst) new in 2020.06
void copy(const Containers::StridedArrayView3D<const char>& src, const Containers::StridedArrayView3D<char>& dst) new in 2020.06
void copy(const Containers::StridedArrayView4D<const char>& src, const Containers::StridedArrayView4D<char>& dst) new in 2020.06
template<unsigned dimensions, class T>
void copy(const Containers::StridedArrayView<dimensions, const T>& src, const Containers::StridedArrayView<dimensions, T>& dst) new in 2020.06
Copy a strided array view to another.
template<class To, class ToView = decltype(Implementation::arrayViewTypeFor(std::declval<To && >()))>
void copy(std::initializer_list<typename ToView::Type> src, To&& dst) new in Git master
Copy an initializer list to a view.
template<unsigned dimension, unsigned dimensions, class T>
void flipInPlace(const Containers::StridedArrayView<dimensions, T>& view) new in Git master
Flip given dimension of a view in-place.
void copyMasked(const Containers::StridedArrayView2D<const char>& src, Containers::BitArrayView srcMask, const Containers::StridedArrayView2D<char>& dst) new in Git master
Copy a masked array view to another.
template<class T>
void copyMasked(const Containers::StridedArrayView1D<const T>& src, Containers::BitArrayView srcMask, const Containers::StridedArrayView1D<T>& dst) new in Git master
Copy a masked array view to another.
auto operator!(Implementation::DebugSourceLocation debug) -> Debug& new in 2020.06
Prefix the output with source location.
template<class T>
auto operator<<(Debug& debug, const T& value) -> Debug&
Operator for printing custom types to debug output.
template<class Iterable>
auto operator<<(Debug& debug, const Iterable& value) -> Debug&
Operator for printing iterable types to debug output.
template<class T, class U>
auto operator<<(Debug& debug, const std::pair<T, U>& value) -> Debug&
Print a std::pair to debug output.
auto operator<<(Debug& debug, const std::string& value) -> Debug&
Print a std::string to debug output.
template<class T>
auto operator<<(Debug& debug, const std::basic_string<T>& value) -> std::enable_if<!std::is_same<T, char>::value, Debug&>::type
Print a std::basic_string to debug output.
template<class ... Args>
auto operator<<(Debug& debug, const std::tuple<Args...>& value) -> Debug&
Print a std::tuple to debug output.
auto operator<<(Debug& debug, std::string_view value) -> Debug& new in Git master
Print a std::string_view to debug output.
template<class T>
auto operator<<(Debug& debug, std::basic_string_view<T> value) -> Debug& new in Git master
Print a std::basic_string_view to debug output.
template<class ... Args>
auto format(const char* format, const Args&... args) -> Containers::String new in 2019.10
Format a string.
template<class ... Args>
auto formatInto(const Containers::MutableStringView& buffer, const char* format, const Args&... args) -> std::size_t
Format a string into an existing buffer.
template<class ... Args, std::size_t size>
auto formatInto(char(&buffer)[size], const char* format, const Args&... args) -> std::size_t
template<class ... Args>
void formatInto(std::FILE* file, const char* format, const Args&... args)
Format a string into a file.
template<class ... Args>
void print(const char* format, const Args&... args)
Print a string to the standard output.
template<class ... Args>
void printError(const char* format, const Args&... args)
Print a string to the standard error output.
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 T>
auto min(T value, T min) -> T constexpr new in Git master
Minimum.
template<class T>
auto max(T value, T max) -> T constexpr new in Git master
Maximum.
template<class T>
auto abs(T a) -> T constexpr new in Git master
Absolute value.
template<class T, std::size_t alignment = alignof(T)>
auto allocateAligned(std::size_t size) -> Containers::Array<T> new in Git master
Allocate aligned memory and value-initialize it.
template<class T, std::size_t alignment = alignof(T)>
auto allocateAligned(DefaultInitT, std::size_t size) -> Containers::Array<T> new in Git master
Allocate aligned memory and default-initialize it.
template<class T, std::size_t alignment = alignof(T)>
auto allocateAligned(ValueInitT, std::size_t size) -> Containers::Array<T> new in Git master
Allocate aligned memory and value-initialize it.
template<class T, std::size_t alignment = alignof(T)>
auto allocateAligned(NoInitT, std::size_t size) -> Containers::Array<T> new in Git master
Allocate aligned memory and leave it uninitialized.
template<class T>
auto forward(typename std::remove_reference<T>::type& t) -> T&& constexpr noexcept new in Git master
Forward an l-value.
template<class T>
auto forward(typename std::remove_reference<T>::type&& t) -> T&& constexpr noexcept new in Git master
Forward an r-value.
template<class T>
auto move(T&& t) -> std::remove_reference<T>::type&& constexpr noexcept new in Git master
Convert a value to an r-value.
template<class T>
void swap(T& a, T& b) noexcept(…) new in Git master
Swap two values.
template<std::size_t size, class T>
void swap(T(&a)[size], T(&b)[size]) noexcept(…) new in Git master
Swap two arrays.
auto operator<<(Debug& debug, TweakableState value) -> Debug&
Debug output operator.

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: unsigned char

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

enum class Corrade::Utility::TweakableState: unsigned char

Tweakable state.

Enumerators
NoChange

No source file has any changes that affect tweakable values. Nothing to do.

Success

Tweakable values in some source files were changed and successfully updated. Values that are neither accessed in the main event loop nor were part of any Tweakable::scope() call should be updated manually on the caller side.

Recompile

Source files were changed in a way that can't be handled by updating just the tweakable values alone. No values were updated, hot-reload the affected code or restart a recompiled version of the app to pick up the changes.

Note that this state is optimistic — it may happen that the changes will lead to a compile error similarly as with TweakableState::Error, but detecting that is out of scope of this utility.

Error

Source files were changed in a way that caused a parse error. No values were updated, fix the error and save the file again to retry the parsing.

This state is returned only when the utility is absolutely sure there is a syntax error (for example when a char literal is not terminated). If not sure, TweakableState::Recompile is returned (and then the compiler might or might not report an error).

Typedef documentation

typedef JsonView<JsonObjectItem> Corrade::Utility::JsonObjectView new in Git master

JSON object view.

Returned from Json::parseObject() and JsonToken::asObject(). See Iterating objects and arrays for more information.

typedef JsonView<JsonArrayItem> Corrade::Utility::JsonArrayView new in Git master

JSON array view.

Returned from Json::parseArray() and JsonToken::asArray(). See Iterating objects and arrays for more information.

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.

Used together with IsStringLike by Debug to decide whether given type should be printed as a container of its contents or as a whole.

template<class T>
using Corrade::Utility::IsStringLike = std::integral_constant<bool, implementation-specific> new in 2019.10

Traits class for checking whether given type is string-like.

Equivalent to std::true_type if the class is has a c_str() or a substr() member or is a Containers::[Mutable]StringView / Containers::String. Otherwise equivalent to std::false_type. Useful for dispatching on the std::string or the C++17 std::string_view and std::filesystem::path types without having to include or forward-declare them.

Used together with IsIterable by Debug to decide whether given type should be printed as a container of its contents or as a whole.

Function documentation

void Corrade::Utility::copy(Containers::ArrayView<const void> src, Containers::ArrayView<void> dst) new in 2020.06

Copy an array view to another.

Calls std::memcpy() on the contents. Expects that both arrays have the same size.

template<class T>
void Corrade::Utility::copy(Containers::ArrayView<const T> src, Containers::ArrayView<T> dst) new in 2020.06

Copy an array view to another.

Casts views into a void type and delegates into copy(Containers::ArrayView<const void>, Containers::ArrayView<void>). Expects that T is a trivially copyable type.

template<unsigned dimensions>
void Corrade::Utility::copy(const Containers::StridedArrayView<dimensions, const char>& src, const Containers::StridedArrayView<dimensions, char>& dst) new in 2020.06

Copy a strided array view to another.

Optimized to call std::memcpy() on largest contiguous sub-dimensions, looping over the non-contiguous dimensions (except when memcpy would be called for very small pieces of memory, in which case either a loop or a variant of Duff's device is used, depending on which is faster on given compiler). The function has specializations for 1D, 2D, 3D and 4D, higher dimensions recurse into these. Expects that both arrays have the same size.

void Corrade::Utility::copy(const Containers::StridedArrayView1D<const char>& src, const Containers::StridedArrayView1D<char>& dst) new in 2020.06

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Corrade::Utility::copy(const Containers::StridedArrayView2D<const char>& src, const Containers::StridedArrayView2D<char>& dst) new in 2020.06

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Corrade::Utility::copy(const Containers::StridedArrayView3D<const char>& src, const Containers::StridedArrayView3D<char>& dst) new in 2020.06

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Corrade::Utility::copy(const Containers::StridedArrayView4D<const char>& src, const Containers::StridedArrayView4D<char>& dst) new in 2020.06

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

template<unsigned dimensions, class T>
void Corrade::Utility::copy(const Containers::StridedArrayView<dimensions, const T>& src, const Containers::StridedArrayView<dimensions, T>& dst) new in 2020.06

Copy a strided array view to another.

Casts views into a char type of one dimension more (where the last dimension has a size of sizeof(T) and delegates into copy(const Containers::StridedArrayView<dimensions, const char>&, const Containers::StridedArrayView<dimensions, char>&). Expects that both arrays have the same size and T is a trivially copyable type.

template<class To, class ToView = decltype(Implementation::arrayViewTypeFor(std::declval<To && >()))>
void Corrade::Utility::copy(std::initializer_list<typename ToView::Type> src, To&& dst) new in Git master

Copy an initializer list to a view.

Based on whether the dst is convertible to either Containers::ArrayView or Containers::StridedArrayView, calls either copy(Containers::ArrayView<const T>, Containers::ArrayView<T>) or copy(const Containers::StridedArrayView<dimensions, const T>& src, const Containers::StridedArrayView<dimensions, T>&). Works with any dst that's convertible to an one-dimensional Containers::StridedArrayView, expects that src has the same underlying type as dst, that they have both the same size and the dst is not const.

This overload can also be used for convenient filling of C arrays, which would otherwise have to be done element-by-element or using std::memcpy() as neither C nor C++ allows array assignment:

int a[3];



Utility::copy({1, 2, 3}, a);

template<unsigned dimension, unsigned dimensions, class T>
void Corrade::Utility::flipInPlace(const Containers::StridedArrayView<dimensions, T>& view) new in Git master

Flip given dimension of a view in-place.

Swaps all items in dimension such that viewDimension[i] and viewDimension[dimensionSize - i - 1] exchange their contents for all i < dimensionSize/2. Expects that T is a trivially copyable type and the view is contiguous after dimension.

View flip not in place can be performed using a copy() to a view that has the desired dimension Containers::StridedArrayView::flipped(). In the following snippet, the first expression does the flip during a copy, while the second performs it in-place:

Containers::StridedArrayView2D<T> pixels = ;
Containers::StridedArrayView2D<T> destination = ;

/* Y-flip the pixels into a destination */
Utility::copy(pixels.flipped<0>(), destination);

/* Y-flip the pixels in-place */
Utility::flipInPlace<0>(pixels);

void Corrade::Utility::copyMasked(const Containers::StridedArrayView2D<const char>& src, Containers::BitArrayView srcMask, const Containers::StridedArrayView2D<char>& dst) new in Git master

Copy a masked array view to another.

For all bits that are set in srcMask takes an element from src and copies it to dst. Expects that src and srcMask have the same size, that count of bits set in srcMask is the same as dst size and that the second dimension of both src and dst has the same size and is contiguous.

template<class T>
void Corrade::Utility::copyMasked(const Containers::StridedArrayView1D<const T>& src, Containers::BitArrayView srcMask, const Containers::StridedArrayView1D<T>& dst) new in Git master

Copy a masked array view to another.

Casts views into a char type of one dimension more (where the last dimension has a size of sizeof(T) and delegates into copyMasked(const Containers::StridedArrayView2D<const char>&, Containers::BitArrayView, const Containers::StridedArrayView2D<char>&). Expects that T is a trivially copyable type.

Debug& Corrade::Utility::operator!(Implementation::DebugSourceLocation debug) new in 2020.06

Prefix the output with source location.

Only on supported compilers, does nothing otherwise. See Source location for more information.

template<class T>
Debug& Corrade::Utility::operator<<(Debug& debug, const T& value)

Operator for printing custom types to debug output.

Parameters
debug Debug class
value Value to be printed

Support for printing custom types (i.e. those not handled by std::iostream) can be added by implementing this function for given type.

The function should convert the type to one of supported types (such as the builtin types or std::string) and then call Debug::operator<<() with it. You can also use Debug::nospace and Debug::newline.

template<class Iterable>
Debug& Corrade::Utility::operator<<(Debug& debug, const Iterable& value)

Operator for printing iterable types to debug output.

Prints the value as {a, b, …}. If the type contains a nested iterable type, the values are separated by newlines. Specifying Debug::Flag::Packed or using Debug::packed will print the values tightly-packed without commas and spaces in between.

template<class T, class U>
Debug& Corrade::Utility::operator<<(Debug& debug, const std::pair<T, U>& value)

Print a std::pair to debug output.

Prints the value as (first, second). Unlike operator<<(Debug& debug, const Iterable& value), the output is not affected by Debug::Flag::Packed / Debug::packed.

Debug& Corrade::Utility::operator<<(Debug& debug, const std::string& value)

Print a std::string to debug output.

For types that are only convertible to a std::string this overload is picked only if the type doesn't also provide a std::ostream operator<<() overload. In that case the value is printed directly to the stream instead, assuming it's a cheaper operation than conversion to a std::string. This is for example a case with std::filesystem::path.

template<class T>
std::enable_if<!std::is_same<T, char>::value, Debug&>::type Corrade::Utility::operator<<(Debug& debug, const std::basic_string<T>& value)

Print a std::basic_string to debug output.

All other types than exactly std::string are printed as containers.

template<class ... Args>
Debug& Corrade::Utility::operator<<(Debug& debug, const std::tuple<Args...>& value)

Print a std::tuple to debug output.

Prints the value as (first, second, third...). Unlike operator<<(Debug& debug, const Iterable& value), the output is not affected by Debug::Flag::Packed / Debug::packed.

Debug& Corrade::Utility::operator<<(Debug& debug, std::string_view value) new in Git master

Print a std::string_view to debug output.

template<class T>
Debug& Corrade::Utility::operator<<(Debug& debug, std::basic_string_view<T> value) new in Git master

Print a std::basic_string_view to debug output.

All other types than exactly std::string_view are printed as containers.

template<class ... Args>
Containers::String Corrade::Utility::format(const char* format, const Args&... args) new in 2019.10

Format a string.

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

Containers::String s = Utility::format("{} 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:

Containers::String s = Utility::format("<{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:

Containers::String s = Utility::format("union {{ {} a; char data[{}]; }} caster;",
    "float", sizeof(float));
// union { float a; char data[4]; } caster;

Data type support

TypeDefault behavior
char, unsigned charWritten as a base-10 integer (not as a character)
short, unsigned shortWritten as a base-10 integer
int, unsigned intWritten as a base-10 integer
long, unsigned longWritten as a base-10 integer
long long, unsigned long longWritten as a base-10 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, by default with 18 significant digits on platforms
with 80-bit long double and 15 digits on platforms where it is 64-bit
char*Written as a sequence of characters until '\0' (which is not written)
Containers::StringView,
MutableStringView, String
Written as a sequence of Containers::StringView::size() characters
Containers::ArrayView<const char> deprecatedWritten as a sequence of Containers::ArrayView::size() characters.
Deprecated, use Containers::StringView instead.
std::stringWritten as a sequence of std::string::size() characters
(#include Corrade/Utility/FormatStl.h in addition)
std::string_viewWritten as a sequence of std::string_view::size() characters
(#include Corrade/Utility/FormatStlStringView.h in addition)

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 -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
'c'Character. Valid only for 8-, 16- and 32-bit integer types. At the moment, arbitrary UTF-32 codepoints don't work, only 7-bit ASCII values have a guaranteed output.
'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
Integers, except for the 'c' type specifierIf 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.
Strings, characters (integers with the 'c' type specifier)If 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 and specifying precision of 0 doesn't give the expected output for characters.

Example of formating of CSS colors with correct width:

Containers::String s = Utility::format("path {{ fill: #{:.6x}; stroke: #{:.6x}; }}",
    0x33ff00, 0x00aa55);
// path { fill: #33ff00; stroke: #00aa55; }

Performance

This function always does exactly one allocation for the output array. See formatInto(std::string&, std::size_t, const char*, const Args&... args) for an ability to write into an existing std::string (with at most one reallocation) and formatInto(const Containers::MutableStringView&, 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 format() 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(const Containers::MutableStringView& 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 format() for more information about usage and templating language.

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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 format() for more information about usage and templating language.

template<class ... Args>
void Corrade::Utility::print(const char* format, const Args&... args)

Print a string to the standard output.

Equivalent to calling formatInto(std::FILE*, const char*, const Args&... args) with stdout as a first parameter.

template<class ... Args>
void Corrade::Utility::printError(const char* format, const Args&... args)

Print a string to the standard error output.

Equivalent to calling formatInto(std::FILE*, const char*, const Args&... args) with stderr as a first parameter.

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

Format a string.

Same as format(), but returning a std::string instead of Containers::String.

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 format() for more information about usage and templating language.

template<class T>
T Corrade::Utility::min(T value, T min) constexpr new in Git master

Minimum.

The main purpose of this function is to be used in places where having to #include <algorithm> to get std::min() would be an unnecessary overkill. It's primarily meant to be used on builtin scalar types, thus the arguments are taken by value and not by reference.

NaNs passed in the value parameter are propagated.

template<class T>
T Corrade::Utility::max(T value, T max) constexpr new in Git master

Maximum.

The main purpose of this function is to be used in places where having to #include <algorithm> to get std::max() would be an unnecessary overkill. It's primarily meant to be used on builtin scalar types, thus the arguments are taken by value and not by reference.

NaNs passed in the value parameter are propagated.

template<class T>
T Corrade::Utility::abs(T a) constexpr new in Git master

Absolute value.

The main purpose of this function is to be used in places where having to #include <cmath> to get std::abs() would be an unnecessary overkill. It's primarily meant to be used on builtin scalar types, thus the arguments are taken by value and not by reference.

template<class T, std::size_t alignment = alignof(T)>
Containers::Array<T> Corrade::Utility::allocateAligned(std::size_t size) new in Git master

Allocate aligned memory and value-initialize it.

Template parameters
T Type of the returned array
alignment Allocation alignment, in bytes
Parameters
size Count of T items to allocate. If 0, no allocation is done.

Compared to the classic C std::malloc() or C++ new that commonly aligns only to 2*sizeof(void*), this function returns "overaligned" allocations, which is mainly useful for efficient SIMD operations. Example usage:

Containers::Array<__m256> avxVectors =
    Utility::allocateAligned<__m256>(size);

The alignment is implicitly alignof(T), but can be overridden with the alignment template parameter. When specified explicitly, it is expected to be a power-of-two value, at most 256 bytes and the total byte size being a multiple of the alignment:

Containers::Array<Matrix4> avxMatrices =
    Utility::allocateAligned<Matrix4, 32>(size);

The returned pointer is always aligned to at least the desired value, but the alignment can be also higher. For example, allocating a 2 MB buffer may result in it being aligned to the whole memory page, or small alignment values could get rounded up to the default 2*sizeof(void*) alignment.

The function is implemented using posix_memalign() on UNIX systems and _aligned_malloc() on Windows. On other platforms (such as Emscripten), if requested alignment is higher than platform's default alignment, the allocation is done via a classic std::malloc() with an alignment - 1 padding and the returned pointer is then patched to satisfy the alignment. In all cases the returned Containers::Array has a custom deleter, which for non-trivial types calls destructors on all types, and then either std::free() or, in case of Windows, _aligned_free() is used to deallocate the memory.

Array initialization

Like with Containers::Array, the returned array is by default value-initialized, which means that trivial types are zero-initialized and the default constructor is called on other types. Different behavior can be achieved with the following tags, compared to Containers::Array the initialization is performed separately from the allocation itself with either a loop or a call to std::memset().

  • allocateAligned(DefaultInitT, std::size_t) leaves trivial types uninitialized and calls the default constructor elsewhere. Because of the differing behavior for trivial types it's better to explicitly use either the ValueInit or NoInit variants instead.
  • allocateAligned(ValueInitT, std::size_t) is equivalent to the default case, zero-initializing trivial types and calling the default constructor elsewhere. Useful when you want to make the choice appear explicit.
  • allocateAligned(NoInitT, std::size_t) does not initialize anything. Useful for trivial types when you'll be overwriting the contents anyway, for non-trivial types this is the dangerous option and you need to call the constructor on all elements manually using placement new, std::uninitialized_copy() or similar — see the function docs for an example.

template<class T, std::size_t alignment = alignof(T)>
Containers::Array<T> Corrade::Utility::allocateAligned(DefaultInitT, std::size_t size) new in Git master

Allocate aligned memory and default-initialize it.

Compared to allocateAligned(std::size_t), trivial types are not initialized and default constructor is called otherwise. Because of the differing behavior for trivial types it's better to explicitly use either the allocateAligned(ValueInitT, std::size_t) or the allocateAligned(NoInitT, std::size_t) variant instead.

Implemented via allocateAligned(NoInitT, std::size_t) with a loop calling the constructors on the returned allocation in case of non-trivial types.

template<class T, std::size_t alignment = alignof(T)>
Containers::Array<T> Corrade::Utility::allocateAligned(ValueInitT, std::size_t size) new in Git master

Allocate aligned memory and value-initialize it.

Same as allocateAligned(std::size_t), just more explicit. Implemented via allocateAligned(NoInitT, std::size_t) with either a std::memset() or a loop calling the constructors on the returned allocation.

template<class T, std::size_t alignment = alignof(T)>
Containers::Array<T> Corrade::Utility::allocateAligned(NoInitT, std::size_t size) new in Git master

Allocate aligned memory and leave it uninitialized.

Compared to allocateAligned(std::size_t), the memory is left in an unitialized state. For trivial types is equivalent to allocateAligned(DefaultInitT, std::size_t). For non-trivial types, destruction is always done using a custom deleter that explicitly calls the destructor on all elements — which means that for non-trivial types you're expected to construct all elements using placement new (or for example std::uninitialized_copy()) in order to avoid calling destructors on uninitialized memory:

struct Foo {
    explicit Foo(int) {}
    
};

Containers::Array<Foo> data = Utility::allocateAligned<Foo>(NoInit, 5);

int index = 0;
for(Foo& f: data) new(&f) Foo{index++};

template<class T>
T&& Corrade::Utility::forward(typename std::remove_reference<T>::type& t) constexpr noexcept new in Git master

Forward an l-value.

Returns static_cast<T&&>(t). Equivalent to std::forward(), which is used to implement perfect forwarding, but without the #include <utility> dependency and guaranteed to be constexpr even in C++11.

template<class T>
T&& Corrade::Utility::forward(typename std::remove_reference<T>::type&& t) constexpr noexcept new in Git master

Forward an r-value.

Returns static_cast<T&&>(t). Equivalent to std::forward(), which is used to implement perfect forwarding, but without the #include <utility> dependency and guaranteed to be constexpr even in C++11.

template<class T>
std::remove_reference<T>::type&& Corrade::Utility::move(T&& t) constexpr noexcept new in Git master

Convert a value to an r-value.

Returns static_cast<typename std::remove_reference<T>::type&&>(t). Equivalent to std::move(), but without the #include <utility> dependency and guaranteed to be constexpr even in C++11.

template<class T>
void Corrade::Utility::swap(T& a, T& b) noexcept(…) new in Git master

Swap two values.

Swaps two values. Equivalent to std::swap(), but without the #include <utility> dependency, and without the internals delegating to std::move(), hurting debug performance. In order to keep supporting custom specializations, the usage pattern should be similar to the standard utility, i.e. with using Utility::swap:

MyClass& MyClass::operator=(MyClass&& other) noexcept {
    using Utility::swap;
    swap(other._member, _member);
    swap(other._another, _another);
    return *this;
}

template<std::size_t size, class T>
void Corrade::Utility::swap(T(&a)[size], T(&b)[size]) noexcept(…) new in Git master

Swap two arrays.

Does the same as swap(T&, T&), but for every array element.

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

Debug output operator.

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.