utils

Contents

utils#

namespace heph#
namespace utils#
namespace string#

Functions

std::string_view truncate(std::string_view str, std::string_view start_token, std::string_view end_token = std::string_view(""), bool include_end_token = true)#

Truncates a string by returning the segment between the first start token and the first end token strings, including the start token and the end token. If

Parameters:

include_end_token – is false, the end token will not be included in the result. For example, the following code will return ‘to/some/file’

constexpr auto str = "/path/to/some/file.txt";
constexpr auto start_token = "to";
constexpr auto end_token = ".txt";
constexpr auto truncated = truncate(str, start_token, end_token, false);
std::cout << truncated << '\n'; // $ to/some/file

std::string toSnakeCase(std::string_view camel_case)#

camelCase -> camel_case

std::string toScreamingSnakeCase(std::string_view camel_case)#

camelCase -> CAMEL_CASE

std::string toAsciiHex(const std::string &input)#

Convert a string to its ASCII hex representation. Examples: “ciao” -> “6369616f”

namespace heph
namespace utils
namespace timing#
class MockClock#

Public Types

using duration = std::chrono::steady_clock::duration#
using rep = std::chrono::steady_clock::rep#
using period = std::chrono::steady_clock::period#
using time_point = std::chrono::time_point<std::chrono::steady_clock>#

Public Functions

~MockClock() = default#
MockClock(const MockClock&) = delete#
MockClock &=delete operator= (const MockClock &)
MockClock(MockClock&&) = delete#
MockClock &=delete operator= (MockClock &&)

Public Static Attributes

static bool is_steady = true#

Public Static Functions

static inline time_point now()#
static inline void reset()#
static inline void setCurrentTime(time_point new_time)#
static inline void advance(duration delta)#
namespace heph
template<typename T, typename = void>
struct has_stream_operator : public std::false_type#
template<typename T>
struct has_stream_operator<T, std::void_t<decltype(std::declval<std::ostream&>() << std::declval<T>())>> : public std::false_type, public std::true_type#
namespace heph
namespace utils
class TerminationBlocker#
#include “hephaestus/utils/signal_handler.h”

Use this class to block until a signal is received.

NOTE: can be extended to call a generic callback when a signal is received. Usage:

int main() {
 // Do something
 TerminationBlocker::waitForInterrupt();
}
// Or
while (!TerminationBlocker::stopRequested()) {
// Do something
}

Public Static Functions

static bool stopRequested()#

Return true if a signal has been received, false otherwise.

static void waitForInterrupt()#

Blocks until a signal has been received.

template<StoppableAndWaitable T>
static void waitForInterruptOrAppCompletion(T &app)#

Wait returns when a signal is received or the app completes.

static void registerInterruptCallback(std::function<void()> &&interrupt_callback)#

Register a callback to be called when a signal is received. This function can be called together with others from this class. Only one callback can be registered at a time.

namespace heph
namespace utils

Functions

template<typename T>
std::string getTypeName()#

Return user-readable name for specified type.

std::string getHostName()#
std::optional<std::filesystem::path> getBinaryPath()#
namespace heph
namespace utils
namespace filesystem#
class ScopedPath#
#include “hephaestus/utils/filesystem/scoped_path.h”

This class allows to create a file that is removed when the class goes out of scope (RAII). This is very useful in tests to avoid having dangling files.

Public Functions

~ScopedPath()#
ScopedPath(const ScopedPath&) = delete#
ScopedPath(ScopedPath&&) = default#
ScopedPath &=delete operator= (const ScopedPath &)
ScopedPath &=default operator= (ScopedPath &&)
operator std::filesystem::path() const#
operator std::string() const#
operator std::string_view() const#

Public Static Functions

static ScopedPath createFile()#
static ScopedPath createDir()#
namespace heph
namespace utils
class StackTrace#
#include “hephaestus/utils/stack_trace.h”

Class to print a stack trace on crash. Usage: int main() { heph::utils::StackTrace stack_trace; … }.

Public Functions

StackTrace()#
~StackTrace()#

Public Static Functions

static std::string print()#
namespace heph
namespace utils
namespace timing
class StopWatch#
#include “hephaestus/utils/timing/stop_watch.h”

StopWatch provides functionalities to measure elapsed time in different intervals.

start stop start stop | lapse | lapse | | lapse | | elapsed | |___________________| |___________| accumulatedLapsDuration

Public Types

using ClockT = std::chrono::steady_clock#
using DurationT = ClockT::duration#
using NowFunctionPtr = std::chrono::steady_clock::time_point (*)()#

Public Functions

explicit StopWatch(NowFunctionPtr now_fn = &ClockT::now)#
void start()#

Start new lap. Does nothing if already ticking.

template<typename TargetDurationT = StopWatch::DurationT>
TargetDurationT stop()#

Stop current lap and pause accumulating time.

Returns:

Lap time, which is time elapsed between most recent start() and this stop() cast to the desired duration.

template<typename TargetDurationT = StopWatch::DurationT>
TargetDurationT lapse()#
Returns:

Currently running lap time, measured from the last call to lapse. The first lap is measured from the last start timestamp:

  • time elapsed from max[most recent start(), most recent lapse()] to now.

  • Cast to desired duration.

  • Doesn’t stop the watch.

template<typename TargetDurationT = StopWatch::DurationT>
TargetDurationT elapsed() const#
Returns:

Elapsed time since the last start() cast to the desired duration.

void reset()#

Stop and reset accumulated information.

DurationT accumulatedLapsDuration() const#
Returns:

Time accumulated across all laps since last reset().

std::optional<typename ClockT::time_point> initialStartTimestamp() const#
Returns:

Timestamp of the first start() call after the last reset().

std::size_t lapsCount() const#
Returns:

the number of times the timer has been stopped and re-started.

namespace heph
namespace utils
namespace timing
class WatchdogTimer#

Public Types

using Callback = std::function<void()>#

Public Functions

void start(std::chrono::milliseconds period, Callback &&callback)#

Start the watchdog timer with the specified period and callback. Once the timer starts it will loop indefinitely, calling the callback ever period milliseconds.

void stop()#

Stop the timer.

void pat()#

Pat the watchdog. If called the timer will not call the callback for the next period. This can be used to implement a dead-man switch.

namespace heph

Functions

template<typename ...Args>
void panic(internal::StringLiteralWithLocation<Args...> message, Args&&... args)#

User function to panic. Internally this throws a Panic exception.

Note: If macro DISABLE_EXCEPTIONS is defined, this function terminates printing the message. In this case, the whole code should be considered noexcept.

Parameters:
  • message – A message describing the error and what caused it

  • location – Location in the source where the error was triggered at

template<typename ...Args>
void panicIf(bool condition, internal::StringLiteralWithLocation<Args...> message, Args&&... args)#

User function to panic on condition lazily formatting the message. The whole code should be considered noexcept. Will use CHECK if DISABLE_EXCEPTIONS = ON.

Parameters:
  • condition – Condition whether to panic

  • message – A message describing the error and what caused it

  • location – Location in the source where the error was triggered at

class Panic : public std::runtime_error#
#include “hephaestus/utils/exception.h”

Exception class for panic situations This should not be instantiated directly, but rather through the panic or panicIf function.


Public Functions

explicit Panic(std::string message, const std::source_location &location = std::source_location::current())#

Constructs a panic exception.

Parameters:
  • message – Message describing the error cause

  • location – Source location where the error occurred

namespace heph

Functions

template<typename Sig>
bool operator==(const UniqueFunction<Sig> &func, std::nullptr_t)#
template<typename Sig>
bool operator==(std::nullptr_t, const UniqueFunction<Sig> &func)#
template<typename Sig>
bool operator!=(const UniqueFunction<Sig> &func, std::nullptr_t)#
template<typename Sig>
bool operator!=(std::nullptr_t, const UniqueFunction<Sig> &func)#
template<typename R, typename ...Args>
class UniqueFunction<R(Args...)>#

Public Functions

inline UniqueFunction() noexcept#
inline ~UniqueFunction() noexcept#
inline UniqueFunction(std::nullptr_t) noexcept#
template<detail::invocable<R, Args...> F>
inline UniqueFunction(F &&f)#
UniqueFunction(const UniqueFunction &other) noexcept = delete#
inline UniqueFunction(UniqueFunction &&other) noexcept#
UniqueFunction &=delete operator= (const UniqueFunction &other) noexcept
inline UniqueFunction &operator=(UniqueFunction &&other) noexcept#
template<detail::invocable<R, Args...> F>
inline UniqueFunction &operator=(F &&f) noexcept#
inline UniqueFunction &operator=(std::nullptr_t) noexcept#
inline R operator()(Args... args)#
inline R operator()(Args... args) const#
inline explicit operator bool() const noexcept#
namespace heph
namespace utils
namespace filesystem

Functions

std::optional<std::string> readFile(const std::filesystem::path &path)#

Read the whole content of the input file into a string.

Returns:

std::nullopt if the file doesn’t exists.

std::optional<std::vector<std::byte>> readBinaryFile(const std::filesystem::path &path)#

Read the whole content of the input binary file into a binary buffer.

Returns:

std::nullopt if the file doesn’t exists.

bool writeStringToFile(const std::filesystem::path &path, std::string_view content)#
bool writeBufferToFile(const std::filesystem::path &path, std::span<const std::byte> content)#
std::optional<std::filesystem::path> searchFilenameInPaths(const std::string &filename, const std::vector<std::filesystem::path> &paths)#
std::filesystem::path getThisExecutableFullPath()#

Return the full path of the executable calling this function.

namespace heph
template<class ...Ts>
struct Overloads : public Ts...#
#include “hephaestus/utils/variant.h”

A helper struct which allows you to easily branch on the type of alternative held by a variant:

std::visit(heph::Overloads { [](const &FirstAlternative& value) { // Code to be run if variant holds a value of type FirstAlternative. }, [](const &SecondAlternative& value) { // Code to be run if variant holds a value of type SecondAlternative. }, }, variant);

namespace heph
namespace utils
namespace format#

Functions

template<ArrayOrVectorType T>
inline std::string toString(const T &vec)#
template<OptionalType T>
inline std::string toString(const T &optional)#
template<UnorderedMapType T>
inline std::string toString(const T &umap)#
template<EnumType T>
inline std::string_view toString(T value)#
template<ChronoSystemClockType Clock, ChronoDurationType Duration>
inline std::string toString(const std::chrono::time_point<Clock, Duration> &timestamp)#
template<ChronoSteadyClockType Clock, ChronoDurationType Duration>
inline std::string toString(const std::chrono::time_point<Clock, Duration> &timestamp)#
namespace heph
namespace utils
namespace string

Functions

template<std::size_t SizeL, std::size_t SizeR>
StringLiteral<SizeL + SizeR - 1> operator+(const StringLiteral<SizeL> &lhs, const StringLiteral<SizeR> &rhs)#
template<std::size_t Size>
struct StringLiteral#
#include “hephaestus/utils/string/string_literal.h”

Helper to convert a string literal to a std::string_view. This for example allows to use a literal string “foo” as a non-type template parameter.

Public Members

std::array<char, Size> value#

Public Functions

constexpr StringLiteral(const char (&str)[Size])#
explicit constexpr StringLiteral(std::array<char, Size> v)#
explicit constexpr operator std::string_view() const noexcept#
auto operator<=>(const StringLiteral&) const noexcept = default#