Utilities¶
-
namespace util¶
Aliases
-
template<typename ...Args>
using num_traits_t = typename num_traits_of<Args...>::type¶ Convenience alias for
typename num_traits_of<Args...>::type.This alias simplifies the usage of
num_traits_of, allowing users to specify numeric traits more concisely.- Template Parameters:
Args – Template arguments to pass to
num_traits_of.
Typedefs
-
using HashValue_t = std::uint64_t¶
64-bit unsigned integer type used for storing FNV-1a hash values.
Functions
-
template<typename F>
ScopeExit<std::decay_t<F>> scope_exit(F &&f)¶ Factory function to create a ScopeExit object.
This function uses template argument deduction to simplify the creation of scope guards.
- Template Parameters:
F – The callable type.
- Parameters:
f – The callable to execute at the end of the scope.
- Returns:
A ScopeExit object.
-
template<typename F>
ScopeExit<std::decay_t<F>> defer(F &&f)¶ Factory function to create a ScopeExit object, aliased as ‘defer’.
This is an alias for
scope_exitthat mimics the ‘defer’ keyword found in other languages like Go or Swift.- Template Parameters:
F – The callable type.
- Parameters:
f – The callable to execute at the end of the scope.
- Returns:
A ScopeExit object.
-
inline std::vector<UserDataRecordInfo> list_user_data_records_stream(std::istream &in)¶
Scans an input stream for all valid user-data records.
- Parameters:
in – The stream to scan.
- Throws:
std::runtime_error – if stream size cannot be determined.
- Returns:
A list of discovered record metadata in file order.
-
inline std::vector<UserDataRecordInfo> list_user_data_records(const std::filesystem::path &filepath)¶
Lists all user-data records in a file.
- Throws:
std::ios_base::failure – if the file cannot be opened.
-
inline std::streampos find_header_start(std::istream &in, std::string_view keyword)¶
Finds the start of a record with the specified keyword.
- Parameters:
in – The stream to search.
keyword – The keyword to locate.
- Throws:
std::invalid_argument – if keyword is empty.
- Returns:
Absolute stream position, or -1 if not found.
-
template<typename UD>
void write_user_data_stream(std::ostream &out, const UD &data, std::string_view keyword = "USERDATA")¶ Serializes and writes a user-data record to a stream.
- Throws:
std::invalid_argument – if keyword is empty or too large.
-
template<typename UD>
void read_user_data_stream(std::istream &in, UD &data, std::string_view keyword = "USERDATA")¶ Reads a user-data record from a stream.
- Throws:
std::invalid_argument – if keyword is empty or too large.
std::runtime_error – if the header is malformed or keyword mismatches.
-
template<typename UD>
void write_user_data(const std::filesystem::path &filepath, const UD &data, std::string_view keyword = "USERDATA")¶ Appends a record to a file, ensuring the keyword is unique.
- Parameters:
filepath – Path to the target file.
data – Payload to append.
keyword – Record keyword.
- Throws:
std::runtime_error – if the keyword already exists in the file.
std::ios_base::failure – if file operations fail.
-
template<typename UD>
void read_user_data(const std::filesystem::path &filepath, UD &data, std::string_view keyword = "USERDATA")¶ Reads a record from a file by keyword.
- Parameters:
filepath – Path to the source file.
data – Destination object.
keyword – Record keyword.
- Throws:
std::runtime_error – if the keyword is not found.
std::ios_base::failure – if file operations fail.
Variables
-
constexpr std::string_view USER_DATA_HEADER = "USERDATA"¶
Magic string identifying the start of a user-data record.
-
constexpr std::uint8_t USER_DATA_VERSION = 1¶
Current binary format version.
-
constexpr std::size_t USER_DATA_MAX_KEYWORD_SIZE = 4096¶
Defensive limit for keyword length to prevent excessive allocations.
-
class Hash¶
- #include <hash.h>
Implements the FNV-1a non-cryptographic hash function (64-bit).
This class provides a convenient interface for computing FNV-1a hashes for various data types. It processes data byte-by-byte.
Note
This implementation hashes the raw memory representation of types. Therefore, hashes of multi-byte integers are endian-dependent and should not be expected to match across big-endian and little-endian systems.
Public Functions
-
inline constexpr Hash() noexcept¶
Initialize hash with the FNV offset basis.
-
template<typename T>
inline Hash &add(const T &value) noexcept¶ Adds a single trivially copyable value to the hash.
- Template Parameters:
T – The type of the value to add (must be trivially copyable).
- Parameters:
value – The value to add to the hash.
- Returns:
A reference to the current
Hashobject for chaining calls.
-
template<typename T>
inline Hash &add(const T *data, size_t count) noexcept¶ Adds a C-style array of trivially copyable values to the hash.
- Template Parameters:
T – The type of the array elements (must be trivially copyable).
- Parameters:
data – A pointer to the beginning of the array.
count – The number of elements in the array.
- Returns:
A reference to the current
Hashobject for chaining calls.
-
template<typename T>
inline Hash &add(std::span<const T> data) noexcept¶ Adds a contiguous sequence of values (span) to the hash.
This overload handles
std::vector,std::array, and C-arrays implicitly.- Template Parameters:
T – The type of the elements (must be trivially copyable).
- Parameters:
data – The span of data to add.
- Returns:
A reference to the current
Hashobject for chaining calls.
-
template<typename T>
inline Hash &add(const std::vector<T> &vec) noexcept¶ Adds a
std::vectorof trivially copyable values to the hash.This overload enables implicit usage with temporary vectors, where span deduction might fail.
- Template Parameters:
T – The type of the vector elements (must be trivially copyable).
- Parameters:
vec – The
std::vectorto add to the hash.- Returns:
A reference to the current
Hashobject for chaining calls.
-
inline Hash &add(std::string_view str) noexcept¶
Adds a string view to the hash.
- Parameters:
str – The string to add.
- Returns:
A reference to the current
Hashobject for chaining calls.
-
inline constexpr HashValue_t value() const noexcept¶
Gets the current hash value.
- Returns:
The current 64-bit FNV-1a hash value.
-
inline void reset() noexcept¶
Resets the hash to its initial FNV offset basis.
-
inline std::string encode_hex() const noexcept¶
Encodes the current hash value as a lowercase hexadecimal string.
- Returns:
A 16-character string representation of the hash.
Public Static Functions
-
static inline constexpr void add_bytes(HashValue_t &hash, const void *data, size_t len) noexcept¶
Adds a raw byte array to the FNV-1a hash.
- Parameters:
hash – The current hash value to update.
data – A pointer to the byte array.
len – The number of bytes to hash.
-
template<typename T>
static inline void add_one(HashValue_t &hash, const T &value) noexcept¶ Hashes a single trivially copyable value.
- Template Parameters:
T – The type of the value (must be trivially copyable).
- Parameters:
hash – The current hash value to update.
value – The value to hash.
-
template<typename T>
static inline void add_span(HashValue_t &hash, std::span<const T> data) noexcept¶ Hashes a span of trivially copyable values.
- Template Parameters:
T – The type of the elements (must be trivially copyable).
- Parameters:
hash – The current hash value to update.
data – The span of data to hash.
-
static inline void add_string(HashValue_t &hash, std::string_view str) noexcept¶
Hashes a string view.
- Parameters:
hash – The current hash value to update.
str – The string view to hash.
-
inline constexpr Hash() noexcept¶
-
template<typename T = double, typename S = std::uint32_t, typename U = std::uint64_t>
struct num_traits_of¶ - #include <numeric_traits.h>
Helper to extract or define NumericTraits from template arguments.
This primary template defines
typeasNumericTraits<T, S, U>with default types if not provided.- Template Parameters:
T – The value type. Defaults to
double.S – The size type. Defaults to
std::uint32_t.U – The count type. Defaults to
std::uint64_t.
-
template<typename ...Args>
struct num_traits_of<kakuhen::integrator::Point<Args...>>¶ - #include <point.h>
num_traits_of specialization for Point types.
Allows extracting NumericTraits from a Point type directly.
- Template Parameters:
Args – Template arguments of the Point (which is expected to be a NumericTraits).
-
template<typename T, typename S, typename U>
struct num_traits_of<NumericTraits<T, S, U>>¶ - #include <numeric_traits.h>
Specialization for when NumericTraits is already provided.
If the template argument is already a
NumericTraitstype, this specialization simply uses that type.- Template Parameters:
T – The value type.
S – The size type.
U – The count type.
-
template<typename T, typename S, typename U>
struct NumericTraits¶ - #include <numeric_traits.h>
Defines the numeric types used throughout the kakuhen classes.
This struct serves as a central place to define the primary data types for numerical calculations, sizing of dimensions, and counting of evaluations. This allows for easy customization of precision and range for different applications.
- Template Parameters:
T – The value type for integral results (must be floating point).
S – The size type for dimensions and array indices (must be integral).
U – The count type for number of evaluations or samples (must be integral).
-
template<typename F>
class ScopeExit¶ - #include <scope_exit.h>
RAII class that executes a function when it goes out of scope.
This utility is useful for ensuring that certain clean-up or restoration logic is performed regardless of how a block is exited (normal return, exception, etc.).
- Template Parameters:
F – The type of the callable to execute.
Public Functions
-
inline explicit ScopeExit(F &&f) noexcept(std::is_nothrow_move_constructible_v<F>)¶
Constructs a ScopeExit object with a given callable.
- Parameters:
f – The callable to execute on destruction.
-
inline ScopeExit(ScopeExit &&other) noexcept(std::is_nothrow_move_constructible_v<F>)¶
Move constructor. Transfers the callable and takes over responsibility.
- Parameters:
other – The other ScopeExit object.
-
inline ~ScopeExit() noexcept¶
Destructor. Executes the callable if it has not been released.
-
inline void release() noexcept¶
Prevents the callable from being executed when the object is destroyed.
-
template<typename T, std::size_t N>
class SmallVector¶ - #include <small_vector.h>
A small-capacity optimized vector for trivially copyable types.
SmallVector provides a vector-like interface but stores its first N elements in-place (on the stack or within the object itself). This avoids heap allocations for small collections. It is restricted to trivially copyable types to allow highly efficient memory operations like std::memcpy.
- Template Parameters:
T – The type of elements. Must be trivially copyable.
N – The number of elements to store inline. Must be greater than 0.
Public Functions
-
inline SmallVector() noexcept¶
Constructs an empty SmallVector with inline capacity N.
-
inline SmallVector(std::initializer_list<T> init)¶
Constructs a SmallVector with elements from an initializer list.
- Parameters:
init – Initializer list of elements.
-
inline ~SmallVector()¶
Destructor. Releases heap memory if it was allocated.
-
inline SmallVector(const SmallVector &other)¶
Copy constructor.
- Parameters:
other – The SmallVector to copy from.
-
inline SmallVector &operator=(const SmallVector &other)¶
Copy assignment operator.
- Parameters:
other – The SmallVector to copy from.
- Returns:
Reference to this SmallVector.
-
inline SmallVector(SmallVector &&other) noexcept¶
Move constructor.
- Parameters:
other – The SmallVector to move from.
-
inline SmallVector &operator=(SmallVector &&other) noexcept¶
Move assignment operator.
- Parameters:
other – The SmallVector to move from.
- Returns:
Reference to this SmallVector.
-
inline reference operator[](size_type i) noexcept¶
Returns a reference to the element at index i.
-
inline const_reference operator[](size_type i) const noexcept¶
Returns a const reference to the element at index i.
-
inline reference at(size_type i)¶
Returns a reference to the element at index i with bounds checking.
-
inline const_reference at(size_type i) const¶
Returns a const reference to the element at index i with bounds checking.
-
inline reference front() noexcept¶
Returns a reference to the first element.
-
inline const_reference front() const noexcept¶
Returns a const reference to the first element.
-
inline reference back() noexcept¶
Returns a reference to the last element.
-
inline const_reference back() const noexcept¶
Returns a const reference to the last element.
-
inline pointer data() noexcept¶
Returns a pointer to the underlying data array.
-
inline const_pointer data() const noexcept¶
Returns a const pointer to the underlying data array.
-
inline bool empty() const noexcept¶
Returns true if the vector is empty.
-
inline size_type size() const noexcept¶
Returns the number of elements in the vector.
-
inline size_type capacity() const noexcept¶
Returns the current capacity of the vector.
-
inline void reserve(size_type new_cap)¶
Ensures that the capacity is at least new_cap.
- Parameters:
new_cap – The desired minimum capacity.
-
inline void shrink_to_fit()¶
Reduces capacity to match size, moving back to inline storage if possible.
-
inline void clear() noexcept¶
Removes all elements. Heap memory is retained.
-
template<typename ...Args>
inline reference emplace_back(Args&&... args)¶ Constructs an element in-place at the end.
-
inline void pop_back() noexcept¶
Removes the last element.
-
inline void resize(size_type new_size)¶
Resizes the vector to new_size.
- Parameters:
new_size – The new number of elements.
-
inline void resize(size_type new_size, const T &value)¶
Resizes the vector to new_size, filling new elements with value.
- Parameters:
new_size – The new number of elements.
value – The value to fill new elements with.
-
template<std::size_t M>
inline bool operator==(const SmallVector<T, M> &other) const noexcept¶ Compares two SmallVectors for equality.
-
template<std::size_t M>
inline bool operator!=(const SmallVector<T, M> &other) const noexcept¶ Compares two SmallVectors for inequality.
Public Static Functions
-
static inline constexpr size_type inline_capacity() noexcept¶
Returns the fixed inline capacity.
-
struct UserDataRecordInfo¶
- #include <user_data.h>
Metadata for a discovered user-data record.
-
namespace accumulator¶
Note
This implementation is not thread-safe.
Typedefs
-
template<typename T = double, AccumAlgo Algo = AccumAlgo::TwoSum>
using Accumulator = typename detail::AccumulatorSelector<Algo, T>::type¶ Alias for selecting a specific accumulator implementation.
- Template Parameters:
T – The floating-point type. Defaults to double.
Algo – The accumulation algorithm. Defaults to AccumAlgo::TwoSum.
Enums
-
template<typename Derived, typename T>
class AccumulatorBase¶ - #include <accumulator.h>
Base class for various floating-point summation algorithms using CRTP.
This class provides a common interface for different accumulation strategies to sum floating-point numbers with varying degrees of precision.
- Template Parameters:
Derived – The derived accumulator class.
T – The floating-point type to accumulate.
Operators
-
inline constexpr Derived &operator+=(const T &value) noexcept¶
Overloads the += operator to add a value.
- Parameters:
value – The value to add.
- Returns:
A reference to the derived object.
-
inline constexpr operator T() const noexcept¶
Conversion operator to allow the accumulator to be used as its underlying value type.
constexpr Derived& operator=(T value) noexcept { derived().reset_impl(value); return derived(); }@brief Assignment operator to reset the accumulator to a value. @param value The value to reset to. @return A reference to the derived object. ‍/
/*!
Serialization
-
inline void serialize(std::ostream &out, bool with_type = false) const noexcept¶
Serializes the accumulator to an output stream.
- Parameters:
out – The output stream.
with_type – Whether to include type information.
-
inline void deserialize(std::istream &in, bool with_type = false)¶
Deserializes the accumulator from an input stream.
- Parameters:
in – The input stream.
with_type – Whether to verify type information.
-
template<typename T>
class KahanAccumulator : public kakuhen::util::accumulator::AccumulatorBase<KahanAccumulator<T>, T>¶ - #include <accumulator.h>
Implements Kahan summation algorithm for improved precision.
The Kahan summation algorithm (compensated summation) keeps track of a running compensation for lost low-order bits.
- Template Parameters:
T – The floating-point type.
-
template<typename T>
class NaiveAccumulator : public kakuhen::util::accumulator::AccumulatorBase<NaiveAccumulator<T>, T>¶ - #include <accumulator.h>
Implements naive floating-point summation.
This accumulator performs straightforward summation (
sum_ += value). It is the simplest and fastest method but can suffer from significant precision loss.- Template Parameters:
T – The floating-point type.
-
template<typename T>
class NeumaierAccumulator : public kakuhen::util::accumulator::AccumulatorBase<NeumaierAccumulator<T>, T>¶ - #include <accumulator.h>
Implements Neumaier’s improved Kahan summation algorithm.
Neumaier’s algorithm improves upon Kahan summation for cases where the added term is larger than the running sum.
- Template Parameters:
T – The floating-point type.
-
template<typename T>
class TwoSumAccumulator : public kakuhen::util::accumulator::AccumulatorBase<TwoSumAccumulator<T>, T>¶ - #include <accumulator.h>
Implements the Two-Sum algorithm for high-precision summation.
The Two-Sum algorithm calculates an exact error term for every addition. This class separates the fast path addition from the renormalization step for maximum performance.
- Template Parameters:
T – The floating-point type.
-
namespace detail¶
Functions
-
template<typename T = double>
constexpr void two_sum(const T &a, const T &b, T &s, T &t) noexcept¶ Two-Sum algorithm for exact summation of two numbers.
This function computes the sum \( s = a + b \) rounded to the nearest floating-point number, and the exact error \( t \) such that \( a + b = s + t \) holds exactly in floating-point arithmetic.
Compared to the original “FastTwoSum” algorithm by Dekker and Kahan, this version (by Knuth and Møller) requires no comparisons to determine the relative magnitude of \( a \) and \( b \), making it faster on modern architectures. It works with any radix.
- Template Parameters:
T – The floating-point type (defaults to double).
- Parameters:
a – First number to add.
b – Second number to add.
s – Output parameter: the rounded sum \( a + b \).
t – Output parameter: the exact rounding error.
-
template<typename T = double>
-
template<typename T = double, AccumAlgo Algo = AccumAlgo::TwoSum>
-
namespace algorithm¶
Functions
-
template<class RandomIt, class T, class Compare>
constexpr RandomIt lower_bound(RandomIt first, RandomIt last, const T &value, Compare comp)¶ Algorithms and utilities.
Branch-friendly lower_bound variant using a “staircase” search.
This is an alternative to
std::lower_boundthat can reduce branch mispredictions on some workloads by keeping the search direction monotonic. It requires random-access iterators for efficient indexing.Note
Based on: https://mhdm.dev/posts/sb_lower_bound/
- Template Parameters:
RandomIt – Random-access iterator type.
T – Value type to compare.
Compare – Strict weak ordering comparator.
- Parameters:
first – Iterator to the first element.
last – Iterator to one past the last element.
value – The value to search for.
comp – Comparator such that
comp(a, b)is true ifa < b.
- Returns:
Iterator to the first element not less than
value.
-
template<class RandomIt, class T, class Compare>
constexpr RandomIt upper_bound(RandomIt first, RandomIt last, const T &value, Compare comp)¶ Branch-friendly upper_bound variant using a “staircase” search.
This is an alternative to
std::upper_boundthat can reduce branch mispredictions on some workloads by keeping the search direction monotonic. It requires random-access iterators for efficient indexing.- Template Parameters:
RandomIt – Random-access iterator type.
T – Value type to compare.
Compare – Strict weak ordering comparator.
- Parameters:
first – Iterator to the first element.
last – Iterator to one past the last element.
value – The value to search for.
comp – Comparator such that
comp(a, b)is true ifa < b.
- Returns:
Iterator to the first element greater than
value.
-
template<class RandomIt, class T, class Compare>
constexpr RandomIt lower_bound_with_hint(RandomIt first, RandomIt last, RandomIt hint, const T &value, Compare comp)¶ lower_bound with a starting hint using exponential search.
Performs an exponential search around the hint to quickly bound the range, then performs a branch-friendly binary search. This is significantly faster than a full search when the hint is near the correct position.
- Template Parameters:
RandomIt – Random-access iterator type.
T – Value type to compare.
Compare – Strict weak ordering comparator.
- Parameters:
first – Iterator to the first element.
last – Iterator to one past the last element.
hint – Hint iterator (clamped to [first, last-1] if necessary).
value – The value to search for.
comp – Comparator such that
comp(a, b)is true ifa < b.
- Returns:
Iterator to the first element not less than
value.
-
template<class RandomIt, class T, class Compare>
constexpr RandomIt upper_bound_with_hint(RandomIt first, RandomIt last, RandomIt hint, const T &value, Compare comp)¶ upper_bound with a starting hint using exponential search.
- Template Parameters:
RandomIt – Random-access iterator type.
T – Value type to compare.
Compare – Strict weak ordering comparator.
- Parameters:
first – Iterator to the first element.
last – Iterator to one past the last element.
hint – Hint iterator (clamped to [first, last-1] if necessary).
value – The value to search for.
comp – Comparator such that
comp(a, b)is true ifa < b.
- Returns:
Iterator to the first element greater than
value.
-
template<class RandomIt, class T, class Compare>
-
namespace detail¶
Functions
-
inline std::uint64_t read_u64(const char *ptr)¶
Reads a 64-bit unsigned integer using the library’s native binary format.
-
inline bool to_size(std::uint64_t in, std::size_t &out)¶
Safely converts u64 to size_t. Returns false on narrowing overflow.
-
inline bool checked_add(std::size_t a, std::size_t b, std::size_t &out)¶
Overflow-safe addition for size values.
-
inline constexpr std::size_t fixed_header_size()¶
Fixed header size in bytes: magic + version + key_size + payload_size.
-
inline bool try_parse_header(std::istream &in, UserDataRecordInfo &info, std::size_t &record_size)¶
Attempts to read and validate a record header at the current stream position.
On failure this function leaves the stream in a failed state; callers that continue scanning should clear the stream state before the next operation.
- Returns:
True if a valid header was parsed, filling
infoandrecord_size.
-
inline std::uint64_t read_u64(const char *ptr)¶
-
namespace math¶
Functions
-
template<typename T>
constexpr T abs(T x)¶ Computes the absolute value of a number.
This function provides a compile-time (constexpr) compatible absolute value calculation, which is necessary because
std::absis notconstexpruntil C++23.- Template Parameters:
T – The numeric type.
- Parameters:
x – The value.
- Returns:
The absolute value of x.
-
template<typename T>
constexpr T sq(const T &x) noexcept¶ Computes the square of a number.
A convenience function for
x * x. This is often more efficient and readable thanstd::pow(x, 2).- Template Parameters:
T – The numeric type.
- Parameters:
x – The value to square.
- Returns:
The square of x.
-
template<typename T>
constexpr int sgn(const T &val) noexcept¶ Extracts the sign of a value.
- Template Parameters:
T – The numeric type.
- Parameters:
val – The value to check.
- Returns:
-1 if val < 0, 1 if val > 0, 0 if val == 0.
-
template<typename T>
constexpr const T &min(const T &a, const T &b) noexcept¶ Returns the smaller of two values.
Provided as a
constexpralternative tostd::min.- Template Parameters:
T – The value type.
- Parameters:
a – First value.
b – Second value.
- Returns:
The smaller of a and b.
-
template<typename T>
constexpr const T &max(const T &a, const T &b) noexcept¶ Returns the larger of two values.
Provided as a
constexpralternative tomax.- Template Parameters:
T – The value type.
- Parameters:
a – First value.
b – Second value.
- Returns:
The larger of a and b.
-
template<typename T, typename Integer>
constexpr T ipow(T base, Integer exp)¶ Computes base raised to the power of exp using binary exponentiation.
This function uses the “exponentiation by squaring” algorithm, which achieves the result in O(log exp) multiplications. This is generally much faster than
std::powfor integer exponents.- Template Parameters:
T – The base type.
Integer – The exponent type (must be integral).
- Parameters:
base – The base value.
exp – The integer exponent.
- Returns:
The result of base^exp.
-
template<typename T>
constexpr bool nearly_equal(T a, T b, int max_ulps = 4, T abs_tol = std::numeric_limits<T>::epsilon())¶ Checks if two floating-point numbers are nearly equal.
This implementation uses a relative error comparison which is significantly faster than
std::nextafterand friendly to SIMD optimizations.The check performed is effectively: \( |a - b| \le \max(\text{abs\_tol}, \max(|a|, |b|) \times \epsilon \times \text{max\_ulps}) \)
- Template Parameters:
T – The floating-point type (e.g., float, double).
- Parameters:
a – The first number to compare.
b – The second number to compare.
max_ulps – The maximum number of “epsilon steps” allowed. Defaults to 4.
abs_tol – The absolute tolerance for comparisons near zero. Defaults to machine epsilon.
- Returns:
True if the numbers are nearly equal, false otherwise.
-
template<typename T>
-
namespace printer¶
Enums
-
class JSONPrinter : public kakuhen::util::printer::PrinterBase<JSONPrinter>¶
- #include <printer.h>
A concrete printer class that generates JSON output.
This class inherits from
PrinterBaseand implements theprint_one_implmethod to format output as JSON. It supports objects, arrays, and basic data types, handling JSON-specific escaping and formatting (indentation).Public Functions
-
inline void reset()¶
Resets the JSON printer to its initial state.
-
inline void break_line()¶
Inserts a line break and indentation if
indent_is greater than 0.
-
template<Context C>
inline void begin(std::string_view key = {})¶ Begins a new JSON object or array.
- Template Parameters:
C – The context type (Context::OBJECT or Context::ARRAY).
- Parameters:
key – An optional key for the object member or array.
-
inline void reset()¶
-
template<typename Derived>
class PrinterBase¶ - #include <printer.h>
Base class for printers, using CRTP.
This class provides a generic interface for printing various types of data to an output stream. It uses the Curiously Recurring Template Pattern (CRTP) to allow derived classes to implement specific printing formats (e.g., JSON, XML) while sharing common functionalities.
- Template Parameters:
Derived – The derived printer class.
Public Functions
-
inline explicit PrinterBase(std::ostream &os)¶
Constructs a PrinterBase.
- Parameters:
os – The output stream to print to.
-
template<typename T>
inline PrinterBase &operator<<(const T &value)¶ Stream operator overload.
- Template Parameters:
T – The type of the value to print.
- Parameters:
value – The value to print.
- Returns:
A reference to the derived printer object.
-
inline void reset()¶
Resets the internal state of the printer.
This typically clears any accumulated context or formatting states.
-
inline void break_line()¶
Inserts a line break or formatting specific to the printer.
For some printers (e.g., JSON), this might involve adding indentation.
-
template<Context C>
inline void begin(std::string_view key = {})¶ Begins a new context (e.g., object or array).
- Template Parameters:
C – The context type (Context::OBJECT or Context::ARRAY).
- Parameters:
key – An optional key associated with the context (e.g., for JSON object members).
-
template<Context C>
inline void end(bool do_break = false)¶ Ends the current context.
- Template Parameters:
C – The context type.
- Parameters:
do_break – Whether to force a line break after ending the context.
-
template<typename T>
inline void print_one(std::string_view key, T &&value)¶ Prints a single key-value pair or a standalone value.
The actual printing logic is implemented in the derived class.
- Template Parameters:
T – The type of the value to print.
- Parameters:
key – The key associated with the value (can be empty for standalone values).
value – The value to print.
-
template<typename Iterator, typename PreRange = std::initializer_list<typename std::iterator_traits<Iterator>::value_type>, typename PostRange = std::initializer_list<typename std::iterator_traits<Iterator>::value_type>>
inline void print_array(std::string_view key, Iterator first, Iterator last, const PreRange &prepend = {}, const PostRange &append = {})¶ Prints a range of elements as an array.
This function iterates through a range defined by iterators and prints each element. It can optionally prepend and append elements.
- Template Parameters:
Iterator – The iterator type for the range.
PreRange – Type of initializer list for prepended elements.
PostRange – Type of initializer list for appended elements.
- Parameters:
key – An optional key for the array.
first – An iterator to the beginning of the range.
last – An iterator to the end of the range.
prepend – An initializer list of elements to print before the range.
append – An initializer list of elements to print after the range.
-
template<typename Array, typename PreRange = std::initializer_list<typename Array::value_type>, typename PostRange = std::initializer_list<typename Array::value_type>>
inline void print_array(std::string_view key, const Array &a, const PreRange &prepend = {}, const PostRange &append = {})¶ Prints an array-like container.
Overload that takes an array-like container (e.g.,
std::vector,NDArray).- Template Parameters:
Array – The array-like container type.
PreRange – Type of initializer list for prepended elements.
PostRange – Type of initializer list for appended elements.
- Parameters:
key – An optional key for the array.
a – The array-like container.
prepend – An initializer list of elements to print before the array.
append – An initializer list of elements to print after the array.
-
template<typename T, typename PreRange = std::initializer_list<T>, typename PostRange = std::initializer_list<T>>
inline void print_array(std::string_view key, const T *ptr, std::size_t count, const PreRange &prepend = {}, const PostRange &append = {})¶ Prints a C-style array (pointer and count).
Overload that takes a pointer to the first element and a count.
- Template Parameters:
T – The type of elements in the array.
PreRange – Type of initializer list for prepended elements.
PostRange – Type of initializer list for appended elements.
- Parameters:
key – An optional key for the array.
ptr – Pointer to the first element.
count – The number of elements to print.
prepend – An initializer list of elements to print before the array.
append – An initializer list of elements to print after the array.
-
class JSONPrinter : public kakuhen::util::printer::PrinterBase<JSONPrinter>¶
-
namespace serialize¶
Core serialization routines
-
inline void write_bytes(std::ostream &out, const void *data, std::size_t size)¶
Writes a specified number of bytes to an output stream.
- Parameters:
out – The output stream to write to.
data – A pointer to the data buffer.
size – The number of bytes to write.
-
inline void read_bytes(std::istream &in, void *data, std::size_t size)¶
Reads a specified number of bytes from an input stream.
- Parameters:
in – The input stream to read from.
data – A pointer to the buffer where the read bytes will be stored.
size – The number of bytes to read.
- Throws:
std::runtime_error – if the expected number of bytes cannot be read.
Size serialization
-
inline void serialize_size(std::ostream &out, std::size_t size)¶
Serializes a size value using a stable 64-bit unsigned integer format.
-
inline void deserialize_size(std::istream &in, std::size_t &size)¶
Deserializes a size value from a 64-bit unsigned integer format.
Generic serialization
-
template<typename T>
void serialize_one(std::ostream &out, const T &obj)¶ Serializes a single object to an output stream.
Dispatches to:
Special handling for
std::string.obj.serialize(out)if the type satisfiesHasSerialize.Byte-wise copy for trivially copyable non-pointer types.
- Template Parameters:
T – The type of the object to serialize.
- Parameters:
out – The output stream to write to.
obj – The object to serialize.
-
template<typename T>
void deserialize_one(std::istream &in, T &obj)¶ Deserializes a single object from an input stream.
Dispatches to:
Special handling for
std::string.obj.deserialize(in)if the type satisfiesHasDeserialize.Byte-wise copy for trivially copyable non-pointer types.
- Template Parameters:
T – The type of the object to deserialize.
- Parameters:
in – The input stream to read from.
obj – The object to deserialize into.
Array and Range serialization
-
template<typename T>
void serialize_array(std::ostream &out, const T *ptr, std::size_t count)¶ Serializes a C-style array of objects.
Uses optimized byte-wise write if the element type is trivially copyable.
- Template Parameters:
T – The type of elements in the array.
- Parameters:
out – The output stream.
ptr – Pointer to the start of the array.
count – Number of elements.
-
template<typename T>
void deserialize_array(std::istream &in, T *ptr, std::size_t count)¶ Deserializes a C-style array of objects.
Uses optimized byte-wise read if the element type is trivially copyable.
-
template<typename Iterator>
void serialize_range(std::ostream &out, Iterator first, Iterator last)¶ Serializes a range of objects defined by iterators.
-
template<typename Iterator>
void deserialize_range(std::istream &in, Iterator first, Iterator last)¶ Deserializes a range of objects defined by iterators.
-
template<typename Container>
void serialize_container(std::ostream &out, const Container &container)¶ Serializes the contents of a container.
Provides optimized paths for contiguous containers of POD types (e.g.
std::vector<double>). Special handling ensuresstd::vector<bool>is treated correctly via iteration.
-
inline void write_bytes(std::ostream &out, const void *data, std::size_t size)¶
-
namespace type¶
Type Identification
-
enum class TypeId : uint8_t¶
Enum class defining identifiers for various supported types.
This enum lists all the types supported by the type identification system. The
UNKNOWNvalue is used for types that are not explicitly supported.Values:
-
enumerator UNKNOWN¶
-
enumerator DEFINE_ENUM_ENTRY¶
-
enumerator BOOL¶
-
enumerator INT8¶
-
enumerator INT16¶
-
enumerator INT32¶
-
enumerator INT64¶
-
enumerator UINT8¶
-
enumerator UINT16¶
-
enumerator UINT32¶
-
enumerator UINT64¶
-
enumerator FLOAT¶
-
enumerator DOUBLE¶
-
enumerator UNKNOWN¶
-
template<typename T>
constexpr TypeId get_type_id()¶ Gets the
TypeIdcorresponding to a given typeT.This function maps a C++ type to its corresponding
TypeIdenum value. It supports standard arithmetic types and their fixed-width integer equivalents.- Template Parameters:
T – The type to identify.
- Returns:
The
TypeIdcorresponding toT, orTypeId::UNKNOWNif not found.
-
template<typename T>
constexpr int16_t get_type_or_size()¶ Gets the
TypeIdas a signed 16-bit integer, or the negative size of the type.If the type is recognized, its
TypeIdis returned as a positive integer. If the type is unknown, its size (in bytes) is returned as a negative integer. This is useful for basic compatibility checking during serialization.Note
This function returns an
int16_t. If the type is unknown and its size exceeds 32767 bytes (32 KB), the result will overflow/wrap, potentially leading to incorrect compatibility checks.- Template Parameters:
T – The type to query.
- Returns:
The
TypeIdor negative size ofT.
Type Mapping
-
template<TypeId ID>
using type_from_id_t = typename TypeFromId<ID>::type¶ Alias helper for
TypeFromId<ID>::type.- Template Parameters:
ID – The
TypeIdto map.
String Conversion
-
constexpr std::string_view to_string(TypeId id)¶
Converts a
TypeIdto its string representation.- Parameters:
id – The
TypeIdto convert.- Returns:
A string view of the type name (e.g., “INT32”), or “UNKNOWN”.
-
template<typename T>
constexpr std::string_view get_type_name()¶ Gets the string name of a type
T.This function is a convenience wrapper around
get_type_idandto_string.- Template Parameters:
T – The type to query.
- Returns:
A string view of the type name.
-
template<TypeId>
struct TypeFromId¶ - #include <type.h>
Helper struct to map a
TypeIdback to a C++ type.The
typemember alias will bevoidif the ID is unknown orTypeId::UNKNOWN. Specializations are generated for each supported type.- Template Parameters:
ID – The
TypeIdto map.
-
enum class TypeId : uint8_t¶
-
template<typename ...Args>