General Utility Library for C++14  2.7
Classes | Typedefs | Enumerations | Functions | Variables
gul14 Namespace Reference

Detailed Description

Namespace gul14 contains all functions and classes of the General Utility Library.

Classes

class  ConvertingStringView
 A string view that can automatically convert numbers into strings. More...
 
class  FinalAction
 FinalAction allows us to execute something if the FinalAction object leaves the scope. More...
 
class  HexdumpParameterForward
 Helper object used to enable a convenient syntax to dump things to a stream. More...
 
class  optional
 A class template that can either contain a value of a certain type or not. More...
 
class  optional< T & >
 A class template that can either contain a value of a certain type or not. More...
 
class  SlidingBuffer
 A circular data buffer of (semi-)fixed capacity to which elements can be added at the front or at the back. More...
 
class  SlidingBufferExposed
 A variant of SlidingBuffer that exposes the underlying container through its iterator interface. More...
 
class  SmallVector
 A resizable container with contiguous storage that can hold a specified number of elements without allocating memory on the heap. More...
 
class  span
 A view to a contiguous sequence of objects. More...
 
struct  MinMax
 Object that is designed to holds two values: minimum and maximum of something. More...
 
class  StandardDeviationMean
 A struct holding a standard deviation and a mean value. More...
 
class  basic_string_view
 A view to a contiguous sequence of chars or char-like objects. More...
 
struct  IsContainerLike
 Helper type trait object to determine if a type is a container. More...
 
class  Trigger
 A class that allows sending triggers and waiting for them across different threads. More...
 
class  FailToInstantiate
 A helper class to debug types. More...
 

Typedefs

template<typename T >
using BitFunctionReturnType = std::enable_if_t< std::is_integral< T >::value and not std::is_same< std::decay_t< T >, bool >::value, std::decay_t< T > >
 Return type of the bit manipulation functions. More...
 
using statistics_result_type = double
 Type used to return statistic properties.
 
using string_view = basic_string_view< char >
 A view to a contiguous sequence of chars. More...
 
using u16string_view = basic_string_view< char16_t >
 A view to a contiguous sequence of char16_ts. More...
 
using u32string_view = basic_string_view< char32_t >
 A view to a contiguous sequence of char32_ts. More...
 
using wstring_view = basic_string_view< wchar_t >
 A view to a contiguous sequence of wchar_ts. More...
 

Enumerations

enum class  ShrinkBehavior { keep_front_elements , keep_back_elements }
 Determine how a SlidingBuffer handles decreases of its size. More...
 

Functions

template<typename T = unsigned, typename ReturnT = BitFunctionReturnType<T>>
constexpr auto bit_set (unsigned bit) noexcept -> ReturnT
 Set a bit in an integral type. More...
 
template<typename T , typename ReturnT = BitFunctionReturnType<T>>
constexpr auto bit_set (T previous, unsigned bit) noexcept -> ReturnT
 Set a bit in an integral value. More...
 
template<typename T , typename ReturnT = BitFunctionReturnType<T>>
constexpr auto bit_reset (T previous, unsigned bit) noexcept -> ReturnT
 Reset a bit in an integral value. More...
 
template<typename T , typename ReturnT = BitFunctionReturnType<T>>
constexpr auto bit_flip (T previous, unsigned bit) noexcept -> ReturnT
 Flip a bit in an integral value. More...
 
template<typename T >
constexpr bool bit_test (T bits, unsigned bit) noexcept
 Test a bit in an integral value. More...
 
constexpr char lowercase_ascii (char c) noexcept
 Return the ASCII lowercase equivalent of the given character (or the unchanged character, if it is not an ASCII letter). More...
 
GUL_EXPORT std::string lowercase_ascii (gul14::string_view str)
 Return a copy of the given string in which all ASCII characters are replaced by their lowercase equivalents. More...
 
GUL_EXPORT std::string & lowercase_ascii_inplace (std::string &str) noexcept
 Replace all ASCII characters in a string by their lowercase equivalents. More...
 
constexpr char uppercase_ascii (char c) noexcept
 Return the ASCII uppercase equivalent of the given character (or the unchanged character, if it is not an ASCII letter). More...
 
GUL_EXPORT std::string uppercase_ascii (gul14::string_view str)
 Return a copy of the given string in which all ASCII characters are replaced by their uppercase equivalents. More...
 
GUL_EXPORT std::string & uppercase_ascii_inplace (std::string &str) noexcept
 Replace all ASCII characters in a string by their uppercase equivalents. More...
 
std::string cat ()
 Efficiently concatenate an arbitrary number of strings and numbers. More...
 
std::string cat (const ConvertingStringView &s)
 
GUL_EXPORT std::string cat (const ConvertingStringView &s1, const ConvertingStringView &s2)
 
GUL_EXPORT std::string cat (const ConvertingStringView &s1, const ConvertingStringView &s2, const ConvertingStringView &s3)
 
GUL_EXPORT std::string cat (std::initializer_list< ConvertingStringView > pieces)
 
template<typename... Args, typename = std::enable_if_t<(sizeof...(Args) > 3)>>
std::string cat (const Args &... args)
 
GUL_EXPORT std::string escape (string_view in)
 Create a new string that looks like an ASCII-only C string literal of the input string. More...
 
GUL_EXPORT std::string unescape (string_view in)
 Evaluate a string with escaped characters to get the original string back. More...
 
template<typename F >
FinalAction< typename std::decay_t< F > > finally (F &&f) noexcept
 finally() - convenience function to generate a FinalAction More...
 
template<typename IntTypeA , typename IntTypeB >
constexpr auto gcd (IntTypeA a, IntTypeB b)
 Calculate the greatest common divisor of two integers using the Euclidean algorithm. More...
 
template<typename IntTypeA , typename IntTypeB >
constexpr auto lcm (IntTypeA a, IntTypeB b)
 Calculate the least common multiple of two integers. More...
 
template<typename IteratorT , typename = std::enable_if_t<detail::IsHexDumpIterator<IteratorT>::value>>
std::string hexdump (IteratorT begin, IteratorT end, string_view prompt="")
 Generate a hexdump of a data range and return it as a string. More...
 
template<typename ContainerT , typename = std::enable_if_t<detail::IsHexDumpContainer<ContainerT>::value>>
std::string hexdump (const ContainerT &cont, string_view prompt="")
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename IteratorT , typename = std::enable_if_t<detail::IsHexDumpIterator<IteratorT>::value>>
HexdumpParameterForward< const IteratorT > hexdump_stream (const IteratorT &begin, const IteratorT &end, std::string prompt="")
 Generate a hexdump of a data range that can be efficiently written to a stream using operator<<. More...
 
template<typename ContainerT , typename = std::enable_if_t<detail::IsHexDumpContainer<ContainerT>::value>>
HexdumpParameterForward< const decltype(std::declval< ContainerT >).cbegin())> hexdump_stream (const ContainerT &cont, std::string prompt="")
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename ContainerT , typename = std::enable_if_t<detail::IsHexDumpContainer<ContainerT>::value, decltype(HexdumpParameterForward<decltype(std::declval<ContainerT>().cbegin()), ContainerT> {}, 0)>>
HexdumpParameterForward< decltype(std::declval< ContainerT >).cbegin()), ContainerT > hexdump_stream (ContainerT &&cont, std::string prompt="")
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename StringContainer = std::vector<std::string>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer split (string_view text, string_view delimiter, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
 Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in a container. More...
 
template<typename StringContainer = std::vector<std::string>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer split (string_view text, const std::regex &delimiter, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
 Separate a string at all occurrences of a delimiter described by a regular expression, returning the strings between the delimiters in a container. More...
 
template<typename StringContainer = std::vector<string_view>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer split_sv (string_view text, string_view delimiter, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
 Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in a vector. More...
 
template<typename StringContainer >
std::string join (const StringContainer &parts, string_view glue)
 Concatenate all strings in a range, placing a delimiter between them. More...
 
template<typename Iterator >
std::string join (Iterator begin, Iterator end, string_view glue)
 Concatenate all strings in a range, placing a delimiter between them. More...
 
template<typename ValueT >
constexpr auto abs (ValueT n) noexcept -> std::enable_if_t< std::is_unsigned< ValueT >::value, ValueT >
 Compute the absolute value of a number. More...
 
template<typename NumT , typename OrderT , typename = std::enable_if_t< std::is_arithmetic<NumT>::value and std::is_arithmetic<OrderT>::value >>
bool within_orders (const NumT a, const NumT b, const OrderT orders) noexcept(false)
 Determine if two numbers are almost equal, comparing only some significant digits. More...
 
template<typename NumT >
bool within_abs (NumT a, NumT b, NumT tol) noexcept
 Determine if two numbers are almost equal, allowing for an absolute difference. More...
 
template<typename NumT , typename = std::enable_if_t<std::is_floating_point<NumT>::value>>
bool within_ulp (NumT a, NumT b, unsigned int ulp)
 Determine if two numbers are almost equal, allowing for a difference of a given number of units-in-the-last-place (ULPs). More...
 
template<class NumT >
constexpr const NumT & clamp (const NumT &v, const NumT &lo, const NumT &hi)
 Coerce a value to be within a given range. More...
 
template<class NumT , class Compare >
constexpr const NumT & clamp (const NumT &v, const NumT &lo, const NumT &hi, Compare comp)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
GUL_EXPORT std::string replace (string_view haystack, string_view needle, string_view hammer)
 Replace all occurrences of a string within another string, returning the result as a std::string. More...
 
GUL_EXPORT std::string & replace_inplace (std::string &haystack, string_view needle, string_view hammer)
 Replace all occurrences of a string within another string in-place. More...
 
template<typename ElementT , size_t in_capacity>
void swap (SmallVector< ElementT, in_capacity > &a, SmallVector< ElementT, in_capacity > &b)
 Exchange the contents of one SmallVector with those of another one. More...
 
template<typename ElementType , std::size_t Extent>
span< const unsigned char,((Extent==dynamic_extent) ? dynamic_extent :sizeof(ElementType) *Extent)> as_bytes (span< ElementType, Extent > s) noexcept
 Return a constant view to the byte representation of the elements of a given span. More...
 
template<class ElementType , size_t Extent, typename std::enable_if<!std::is_const< ElementType >::value, int >::type = 0>
span< unsigned char,((Extent==dynamic_extent) ? dynamic_extent :sizeof(ElementType) *Extent)> as_writable_bytes (span< ElementType, Extent > s) noexcept
 Return a writable view to the byte representation of the elements of a given span. More...
 
template<std::size_t N, typename E , std::size_t S>
constexpr auto get (span< E, S > s) -> decltype(s[N])
 Return a reference to the Nth element of a given span. More...
 
template<typename ElementT >
auto ElementAccessor ()
 Return a mock element accessor for containers. More...
 
template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto mean (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 Calculate the arithmetic mean value of all elements in a container. More...
 
template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto rms (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 Calculate the root mean square of all elements in a container. More...
 
template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto median (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 Find the median of all elements in a container. More...
 
template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto maximum (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> DataT
 Return the maximum element value in a container. More...
 
template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto minimum (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> DataT
 Return the minimum element value in a container. More...
 
template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto min_max (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> MinMax< DataT >
 Find the minimum and maximum element values in a container. More...
 
template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto remove_outliers (ContainerT &&cont, std::size_t outliers, Accessor accessor=ElementAccessor< ElementT >()) -> ContainerT &
 Remove elements that are far away from other elements. More...
 
template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto remove_outliers (ContainerT const &cont, std::size_t outliers, Accessor accessor=ElementAccessor< ElementT >()) -> std::vector< ElementT >
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.The original container is not modified. More...
 
template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto standard_deviation (ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> StandardDeviationMean< ResultT >
 Calculate the standard deviation of all elements in a container. More...
 
template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename OpClosure , typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto accumulate (ContainerT const &container, OpClosure op, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 Calculate some aggregate value from all elements of a container. More...
 
template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto mean (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto rms (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto median (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto maximum (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> DataT
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto minimum (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> DataT
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto min_max (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> MinMax< DataT >
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto remove_outliers (IteratorT const &begin, IteratorT const &end, std::size_t outliers, Accessor accessor=ElementAccessor< ElementT >()) -> std::vector< ElementT >
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.The original container is not modified. More...
 
template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto standard_deviation (IteratorT const &begin, IteratorT const &end, Accessor accessor=ElementAccessor< ElementT >()) -> StandardDeviationMean< ResultT >
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename OpClosure >
auto accumulate (IteratorT const &begin, IteratorT const &end, OpClosure op, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename Integer , std::enable_if_t< std::is_integral< Integer >::value, bool > = true>
std::string hex_string (Integer v)
 Return the hexadecimal ASCII representation of an integer value. More...
 
template<typename Iterator >
std::string hex_string (Iterator begin, Iterator end, string_view separator="")
 Return the hexadecimal ASCII representation of a range of integer values. More...
 
template<typename Integer , size_t num_elements, std::enable_if_t< std::is_integral< Integer >::value, bool > = true>
std::string hex_string (const Integer(&array)[num_elements], string_view separator="")
 Return the hexadecimal ASCII representation of an array with integer values. More...
 
template<typename Container , std::enable_if_t< IsContainerLike< Container >::value, bool > = true>
std::string hex_string (const Container &container, string_view separator="")
 Return the hexadecimal ASCII representation of a container with integer values. More...
 
GUL_EXPORT std::string repeat (gul14::string_view str, std::size_t n)
 Repeat a string N times. More...
 
GUL_EXPORT std::string safe_string (const char *char_ptr, std::size_t length)
 Safely construct a std::string from a char pointer and a length. More...
 
constexpr bool contains (string_view haystack, string_view needle) noexcept
 Determine whether a string contains another string. More...
 
constexpr bool contains (string_view haystack, char needle) noexcept
 Determine whether a string contains a certain character. More...
 
constexpr bool ends_with (string_view str, string_view suffix) noexcept
 Determine whether a string ends with another string. More...
 
constexpr bool ends_with (string_view str, char c) noexcept
 Determine whether a string ends with a certain character. More...
 
constexpr bool starts_with (string_view str, string_view prefix) noexcept
 Determine whether a string starts with another string. More...
 
constexpr bool starts_with (string_view str, char c) noexcept
 Determine whether a string starts with a certain character. More...
 
constexpr bool equals_nocase (string_view str1, string_view str2) noexcept
 Determine whether a string is equal to another one, making no distinction between upper and lower case ASCII characters. More...
 
constexpr bool contains_nocase (string_view haystack, string_view needle) noexcept
 Determine whether a string contains another string. More...
 
constexpr bool contains_nocase (string_view haystack, char needle) noexcept
 Determine whether a string contains a certain character. More...
 
constexpr bool ends_with_nocase (string_view str, string_view suffix) noexcept
 Determine whether a string ends with another string. More...
 
constexpr bool ends_with_nocase (string_view str, char c) noexcept
 Determine whether a string ends with a certain character. More...
 
constexpr bool starts_with_nocase (string_view str, string_view prefix) noexcept
 Determine whether a string starts with another string. More...
 
constexpr bool starts_with_nocase (string_view str, char c) noexcept
 Determine whether a string starts with a certain character. More...
 
std::chrono::steady_clock::time_point tic ()
 Return the current time as a std::chrono time_point. More...
 
template<class TimeUnitType = std::chrono::duration<double>>
auto toc (std::chrono::steady_clock::time_point t0)
 Return the elapsed time in seconds (or a different unit) since the given time point. More...
 
template<class Rep , class Period >
bool sleep (const std::chrono::duration< Rep, Period > &duration, const Trigger &trg)
 Sleep for at least the given time span, with the option of being woken up from another thread. More...
 
bool sleep (double seconds, const Trigger &trg)
 Sleep for a given number of seconds, with the option of being woken up from another thread. More...
 
template<class Rep , class Period >
bool sleep (const std::chrono::duration< Rep, Period > &duration)
 Sleep for a given time span. More...
 
bool sleep (double seconds)
 Sleep for a given number of seconds. More...
 
template<typename NumberType , std::enable_if_t< std::is_integral< NumberType >::value &&std::is_unsigned< NumberType >::value, int > = 0>
constexpr optional< NumberType > to_number (gul14::string_view str) noexcept
 Convert an ASCII string_view into a number. More...
 
template<typename StringContainer = std::vector<std::string>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer tokenize (string_view str, string_view delimiters=default_whitespace_characters, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
 Split the given string into a vector of substrings (tokens) delimited by any of the characters in the delimiters string. More...
 
template<typename StringContainer = std::vector<string_view>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer tokenize_sv (string_view str, string_view delimiters=default_whitespace_characters, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
 Split the given string into a vector of substrings (tokens) delimited by any of the characters in the delimiters string. More...
 
GUL_EXPORT std::string trim (string_view str, string_view ws_chars=default_whitespace_characters)
 Trim leading and trailing whitespace (or a custom set of characters) from a string, returning a new std::string. More...
 
GUL_EXPORT string_view trim_sv (string_view str, string_view ws_chars=default_whitespace_characters)
 Trim leading and trailing whitespace (or a custom set of characters) from a string, returning a view into the original string. More...
 
GUL_EXPORT std::string trim_left (string_view str, string_view ws_chars=default_whitespace_characters)
 Trim leading whitespace (or a custom set of characters) from a string, returning a new std::string. More...
 
GUL_EXPORT string_view trim_left_sv (string_view str, string_view ws_chars=default_whitespace_characters)
 Trim leading whitespace (or a custom set of characters) from a string, returning a view into the original string. More...
 
GUL_EXPORT std::string trim_right (string_view str, string_view ws_chars=default_whitespace_characters)
 Trim trailing whitespace (or a custom set of characters) from a string, returning a new std::string. More...
 
GUL_EXPORT string_view trim_right_sv (string_view str, string_view ws_chars=default_whitespace_characters)
 Trim trailing whitespace (or a custom set of characters) from a string, returning a view into the original string. More...
 
template<class T >
constexpr string_view type_name ()
 Generate a human readable string describing a type. More...
 

Variables

GUL_EXPORT const string_view default_whitespace_characters { " \t\r\n\a\b\f\v" }
 The default characters that are treated as whitespace by GUL. More...
 
GUL_EXPORT const std::array< char, 16 > hex_digits
 The 16 digits for hexadecimal numbers ("0123456789abcdef"). More...
 
GUL_EXPORT char const * version_git
 Holds the git version tag of the sources that the library has been build with. More...
 
GUL_EXPORT char const * version_api
 Holds the API version of the library.
 

Typedef Documentation

◆ BitFunctionReturnType

template<typename T >
using gul14::BitFunctionReturnType = typedef std::enable_if_t< std::is_integral<T>::value and not std::is_same<std::decay_t<T>, bool>::value, std::decay_t<T> >

Return type of the bit manipulation functions.

We want to SFINAE out of all types except integers. Because bools counts as integer type and we don't want that we specifically exclude it here.

The type is then simply the decayed input type, to get rid of const or volatile specifiers.

Template Parameters
TType specified/deduced by bit_*() user

◆ string_view

using gul14::string_view = typedef basic_string_view<char>

A view to a contiguous sequence of chars.

This is a backport of std::string_view from libc++ for C++17.

◆ u16string_view

using gul14::u16string_view = typedef basic_string_view<char16_t>

A view to a contiguous sequence of char16_ts.

This is a backport of std::string_view from libc++ for C++17.

◆ u32string_view

using gul14::u32string_view = typedef basic_string_view<char32_t>

A view to a contiguous sequence of char32_ts.

This is a backport of std::string_view from libc++ for C++17.

◆ wstring_view

using gul14::wstring_view = typedef basic_string_view<wchar_t>

A view to a contiguous sequence of wchar_ts.

This is a backport of std::string_view from libc++ for C++17.

Enumeration Type Documentation

◆ ShrinkBehavior

enum gul14::ShrinkBehavior
strong

Determine how a SlidingBuffer handles decreases of its size.

When the buffer's capacity decreases below the actual size some elements have to be dropped. The user can choose between two strategies:

  1. Keep the elements with the lower indices (ShrinkBehavior::keep_front_elements)
  2. Keep the elements with the higher indices (ShrinkBehavior::keep_back_elements)

Usually the more recent data shall be preserved, while older data can be dropped.

The behavior is utilized by SlidingBuffer::resize(), SlidingBuffer::reserve(), SlidingBufferExposed::resize(), and SlidingBufferExposed::reserve().

Since
GUL version 1.3

Function Documentation

◆ abs()

template<typename ValueT >
constexpr auto gul14::abs ( ValueT  n) -> std::enable_if_t<std::is_unsigned<ValueT>::value, ValueT>
constexprnoexcept

Compute the absolute value of a number.

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

This function is almost equal to std::abs() with the exception of unsigned integral types, which are returned unchanged and in their original type. This is especially useful in templates, where std::abs() cannot be used for all arithmetic types.

Parameters
nThe number whose absolute value should be determined.
Returns
the absolute value of n.

Referenced by gcd(), lcm(), remove_outliers(), within_abs(), within_orders(), and within_ulp().

◆ accumulate() [1/2]

template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename OpClosure , typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::accumulate ( ContainerT const &  container,
OpClosure  op,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

Calculate some aggregate value from all elements of a container.

This is similar to std::accumulate, but

  • works on a whole container,
  • accesses the container elements through an accessor function,
  • applies the binary operator op to a running sum and each element value,
  • the sum's type is in the first template parameter, and
  • the initial value of the sum is its default constructed value.
Parameters
containerContainer of the elements to examine
opBinary operator to aggregate two values into one value
accessorHelper function to access the numeric value of one container element
Returns
the aggregate value.
Template Parameters
ResultTType of the result value / accumulator
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
accumulate(IteratorT const&, IteratorT const&, OpClosure, Accessor) accepts two iterators instead of a container.

References accumulate().

◆ accumulate() [2/2]

template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename OpClosure >
auto gul14::accumulate ( IteratorT const &  begin,
IteratorT const &  end,
OpClosure  op,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
opBinary operator to aggregate two values into one value
accessorHelper function to access the numeric value of one container element
See also
accumulate(ContainerT const&, OpClosure, Accessor) accepts a container instead of iterators.

Referenced by accumulate(), maximum(), mean(), min_max(), minimum(), rms(), and standard_deviation().

◆ as_bytes()

template<typename ElementType , std::size_t Extent>
span<const unsigned char, ((Extent == dynamic_extent) ? dynamic_extent : sizeof(ElementType) * Extent)> gul14::as_bytes ( span< ElementType, Extent >  s)
noexcept

Return a constant view to the byte representation of the elements of a given span.

This is a backport from the C++20 standard library, see: https://en.cppreference.com/w/cpp/container/span/as_bytes

Since
GUL version 1.9

References gul14::span< ElementType, Extent >::data(), and gul14::span< ElementType, Extent >::size_bytes().

◆ as_writable_bytes()

template<class ElementType , size_t Extent, typename std::enable_if<!std::is_const< ElementType >::value, int >::type = 0>
span<unsigned char, ((Extent == dynamic_extent) ? dynamic_extent : sizeof(ElementType) * Extent)> gul14::as_writable_bytes ( span< ElementType, Extent >  s)
noexcept

Return a writable view to the byte representation of the elements of a given span.

This is a backport from the C++20 standard library, see: https://en.cppreference.com/w/cpp/container/span/as_bytes

Since
GUL version 1.9

References gul14::span< ElementType, Extent >::data(), and gul14::span< ElementType, Extent >::size_bytes().

◆ bit_flip()

template<typename T , typename ReturnT = BitFunctionReturnType<T>>
constexpr auto gul14::bit_flip ( previous,
unsigned  bit 
) -> ReturnT
inlineconstexprnoexcept

Flip a bit in an integral value.

Flips the bit number bit in the existing value previous. This inverts the state of the bit: setting the bit if it was previously not set and resetting the bit if it was previously set.

When bit is greater or equal to the number of bits in type T, std::abort() is called (via assert()).

Parameters
previousExisting integral value where the bit shall be modified
bitNumber of the bit that is to be modified (LSB == 0)
Returns
New integral value with the bit modified.
Template Parameters
TType of the bit-holding integral value.
Since
GUL version 1.8
See also
bit_set(bit), bit_set(previous, bit), bit_reset(previous, bit), bit_test(bits, bit)

◆ bit_reset()

template<typename T , typename ReturnT = BitFunctionReturnType<T>>
constexpr auto gul14::bit_reset ( previous,
unsigned  bit 
) -> ReturnT
inlineconstexprnoexcept

Reset a bit in an integral value.

Reset (clear) the bit number bit in the existing value previous.

When bit is greater or equal to the number of bits in type T, std::abort() is called (via assert()).

Parameters
previousExisting integral value where the bit shall be modified
bitNumber of the bit that is to be modified (LSB == 0)
Returns
New integral value with the bit modified.
Template Parameters
TType of the bit-holding integral value.
Since
GUL version 1.8
See also
bit_set(bit), bit_set(previous, bit), bit_flip(previous, bit), bit_test(bits, bit)

◆ bit_set() [1/2]

template<typename T , typename ReturnT = BitFunctionReturnType<T>>
constexpr auto gul14::bit_set ( previous,
unsigned  bit 
) -> ReturnT
inlineconstexprnoexcept

Set a bit in an integral value.

Set the bit number bit in the existing value previous.

When bit is greater or equal to the number of bits in type T, std::abort() is called (via assert()).

Parameters
previousExisting integral value where the bit shall be modified
bitNumber of the bit that is to be modified (LSB == 0)
Returns
New integral value with the bit modified.
Template Parameters
TType of the bit-holding integral value.
Since
GUL version 1.8
See also
bit_set(bit), bit_reset(previous, bit), bit_flip(previous, bit), bit_test(bits, bit)

◆ bit_set() [2/2]

template<typename T = unsigned, typename ReturnT = BitFunctionReturnType<T>>
constexpr auto gul14::bit_set ( unsigned  bit) -> ReturnT
inlineconstexprnoexcept

Set a bit in an integral type.

Return an integral value of type T where the bit number bit and only that bit is set.

When bit is greater or equal to the number of bits in type T, std::abort() is called (via assert()).

Parameters
bitNumber of the bit that is to be set (LSB == 0)
Returns
Integral value with the bit set.
Template Parameters
TType of the bit-holding integral value.
Note
If no type T is specified an unsigned int will be returned.
Since
GUL version 1.8
See also
bit_set(previous, bit), bit_reset(previous, bit), bit_flip(previous, bit), bit_test(bits, bit)

◆ bit_test()

template<typename T >
constexpr bool gul14::bit_test ( bits,
unsigned  bit 
)
inlineconstexprnoexcept

Test a bit in an integral value.

Test the bit number bit in the existing value bits.

When bit is greater or equal to the number of bits in type T, std::abort() is called (via assert()).

Parameters
bitsIntegral value where the bit shall be tested
bitNumber of the bit that is to be modified (LSB == 0)
Returns
True or false
Template Parameters
TType of the bit-holding integral value.
Since
GUL version 1.8
See also
bit_set(bit), bit_set(previous, bit), bit_reset(previous, bit), bit_flip(previous, bit)

◆ cat() [1/6]

std::string gul14::cat ( )
inline

Efficiently concatenate an arbitrary number of strings and numbers.

Numbers are converted to strings in the same way as done by std::to_string. cat() reserves the correct amount of space before concatenating the strings and can therefore save several memory allocations compared to concatenation with "+".

std::string str = gul14::cat(13.5, std::string(" quick "), "brown foxes ", "jump over ",
42, " lazy dogs'", std::string(" heads."));
// str == "13.500000 quick brown foxes jump over 42 lazy dogs' heads."
std::string cat()
Efficiently concatenate an arbitrary number of strings and numbers.
Definition: cat.h:90
Returns
a string containing the concatenation of all arguments.

Referenced by gul14::SlidingBuffer< ElementT, fixed_capacity, Container >::at(), gul14::SmallVector< ElementT, in_capacity >::at(), and cat().

◆ cat() [2/6]

template<typename... Args, typename = std::enable_if_t<(sizeof...(Args) > 3)>>
std::string gul14::cat ( const Args &...  args)
inline
See also
cat()

References cat().

◆ cat() [3/6]

std::string gul14::cat ( const ConvertingStringView s)
inline
See also
cat()

◆ cat() [4/6]

std::string gul14::cat ( const ConvertingStringView s1,
const ConvertingStringView s2 
)

◆ cat() [5/6]

std::string gul14::cat ( const ConvertingStringView s1,
const ConvertingStringView s2,
const ConvertingStringView s3 
)

◆ cat() [6/6]

std::string gul14::cat ( std::initializer_list< ConvertingStringView pieces)
See also
cat()

◆ clamp() [1/2]

template<class NumT >
constexpr const NumT& gul14::clamp ( const NumT &  v,
const NumT &  lo,
const NumT &  hi 
)
constexpr

Coerce a value to be within a given range.

Check if value v is between (including) lo and hi. If it is too low, lo is returned. If it is too high, hi is returned.

lo must not be greater than hi, but they are allowed to be equal.

Only operator<() is used for this, so it has to be defined for NumT.

Note that all parameters need to be of the same type. Add the correct suffix if using a literal as shown in the following example:

char c = ...;
size_t s = ...;
float f = ...;
auto c2 = clamp(c, 'a', 'z');
auto s2 = clamp(s, 0ul, 1000ul);
auto f2 = clamp(f, 0.0f, 99.0f);
constexpr const NumT & clamp(const NumT &v, const NumT &lo, const NumT &hi)
Coerce a value to be within a given range.
Definition: num_util.h:196
Template Parameters
NumTType of the objects to compare. Needs to have operator<() defined.
Parameters
vThe value to clamp
loThe lower boundary to clamp v to
hiThe upper boundary to clamp v to
Returns
a reference to lo if v is less than lo, a reference to hi if hi is less than v, or a reference to v otherwise.

◆ clamp() [2/2]

template<class NumT , class Compare >
constexpr const NumT& gul14::clamp ( const NumT &  v,
const NumT &  lo,
const NumT &  hi,
Compare  comp 
)
constexpr

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

Template Parameters
NumTType of the objects to compare. Needs to have operator<() defined.
CompareType of the comparison function. See notes below.
Parameters
vThe value to clamp
loThe lower boundary to clamp v to
hiThe upper boundary to clamp v to
compComparison function object which returns true if the first argument is less than the second.

The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1& a, const Type2& b);

While the signature does not explicitly require passing the arguments by const reference, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category. This means that neither Type1 & nor Type1 are allowed unless a move is equivalent to a copy for Type1. The types Type1 and Type2 must be such that an object of type T can be implicitly converted to both of them.

◆ contains() [1/2]

constexpr bool gul14::contains ( string_view  haystack,
char  needle 
)
inlineconstexprnoexcept

Determine whether a string contains a certain character.

The comparison is case sensitive.

Parameters
haystackThe string in which to search.
needleThe character that should be searched for.
Returns
true if haystack contains at least one occurrence of needle, false otherwise.
See also
contains(string_view, string_view), contains_nocase(string_view, char), ends_with(string_view, char), starts_with(string_view, char)

◆ contains() [2/2]

constexpr bool gul14::contains ( string_view  haystack,
string_view  needle 
)
inlineconstexprnoexcept

Determine whether a string contains another string.

The comparison is case sensitive. If the searched-for string is empty, the result is true.

Parameters
haystackThe string in which to search.
needleThe string that should be searched for.
Returns
true if haystack contains at least one occurrence of needle, false otherwise.
See also
contains(string_view, char), contains_nocase(string_view, string_view), ends_with(string_view, string_view), starts_with(string_view, string_view)

◆ contains_nocase() [1/2]

constexpr bool gul14::contains_nocase ( string_view  haystack,
char  needle 
)
inlineconstexprnoexcept

Determine whether a string contains a certain character.

The comparison is case insensitive as far as ASCII characters are concerned (C locale).

Parameters
haystackThe string in which to search.
needleThe character that should be searched for.
Returns
true if haystack contains at least one occurrence of needle, false otherwise.
Since
GUL version 1.7
See also
contains_nocase(string_view, string_view), contains(string_view, char), ends_with_nocase(string_view, char), starts_with_nocase(string_view, char)

References lowercase_ascii().

◆ contains_nocase() [2/2]

constexpr bool gul14::contains_nocase ( string_view  haystack,
string_view  needle 
)
inlineconstexprnoexcept

Determine whether a string contains another string.

The comparison is case insensitive as far as ASCII characters are concerned (C locale). If the searched-for string is empty, the result is true.

Parameters
haystackThe string in which to search.
needleThe string that should be searched for.
Returns
true if haystack contains at least one occurrence of needle, false otherwise.
Note
This function does not allocate memory to buffer the case-transformed input strings. It might therefore have lower performance than combining contains() and lowercase_ascii().
Since
GUL version 1.7
See also
contains_nocase(string_view, char), contains(string_view, string_view), ends_with_nocase(string_view, string_view), starts_with_nocase(string_view, string_view)

References lowercase_ascii().

◆ ElementAccessor()

template<typename ElementT >
auto gul14::ElementAccessor ( )

Return a mock element accessor for containers.

All functions in statistics.h access the elements of the containers they work on through accessor functions. If the container is simple, i.e. contains just the types we want to work on (like double of std::vector<double>) we can automate the generation of the accessor function, so that the user does not need to specify it.

Template Parameters
ElementTType of the elements in the container
Returns
Pointer to accessor function

◆ ends_with() [1/2]

constexpr bool gul14::ends_with ( string_view  str,
char  c 
)
inlineconstexprnoexcept

Determine whether a string ends with a certain character.

The comparison is case sensitive.

Parameters
strThe string to be tested.
cThe character to be looked for at the end of str.
Returns
true if str ends with c, false otherwise.
See also
ends_with(string_view, string_view), ends_with_nocase(string_view, char), starts_with(string_view, char), contains(string_view, char)

◆ ends_with() [2/2]

constexpr bool gul14::ends_with ( string_view  str,
string_view  suffix 
)
inlineconstexprnoexcept

Determine whether a string ends with another string.

The comparison is case sensitive. If the searched-for suffix is empty, the result is true.

Parameters
strThe full string to be tested.
suffixThe suffix to be looked for at the end of str.
Returns
true if str ends with suffix, false otherwise.
See also
ends_with(string_view, char), ends_with_nocase(string_view, string_view), starts_with(string_view, string_view), contains(string_view, string_view)

◆ ends_with_nocase() [1/2]

constexpr bool gul14::ends_with_nocase ( string_view  str,
char  c 
)
inlineconstexprnoexcept

Determine whether a string ends with a certain character.

The comparison is case insensitive as far as ASCII characters are concerned (C locale).

Parameters
strThe string to be tested.
cThe character to be looked for at the end of str.
Returns
true if str ends with c, false otherwise.
Since
GUL version 1.7
See also
ends_with_nocase(string_view, string_view), ends_with(string_view, char), starts_with_nocase(string_view, char), contains_nocase(string_view, char)

References lowercase_ascii().

◆ ends_with_nocase() [2/2]

constexpr bool gul14::ends_with_nocase ( string_view  str,
string_view  suffix 
)
inlineconstexprnoexcept

Determine whether a string ends with another string.

The comparison is case insensitive as far as ASCII characters are concerned (C locale). If the searched-for suffix is empty, the result is true.

Parameters
strThe full string to be tested.
suffixThe suffix to be looked for at the end of str.
Returns
true if str ends with suffix, false otherwise.
Since
GUL version 1.7
See also
ends_with_nocase(string_view, char), ends_with(string_view, string_view), starts_with_nocase(string_view, string_view), contains_nocase(string_view, string_view)

References lowercase_ascii().

◆ equals_nocase()

constexpr bool gul14::equals_nocase ( string_view  str1,
string_view  str2 
)
inlineconstexprnoexcept

Determine whether a string is equal to another one, making no distinction between upper and lower case ASCII characters.

In other terms, this function performs a case insensitive string comparison using the C locale.

Parameters
str1,str2The two strings that should be compared.
Returns
true if the ASCII-lowercase versions of str1 and str2 are equal, or false otherwise.
Since
GUL version 2.1
See also
contains_nocase(string_view, string_view), ends_with_nocase(string_view, string_view), starts_with_nocase(string_view, string_view)

References lowercase_ascii().

◆ escape()

GUL_EXPORT std::string gul14::escape ( string_view  in)

Create a new string that looks like an ASCII-only C string literal of the input string.

This is achieved by replacing all non-printable and non-ASCII characters with a hex code escape in the form \x01.

A few special cases are implemented to give more readable representations for very common control characters, and of course backslash and double quotes are escaped as well:

CR   ->  \r
NL   ->  \n
TAB  ->  \t
\    ->  \\
"    ->  \"

Example

std::cout << escape("Zwei\tFlüsse\nfließen ins Meer.") << "\n";
GUL_EXPORT std::string escape(string_view in)
Create a new string that looks like an ASCII-only C string literal of the input string.

Output (assuming that the string literal was in Latin-1 encoding):

Zwei\tFl\xfcsse\nflie\xdfen ins Meer.
Note
The hexadecimal escape always uses two digits. This is different from the C/C++ standard, where it can be an arbitrary number of digits. The standard's way makes it impossible to have any hex digit after a hex escape, e.g. "\x200" is invalid and not equal to " 0" from the standard's point of view.
Parameters
inThe input string.
Returns
a new string that contains only ASCII characters.
Since
GUL version 1.4 parameter in is a string_view (was std::string before)

◆ finally()

template<typename F >
FinalAction<typename std::decay_t<F> > gul14::finally ( F &&  f)
noexcept

finally() - convenience function to generate a FinalAction

A FinalAction can be used to add RAII like behavior for non RAII object or to do timing measurements. More information given in the FinalAction documentation.

Template Parameters
FThe type of the closure/function to be called (normally autodeduced).
Parameters
fThe closure or pointer to function to be called on destruction.
Since
GUL version 1.1

◆ gcd()

template<typename IntTypeA , typename IntTypeB >
constexpr auto gul14::gcd ( IntTypeA  a,
IntTypeB  b 
)
inlineconstexpr

Calculate the greatest common divisor of two integers using the Euclidean algorithm.

If both numbers are zero, the function returns zero. Otherwise, the result is a positive integer.

int greatest_common_divisor = gcd(10, 15); // returns 5
constexpr auto gcd(IntTypeA a, IntTypeB b)
Calculate the greatest common divisor of two integers using the Euclidean algorithm.
Definition: gcd_lcm.h:64
Returns
the least common multiple of the two numbers, represented as an integer type (std::common_type_t<IntTypeA, IntTypeB>) that both inputs can implicitly be converted to. If either a, b, or the result can not be represented by that type, the result is undefined.
Note
Unlike std::gcd() from C++17, the GUL14 version cannot be used with integers of different signedness. This avoids undefined behavior when mixing unsigned integers with negative signed values:
// C++17 gcd(): Undefined behavior - the common type is `unsigned int` and -5 has no
// representation in that type
auto bad_result = std::gcd(10u, -5);
// GUL14 gcd(): Does not compile
auto static_assertion_failure = gul14::gcd(10u, -5);
Since
GUL version 2.7

References abs().

Referenced by lcm().

◆ get()

template<std::size_t N, typename E , std::size_t S>
constexpr auto gul14::get ( span< E, S >  s) -> decltype(s[N])
constexpr

Return a reference to the Nth element of a given span.

This is a backport from the C++20 standard library, see: https://en.cppreference.com/w/cpp/container/span/get

Since
GUL version 1.9

◆ hex_string() [1/4]

template<typename Container , std::enable_if_t< IsContainerLike< Container >::value, bool > = true>
std::string gul14::hex_string ( const Container &  container,
string_view  separator = "" 
)
inline

Return the hexadecimal ASCII representation of a container with integer values.

The letters 'a' to 'f' are used in lowercase, and no separators are inserted between individual values.

std::array<unsigned char, 4> values = { 0, 15, 16, 255 };
assert(hex_string(values) == "000f10ff");
std::string hex_string(Integer v)
Return the hexadecimal ASCII representation of an integer value.
Definition: string_util.h:106
Parameters
containerInput container
separatorA string that is inserted between the elements to separate them visually (empty by default)
Template Parameters
Containermust be a gul14::IsContainerLike class
Since
GUL version 2.6

References hex_string().

◆ hex_string() [2/4]

template<typename Integer , size_t num_elements, std::enable_if_t< std::is_integral< Integer >::value, bool > = true>
std::string gul14::hex_string ( const Integer(&)  array[num_elements],
string_view  separator = "" 
)
inline

Return the hexadecimal ASCII representation of an array with integer values.

The letters 'a' to 'f' are used in lowercase, and a user-defined separator can be inserted between individual values.

uint16_t values[] = { 256, 255 };
assert(hex_string(values) == "010000ff");
assert(hex_string(values, "-") == "0100-00ff");
Parameters
arrayInput array
separatorA string that is inserted between the elements to separate them visually (empty by default)
Template Parameters
Integermust be an integral type.
num_elementsis the number of array elements.
Since
GUL version 2.6

References hex_string().

◆ hex_string() [3/4]

template<typename Integer , std::enable_if_t< std::is_integral< Integer >::value, bool > = true>
std::string gul14::hex_string ( Integer  v)
inline

Return the hexadecimal ASCII representation of an integer value.

The letters 'a' to 'f' are used in lowercase, and the number of hex digits is twice the number of bytes in the input integer type.

hex_string(static_cast<unsigned char>(1)) == "01"
hex_string(static_cast<unsigned char>(255)) == "ff";
hex_string(uint32_t{ 256 }) == "00000100";
Parameters
vInput value
Template Parameters
Integermust be an integral type.
Since
GUL version 2.6

References hex_digits.

Referenced by hex_string().

◆ hex_string() [4/4]

template<typename Iterator >
std::string gul14::hex_string ( Iterator  begin,
Iterator  end,
string_view  separator = "" 
)
inline

Return the hexadecimal ASCII representation of a range of integer values.

The letters 'a' to 'f' are used in lowercase, and a user-defined separator can be inserted between individual values.

std::array<unsigned char, 4> values = { 0, 15, 16, 255 };
assert(hex_string(values.begin(), values.end()) == "000f10ff");
assert(hex_string(values.begin(), values.end(), "-") == "00-0f-10-ff");
Parameters
beginIterator to the first element of the range
endIterator past the last element of the range
separatorA string that is inserted between the elements to separate them visually (empty by default)
Template Parameters
Iteratormust be a forward iterator.
Since
GUL version 2.6

References hex_string().

◆ hexdump() [1/2]

template<typename ContainerT , typename = std::enable_if_t<detail::IsHexDumpContainer<ContainerT>::value>>
std::string gul14::hexdump ( const ContainerT &  cont,
string_view  prompt = "" 
)

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

Parameters
contReference to the container whose contents should be dumped; the container must provide ForwardIterators for .cbegin() and .cend()
prompt(optional) String that prefixes the dump text
Returns
a string containing the dump

References hexdump_stream().

◆ hexdump() [2/2]

template<typename IteratorT , typename = std::enable_if_t<detail::IsHexDumpIterator<IteratorT>::value>>
std::string gul14::hexdump ( IteratorT  begin,
IteratorT  end,
string_view  prompt = "" 
)

Generate a hexdump of a data range and return it as a string.

The elements of the data range must be of integral type. They are dumped as unsigned integer values with their native width: Chars as "00" to "ff", 16-bit integers as "0000" to "ffff", and so on. If the elements are of type char, also a textual representation of the printable characters is dumped. An optional prompt can be added in front of the hexdump.

std::string x = "test\nthe Ä west!\t\r\n";
std::string str = gul14::hexdump(x.begin(), x.end(), "debug -> ");
std::cerr << str;
std::string hexdump(IteratorT begin, IteratorT end, string_view prompt="")
Generate a hexdump of a data range and return it as a string.
Definition: hexdump.h:213
deBug -> 000000: 74 65 73 74 0a 74 68 65 20 c3 84 20 77 65 73 74  test.the .. west
         000010: 21 09 0d 0a                                      !...
std::array<int, 8> ar = {{ 0, 1, 5, 2, -0x300fffff, 2, 5, 1999 }};
std::string str = gul14::hexdump(begin(ar), end(ar));
std::cout << str;
000000: 00000000 00000001 00000005 00000002 cff00001 00000002 00000005 000007cf
Parameters
beginForwardIterator to the first data element to be dumped
endForwardIterator past the last data element to be dumped
prompt(optional) String that prefixes the dump text
Returns
a string containing the dump

References hexdump_stream().

◆ hexdump_stream() [1/3]

template<typename ContainerT , typename = std::enable_if_t<detail::IsHexDumpContainer<ContainerT>::value>>
HexdumpParameterForward<const decltype(std::declval<ContainerT>).cbegin())> gul14::hexdump_stream ( const ContainerT &  cont,
std::string  prompt = "" 
)

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

Parameters
contReference to the container to dump
prompt(optional) String that prefixes the dump text
Returns
a helper object to be used with operator<< on streams

◆ hexdump_stream() [2/3]

template<typename IteratorT , typename = std::enable_if_t<detail::IsHexDumpIterator<IteratorT>::value>>
HexdumpParameterForward<const IteratorT> gul14::hexdump_stream ( const IteratorT &  begin,
const IteratorT &  end,
std::string  prompt = "" 
)

Generate a hexdump of a data range that can be efficiently written to a stream using operator<<.

Where hexdump() writes all of its output into one monolithic string, hexdump_stream() returns a tiny helper object that can efficiently send its output to an output stream via operator<<. This means that the following two lines produce the exact same output, but the stream version uses less resources:

std::cout << gul14::hexdump_stream(x.begin(), x.end()) << "\n"; // good
std::cout << gul14::hexdump(x.begin(), x.end()) << "\n"; // also good, but allocates a temporary string
HexdumpParameterForward< const IteratorT > hexdump_stream(const IteratorT &begin, const IteratorT &end, std::string prompt="")
Generate a hexdump of a data range that can be efficiently written to a stream using operator<<.
Definition: hexdump.h:416

The elements of the data range must be of integral type. They are dumped as unsigned integer values with their native width: Chars as "00" to "ff", 16-bit integers as "0000" to "ffff", and so on. If the elements are of type char, also a textual representation of the printable characters is dumped. An optional prompt can be added in front of the hexdump.

std::string x = "test\nthe Ä west!\t\r\n";
std::cerr << gul14::hexdump_stream(x.begin(), x.end(), "debug -> ");
debug -> 000000: 74 65 73 74 0a 74 68 65 20 c3 84 20 77 65 73 74  test.the .. west
         000010: 21 09 0d 0a                                      !...
std::array<int, 8> ar = {{ 0, 1, 5, 2, -0x300fffff, 2, 5, 1999 }};
std::cout << gul14::hexdump_stream(begin(ar), end(ar));
000000: 00000000 00000001 00000005 00000002 cff00001 00000002 00000005 000007cf
Parameters
beginForwardIterator to the first data to be dumped
endForwardIterator past the last data element to be dumped
prompt(optional) String that prefixes the dump text
Returns
a helper object to be used with operator<< on streams

◆ hexdump_stream() [3/3]

template<typename ContainerT , typename = std::enable_if_t<detail::IsHexDumpContainer<ContainerT>::value, decltype(HexdumpParameterForward<decltype(std::declval<ContainerT>().cbegin()), ContainerT> {}, 0)>>
HexdumpParameterForward<decltype(std::declval<ContainerT>).cbegin()), ContainerT> gul14::hexdump_stream ( ContainerT &&  cont,
std::string  prompt = "" 
)

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

Parameters
contReference to the container to dump if is a temporary
prompt(optional) String that prefixes the dump text
Returns
a helper object to be used with operator<< on streams

Referenced by hexdump().

◆ join() [1/2]

template<typename StringContainer >
std::string gul14::join ( const StringContainer &  parts,
string_view  glue 
)
inline

Concatenate all strings in a range, placing a delimiter between them.

This algorithm iterates twice over the range in order to pre-allocate a string of the correct size.

This is the inverse function of split(). It is guaranteed that join(split(text, del), del) == text (unless del is a std::regex object).

Parameters
partsA container holding strings or string views that are to be concatenated
glueString that is put between each element of parts
Returns
all strings glued together with the delimiter glue.
Template Parameters
StringContainerA container type that holds strings, e.g. std::vector<std::string> or std::list<gul14::string_view>. The container must provide an STL-like forward iterator interface. The string type must support concatenation with std::string using operator+=.
See also
join(Iterator, Iterator, string_view) has a two-iterator interface, split() and associated functions can be used to split a string into a vector of substrings.
Since
GUL version 2.3, join() accepts arbitrary containers or iterators (it was limited to std::vector before).

◆ join() [2/2]

template<typename Iterator >
std::string gul14::join ( Iterator  begin,
Iterator  end,
string_view  glue 
)
inline

Concatenate all strings in a range, placing a delimiter between them.

This algorithm iterates twice over the range in order to pre-allocate a string of the correct size.

Parameters
beginIterator pointing to the first string
endIterator pointing past the last string
glueString that is put between each element of parts
Returns
all strings glued together with the delimiter glue.
Template Parameters
IteratorA forward iterator type that dereferences to a string type. The string type must support concatenation with std::string using operator+=.
See also
join(StringContainer, string_view) is a convenience overload for joining entire containers, split() and associated functions can be used to split a string into a vector of substrings.
Since
GUL version 2.3

◆ lcm()

template<typename IntTypeA , typename IntTypeB >
constexpr auto gul14::lcm ( IntTypeA  a,
IntTypeB  b 
)
inlineconstexpr

Calculate the least common multiple of two integers.

If both numbers are zero, the function returns zero. Otherwise, the result is a positive integer.

int least_common_multiple = lcm(10, 15); // returns 30
constexpr auto lcm(IntTypeA a, IntTypeB b)
Calculate the least common multiple of two integers.
Definition: gcd_lcm.h:118
Returns
the least common multiple of the two numbers, represented as an integer type (std::common_type_t<IntTypeA, IntTypeB>) that both inputs can implicitly be converted to. If either a, b, or the result can not be represented by that type, the result is undefined.
Note
Unlike std::lcm() from C++17, the GUL14 version cannot be used with integers of different signedness. This avoids undefined behavior when mixing unsigned integers with negative signed values:
// C++17 lcm(): Undefined behavior - the common type is `unsigned int` and -5 has no
// representation in that type
auto bad_result = std::lcm(10u, -5);
// GUL14 lcm(): Does not compile
auto static_assertion_failure = gul14::lcm(10u, -5);
Since
GUL version 2.7

References abs(), and gcd().

◆ lowercase_ascii() [1/2]

constexpr char gul14::lowercase_ascii ( char  c)
constexprnoexcept

Return the ASCII lowercase equivalent of the given character (or the unchanged character, if it is not an ASCII letter).

Parameters
cThe original character.
Since
GUL version 1.2
See also
lowercase_ascii(gul14::string_view), lowercase_ascii_inplace(std::string &), uppercase_ascii(char)

Referenced by contains_nocase(), ends_with_nocase(), equals_nocase(), lowercase_ascii(), lowercase_ascii_inplace(), and starts_with_nocase().

◆ lowercase_ascii() [2/2]

std::string gul14::lowercase_ascii ( gul14::string_view  str)

Return a copy of the given string in which all ASCII characters are replaced by their lowercase equivalents.

Parameters
strThe original string.
Since
GUL version 1.2
See also
lowercase_ascii(char), lowercase_ascii_inplace(std::string &), uppercase_ascii(gul14::string_view)

References lowercase_ascii().

◆ lowercase_ascii_inplace()

std::string & gul14::lowercase_ascii_inplace ( std::string &  str)
noexcept

Replace all ASCII characters in a string by their lowercase equivalents.

This function modifies the original string and returns a reference to it (which may be helpful for chaining function calls).

Parameters
strThe string to be modified.
Returns
a reference to the string argument.
Since
GUL version 1.2
See also
lowercase_ascii(char), lowercase_ascii(gul14::string_view), uppercase_ascii_inplace(std::string &)

References lowercase_ascii().

◆ maximum() [1/2]

template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::maximum ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> DataT

Return the maximum element value in a container.

The value of each element is determined through the accessor function. The maximum value is returned. Its type (DataT, the return type of the accessor) must provide operator==() and operator<=(). If DataT supports not-a-number (NaN) values, such values are ignored. If the container is empty, the return value is NaN (if supported) or std::numeric_limits<DataT>::lowest().

Hint: If looking for an iterator to the maximum element instead of its value, use std::max_element() from the STL algorithm collection.

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element.
Returns
the maximum value.
Template Parameters
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
maximum(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.
minimum() returns the minimum value, min_max() returns both the minimum and the maximum.
Since
GUL version 2.2

References accumulate().

Referenced by within_orders().

◆ maximum() [2/2]

template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::maximum ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> DataT

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
max(ContainerT const&, Accessor) accepts a container instead of iterators.

◆ mean() [1/2]

template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::mean ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

Calculate the arithmetic mean value of all elements in a container.

The mean value is calculated by dividing the sum of all elements by the number of elements: mean -> sum 0..n-1 (element i) / n

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element
Returns
the arithmetic mean value.
Template Parameters
ResultTType of the result (this is also the type used for holding the sum of all elements and for the division by the number of elements, so make sure it can hold numbers that are big enough)
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
mean(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.

References accumulate().

◆ mean() [2/2]

template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::mean ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
mean(ContainerT const&, Accessor) accepts a container instead of iterators.

Referenced by remove_outliers().

◆ median() [1/2]

template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::median ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

Find the median of all elements in a container.

The median element is the element that has an equal number of elements higher and lower in value. If the container has an even number of elements there can be no 'middle' element. In this case the two 'middlemost' elements are taken and the arithmetic mean of the two is returned.

Because all elements need to be sorted, the function works with a temporary copy of the original container.

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element
Returns
the median value.
Template Parameters
ResultTType of the result value
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
median(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.

◆ median() [2/2]

template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::median ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
median(ContainerT const&, Accessor) accepts a container instead of iterators.

◆ min_max() [1/2]

template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::min_max ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> MinMax<DataT>

Find the minimum and maximum element values in a container.

The value of each element is determined through the accessor function. The minimum and the maximum of these values are returned. Their type (DataT, the return type of the accessor) must provide operator==(),operator<=(), andoperator>=()`. If DataT supports not-a-number (NaN) values, such values are ignored. If the container is empty, the return values are NaN (if supported) or std::numeric_limits<DataT>::max() for the minimum and std::numeric_limits<DataT>::lowest() for the maximum.

This behaves like (symbolic code):

std::minmax_element(std::transform(mycontainer, accessor))

without constructing a temporary container and without the ownership problems that would arise from minmax_element usage on a temporary container.

Hint: If looking for iterators to the minimum and maximum element instead of their values, use std::minmax_element() from the STL algorithm collection.

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element
Returns
the minimum and maximum values stored in a MinMax<DataT> object.
Template Parameters
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
min_max(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.
minimum() returns only the minimum value, maximum() only the maximum value.

References accumulate().

◆ min_max() [2/2]

template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::min_max ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> MinMax<DataT>

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
min_max(ContainerT const&, Accessor) accepts a container instead of iterators.

◆ minimum() [1/2]

template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::minimum ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> DataT

Return the minimum element value in a container.

The value of each element is determined through the accessor function. The minimum value is returned. Its type (DataT, the return type of the accessor) must provide operator==() and operator>=(). If DataT supports not-a-number (NaN) values, such values are ignored. If the container is empty, the return value is NaN (if supported) or std::numeric_limits<DataT>::max().

Hint: If looking for an iterator to the minimum element instead of its value, use std::min_element() from the STL algorithm collection.

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element.
Returns
the minimum value.
Template Parameters
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
minimum(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.
maximum() returns the maximum value, min_max() returns both the minimum and the maximum.
Since
GUL version 2.2

References accumulate().

◆ minimum() [2/2]

template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::minimum ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> DataT

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
max(ContainerT const&, Accessor) accepts a container instead of iterators.

◆ remove_outliers() [1/3]

template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::remove_outliers ( ContainerT &&  cont,
std::size_t  outliers,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ContainerT&

Remove elements that are far away from other elements.

The element whose value differs the most from the arithmetic mean of all elements is removed. This process is repeated if more than one outlier is to be removed; specifically, the mean is recalculated from the remaining elements.

The original container is modified. The container needs to be modifiable and have the erase() member function.

Parameters
contContainer of the elements to examine
outliersHow many outliers shall be removed
accessorHelper function to access the numeric value of one container element
Returns
the container passed in as cont after removal of outliers.
Template Parameters
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT

References abs(), and mean().

◆ remove_outliers() [2/3]

template<typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::remove_outliers ( ContainerT const &  cont,
std::size_t  outliers,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> std::vector<ElementT>

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

A copy of the original container without the outlier elements is returned.

References remove_outliers().

◆ remove_outliers() [3/3]

template<typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::remove_outliers ( IteratorT const &  begin,
IteratorT const &  end,
std::size_t  outliers,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> std::vector<ElementT>

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

A copy of the original container with the outerlier elements removed is returned.

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
outliersHow many outliers shall be removed
accessorHelper function to access the numeric value of one container element

Referenced by remove_outliers().

◆ repeat()

std::string gul14::repeat ( gul14::string_view  str,
std::size_t  n 
)

Repeat a string N times.

std::string str = repeat("du", 3); // str == "dududu"
GUL_EXPORT std::string repeat(gul14::string_view str, std::size_t n)
Repeat a string N times.
Definition: string_util.cc:32
Parameters
strString to be repeated
nNumber of repetitions
Returns
the N-fold concatenation of the input string.
Since
GUL version 2.7

◆ replace()

std::string gul14::replace ( string_view  haystack,
string_view  needle,
string_view  hammer 
)

Replace all occurrences of a string within another string, returning the result as a std::string.

Specifically, replace all occurrences of needle within haystack by hammer.

Parameters
haystackThe string in which search&replace should take place.
needleThe string to be searched for. If this is an empty string, a copy of haystack is returned.
hammerThe replacement string.

◆ replace_inplace()

std::string & gul14::replace_inplace ( std::string &  haystack,
string_view  needle,
string_view  hammer 
)

Replace all occurrences of a string within another string in-place.

This function replaces all occurrences of needle within haystack by hammer and returns a reference to the modified haystack.

Parameters
haystackThe string in which search&replace should take place.
needleThe string to be searched for. If this is an empty string, haystack is not changed.
hammerThe replacement string.
Returns
the altered haystack.

◆ rms() [1/2]

template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::rms ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

Calculate the root mean square of all elements in a container.

The rms value is calculated as the square root of the sum of all squared elements divided by the number of elements: rms -> sqrt (sum 0..n-1 (element i * element i) / n)

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element
Returns
the rms value.
Template Parameters
ResultTType of the result value
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
rms(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.

References accumulate().

◆ rms() [2/2]

template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::rms ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> ResultT

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
rms(ContainerT const&, Accessor) accepts a container instead of iterators.

◆ safe_string()

std::string gul14::safe_string ( const char *  char_ptr,
std::size_t  length 
)

Safely construct a std::string from a char pointer and a length.

If the pointer is null, an empty string is constructed. If there are no zero bytes in the input range, a string of length length is constructed. Otherwise, the input string is treated as a C string and the first zero byte is treated as the end of the string.

auto a = safe_string(nullptr, 5); // a == ""s
auto b = safe_string("ABC", 2); // b == "AB"s
auto c = safe_string("ABC", 4); // c == "ABC"s, trailing zero byte ends the string
auto d = safe_string("AB\0CD", 5); // d == "AB"s, intermediate zero byte ends the string
GUL_EXPORT std::string safe_string(const char *char_ptr, std::size_t length)
Safely construct a std::string from a char pointer and a length.
Definition: string_util.cc:43
Parameters
char_ptrPointer to a C string, an unterminated string of at least the specified length, or null.
lengthMaximum length of the generated string.
Since
GUL version 2.6

◆ sleep() [1/4]

template<class Rep , class Period >
bool gul14::sleep ( const std::chrono::duration< Rep, Period > &  duration)

Sleep for a given time span.

This is equivalent to a call of std::this_thread::sleep_for(), which means that control is handed back to the operating system's task scheduler. This may result in a somewhat bigger effective delay than expected, especially where very small sleep times are requested and the system load is high.

Example:

using namespace std::literals; // for the "ms" suffix
sleep(50ms); // Wait 50 milliseconds
bool sleep(const std::chrono::duration< Rep, Period > &duration, const Trigger &trg)
Sleep for at least the given time span, with the option of being woken up from another thread.
Definition: time_util.h:109
Parameters
durationTime span to wait, as a std::chrono::duration type.
Returns
true to signalize that the entire requested sleep duration has passed. This is for symmetry with the interruptible version of sleep() only.

◆ sleep() [2/4]

template<class Rep , class Period >
bool gul14::sleep ( const std::chrono::duration< Rep, Period > &  duration,
const Trigger trg 
)

Sleep for at least the given time span, with the option of being woken up from another thread.

The sleep can be interrupted from another thread via a shared Trigger object.

Calling sleep() may lead to a context switch of the operation system. Under heavy load or resource contention, this can produce a delay that is longer than expected.

Parameters
durationTime span to wait, as a std::chrono::duration type.
trgReference to a SleepInterrupt object that can be used to interrupt the delay. If such an interruption occurs, false is returned.
Returns
true if the entire requested sleep duration has passed, or false if the sleep has been interrupted prematurely via the Trigger object.
See also
Trigger

References gul14::Trigger::wait_for().

Referenced by sleep().

◆ sleep() [3/4]

bool gul14::sleep ( double  seconds)
inline

Sleep for a given number of seconds.

This is equivalent to a call of std::this_thread::sleep_for(), which means that control is handed back to the operating system's task scheduler. This may result in a somewhat bigger effective delay than expected, especially where very small sleep times are requested and the system load is high.

Example:

sleep(0.05); // Wait 50 milliseconds
Parameters
secondsSeconds to wait.
Returns
true to signalize that the entire requested sleep duration has passed. This is for symmetry with the interruptible version of sleep() only.

References sleep().

◆ sleep() [4/4]

bool gul14::sleep ( double  seconds,
const Trigger trg 
)
inline

Sleep for a given number of seconds, with the option of being woken up from another thread.

The sleep can be interrupted from another thread via a shared Trigger object.

Calling sleep() may lead to a context switch of the operation system. Under heavy load or resource contention, this can produce a delay that is longer than expected.

Parameters
secondsSeconds to wait.
trgReference to a SleepInterrupt object that can be used to interrupt the delay. If such an interruption occurs, false is returned.
Returns
true if the entire requested sleep duration has passed, or false if the sleep has been interrupted prematurely via the Trigger object.
See also
Trigger

References sleep().

◆ split() [1/2]

template<typename StringContainer = std::vector<std::string>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer gul14::split ( string_view  text,
const std::regex &  delimiter,
ContainerInsertFct  insert_fct = detail::emplace_back<StringContainer> 
)
inline

Separate a string at all occurrences of a delimiter described by a regular expression, returning the strings between the delimiters in a container.

This function is a variant of split(string_view, string_view, ContainerInsertFct) that accepts a std::regex object to describe the delimiter:

// Return type is std::vector<std::string>
auto parts = split("one\ntwo\nthree"s, std::regex{"[^[:print:]]"});
assert(y.size() == 3);
assert(y[0] == "one"s);
assert(y[1] == "two"s);
assert(y[2] == "three"s);
StringContainer split(string_view text, string_view delimiter, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in ...
Definition: join_split.h:117
Parameters
textThe string to be split
delimiterA std::regex object describing the delimiters
insert_fctCustom container inserter function
See also
split(string_view, string_view, ContainerInsertFct) splits at a fixed substring,
split_sv() does the same returning a vector of string_views, and
join() can join the vector back into a string.

◆ split() [2/2]

template<typename StringContainer = std::vector<std::string>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer gul14::split ( string_view  text,
string_view  delimiter,
ContainerInsertFct  insert_fct = detail::emplace_back<StringContainer> 
)
inline

Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in a container.

The result has at least one element. If the delimiter is not present in the text, the whole text is returned. If there are consecutive delimiters, the collected string between them is the empty string. If the delimiter is directly at the end of the input, the collected string between the end of the input and the delimiter is again the empty string.

split() is the inverse function of join(). It is guaranteed that join(split(text, del), del) == text.

std::vector<std::string> parts1 = split(" hello world", " ");
assert(parts1.size() == 3);
assert(parts1[0] == ""s);
assert(parts1[1] == "hello"s);
assert(parts1[2] == "world"s);
std::vector<std::string> parts2 = split("<>", "<>");
assert(parts2.size() == 2);
assert(parts2[0] == ""s);
assert(parts2[1] == ""s);

This function returns a std::vector<std::string> by default, but a compatible container for string/string_view types can be specified via a template parameter:

Template Parameters
StringContainerA container for strings or string_view-like types, e.g. std::vector<std::string> or std::list<gul14::string_view>
ContainerInsertFctType for the insert_fct function parameter.
Parameters
textThe string to be split
delimiterThe delimiting substring
insert_fctBy default, split() calls the emplace_back() member function on the container to insert strings. This parameter may contain a different function pointer or object with the signature void f(StringContainer&, gul14::string_view) that is called instead. This can be useful for containers that do not provide emplace_back() or for other customizations.
Returns
a container filled with the substrings that were separated by delimiter in the original string.
// Different string type
auto parts1 = split<std::vector<gul14::string_view>>("Hello world", " "); // behaves like split_sv()
assert(parts1.size() == 2);
assert(parts1[0] == "Hello"); // No lifetime problems because "Hello world" is a
assert(parts1[1] == "world"); // string literal with static storage duration
// Custom container type
auto parts2 = split<gul14::SmallVector<std::string, 3>>("a--b--c", "--");
assert(parts2.size() == 3);
assert(parts2[0] == "a");
assert(parts2[1] == "b");
assert(parts2[2] == "c");
// For a container without emplace_back(), use a custom inserter:
using WeirdContainer = std::queue<std::string>;
auto inserter = [](WeirdContainer& c, gul14::string_view sv) { c.emplace(sv); };
auto parts3 = split<WeirdContainer>("a.b", ".", inserter);
assert(parts3.size() == 2);
assert(parts3.front() == "a");
assert(parts3.back() == "b");
See also
split_sv() returns a vector of string_views,
split(const std::string&, const std::regex&) splits at a delimiter described by a regular expression, and
join() can join the vector back into a string.
Since
GUL version 2.5, the return type of split() can be specified as a template parameter and a custom inserter can be specified (it always returned std::vector<std::string> before).

◆ split_sv()

template<typename StringContainer = std::vector<string_view>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer gul14::split_sv ( string_view  text,
string_view  delimiter,
ContainerInsertFct  insert_fct = detail::emplace_back<StringContainer> 
)
inline

Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in a vector.

This function is identical to split(string_view, string_view, ContainerInsertFct) except that it returns a std::vector of string_views instead of strings by default:

auto parts = split_sv("hello world", " "); // Return type is std::vector<gul14::string_view>
assert(parts.size() == 2);
assert(parts[0] == "hello"); // No problems with lifetime because "hello world"
assert(parts[1] == "world"); // is a string literal with static storage duration
StringContainer split_sv(string_view text, string_view delimiter, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in ...
Definition: join_split.h:221
See also
split(string_view, string_view, ContainerInsertFct) returns a vector of strings,
split(const std::string&, const std::regex&) splits at a delimiter described by a regular expression, and
join() can join the vector back into a string.
Since
GUL version 2.5, the return type of split_sv() can be specified as a template parameter and a custom inserter can be specified (it always returned std::vector<std::string> before).

◆ standard_deviation() [1/2]

template<typename ResultT = statistics_result_type, typename ContainerT , typename ElementT = typename ContainerT::value_type, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = typename std::decay_t<std::result_of_t<Accessor(ElementT)>>, typename = std::enable_if_t<IsContainerLike<ContainerT>::value>>
auto gul14::standard_deviation ( ContainerT const &  container,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> StandardDeviationMean<ResultT>

Calculate the standard deviation of all elements in a container.

The corrected sample standard deviation is calculated: standard_deviation -> sqrt (sum 0..n-1 ((element i - mean) * (element i - mean)) / (n - 1))

The returned StandardDeviationMean object can be used like this:

const StandardDeviationMean std_and_mean = standard_deviation(something);
const double std = std_and_mean.sigma();
const double mean = std_and_mean.mean();
// The cast operator is for people that want to ignore the complicated stuff like this
const double std = standard_deviation(something);
const float std = standard_deviation(something); // implicit conversions possible
// Structured binding (C++17)
const auto [std, mean] = standard_deviation(something);
auto mean(ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> ResultT
Calculate the arithmetic mean value of all elements in a container.
Definition: statistics.h:161
auto standard_deviation(ContainerT const &container, Accessor accessor=ElementAccessor< ElementT >()) -> StandardDeviationMean< ResultT >
Calculate the standard deviation of all elements in a container.
Definition: statistics.h:546

If the container is empty, not-a-number is returned for both the standard deviation and the mean value. If it contains only a single element, not-a-number is returned for the standard deviation and the mean value is the value of the element.

Parameters
containerContainer of the elements to examine
accessorHelper function to access the numeric value of one container element
Returns
the standard deviation and mean values as a StandardDeviationMean object.
Template Parameters
ResultTType of the result value
ContainerTType of the container to examine
ElementTType of an element in the container, i.e. ContainerT::value_type
AccessorType of the accessor function
DataTType returned by the accessor, i.e. numeric value of ElementT
See also
standard_deviation(IteratorT const&, IteratorT const&, Accessor) accepts two iterators instead of a container.

References accumulate().

◆ standard_deviation() [2/2]

template<typename ResultT = statistics_result_type, typename IteratorT , typename ElementT = std::decay_t<decltype(*std::declval<IteratorT>())>, typename Accessor = std::result_of_t<decltype(ElementAccessor<ElementT>())(ElementT)>(*)(ElementT const&), typename DataT = std::decay_t<std::result_of_t<Accessor(ElementT)>>>
auto gul14::standard_deviation ( IteratorT const &  begin,
IteratorT const &  end,
Accessor  accessor = ElementAccessor<ElementT>() 
) -> StandardDeviationMean<ResultT>

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

Parameters
beginIterator to first elements to examine in the container
endIterator past the last element to examine in the container
accessorHelper function to access the numeric value of one container element
See also
standard_deviation(ContainerT const&, Accessor) accepts a container instead of iterators.

◆ starts_with() [1/2]

constexpr bool gul14::starts_with ( string_view  str,
char  c 
)
inlineconstexprnoexcept

Determine whether a string starts with a certain character.

The comparison is case sensitive.

Parameters
strThe string to be tested.
cThe character to be looked for at the beginning of str.
Returns
true if str starts with c, false otherwise.
See also
starts_with(string_view, string_view), starts_with_nocase(string_view, char), ends_with(string_view, char), contains(string_view, char)

◆ starts_with() [2/2]

constexpr bool gul14::starts_with ( string_view  str,
string_view  prefix 
)
inlineconstexprnoexcept

Determine whether a string starts with another string.

The comparison is case sensitive. If the searched-for prefix is empty, the result is true.

Parameters
strThe full string to be tested.
prefixThe prefix to be looked for at the beginning of str.
Returns
true if str starts with prefix, false otherwise.
See also
starts_with(string_view, char), starts_with_nocase(string_view, string_view), ends_with(string_view, string_view), contains(string_view, string_view)

◆ starts_with_nocase() [1/2]

constexpr bool gul14::starts_with_nocase ( string_view  str,
char  c 
)
inlineconstexprnoexcept

Determine whether a string starts with a certain character.

The comparison is case insensitive as far as ASCII characters are concerned (C locale).

Parameters
strThe string to be tested.
cThe character to be looked for at the beginning of str.
Returns
true if str starts with c, false otherwise.
Since
GUL version 1.7
See also
starts_with_nocase(string_view, string_view), starts_with(string_view, char), ends_with_nocase(string_view, char), contains_nocase(string_view, char)

References lowercase_ascii().

◆ starts_with_nocase() [2/2]

constexpr bool gul14::starts_with_nocase ( string_view  str,
string_view  prefix 
)
inlineconstexprnoexcept

Determine whether a string starts with another string.

The comparison is case insensitive as far as ASCII characters are concerned (C locale). If the searched-for prefix is empty, the result is true.

Parameters
strThe full string to be tested.
prefixThe prefix to be looked for at the beginning of str.
Returns
true if str starts with prefix, false otherwise.
Since
GUL version 1.7
See also
starts_with_nocase(string_view, char), starts_with(string_view, string_view), ends_with_nocase(string_view, string_view), contains_nocase(string_view, string_view)

References lowercase_ascii().

◆ swap()

template<typename ElementT , size_t in_capacity>
void gul14::swap ( SmallVector< ElementT, in_capacity > &  a,
SmallVector< ElementT, in_capacity > &  b 
)

Exchange the contents of one SmallVector with those of another one.

If either this or the other vector have internally stored elements (capacity() <= inner_capacity()), this function falls back to element-wise swapping. Otherwise, the heap-allocated buffers are swapped directly.

References gul14::SmallVector< ElementT, in_capacity >::swap().

◆ tic()

std::chrono::steady_clock::time_point gul14::tic ( )
inline

Return the current time as a std::chrono time_point.

This function is intended to be used with the sister function toc() to measure elapsed time.

Example

auto t0 = tic();
// Do some work
std::cout << "Elapsed time: " << toc(t0) << " seconds.\n";
auto toc(std::chrono::steady_clock::time_point t0)
Return the elapsed time in seconds (or a different unit) since the given time point.
Definition: time_util.h:87
std::chrono::steady_clock::time_point tic()
Return the current time as a std::chrono time_point.
Definition: time_util.h:49
See also
toc()

Referenced by toc().

◆ to_number()

template<typename NumberType , std::enable_if_t< std::is_integral< NumberType >::value &&std::is_unsigned< NumberType >::value, int > = 0>
constexpr optional< NumberType > gul14::to_number ( gul14::string_view  str)
inlineconstexprnoexcept

Convert an ASCII string_view into a number.

This function parses the ASCII representation of a number (e.g. "123" or "1.3e10") into an optional integer or floating-point number.

gul14::optional<int> result = gul14::to_number<int>("42");
if (result.has_value())
std::cout << "The answer is " << result.value() << ".\n";
if (result)
std::cout << "The answer is " << *result << ".\n";
A class template that can either contain a value of a certain type or not.
Definition: optional.h:272

Design Goals

to_number() shares many characteristics with std::atoi(), std::stod() and the like, but follows its own set of design goals:

  • Its input type is string_view: No null-termination and no temporary std::string are required for the conversion.
  • Conversion errors are reported by returning a gul14::optional without a value.
  • The function does not allocate.
  • Performance should in most cases be better than and in few cases not much worse than std::sto[ildf].
  • to_number<>() can be used in a constexpr context if the compiler and standard library support this. Support for floating-point numbers may lack even if integer conversion works.

Input Format

The allowed number format depends on the chosen numeric output type.

Unsigned integral types
  • Accept only digits ("123", "042"=42).
Signed integral types
  • Allow additionally a leading minus sign as well ("-42"). No leading plus sign is allowed, though.
Floating-point types

Recognize additionally

  • A decimal point ("1.2", ".5", "12.") and exponential notation using a small or capital "e" ("12e5", "4.2e1", ".2e-4", "2.E5").
  • Infinity expressions: (optional minus sign) INF or INFINITY ignoring case.
  • Not-a-number expressions: (optional minus sign) NAN or NAN(char_sequence) ignoring case. The char_sequence can only contain digits, Latin letters, and underscores. The result is a quiet NaN floating-point value.

The behavior with surrounding whitespace is undefined, so it should be removed before passing input to this function. This means to_number() accepts a subset of C++17's from_chars() input format; where it supports the input format it is modeled close to from_chars().

Template Parameters
NumberTypeDestination numeric type
Parameters
strThe string to be converted into a number.
Returns
a gul14::optional that contains the number if the conversion was successful. If there was a conversion error, the return value is empty. If the input describes a number whose parsed value is not in the range representable by NumberType, the return value is empty.
Note
This function has different overloads for unsigned integers, signed integers, and floating-point types.
The floating-point overload allocates an intermediate string if
  • the intermediate integer type is too small in comparison to NumberType or
  • this function is used with long double on Apple Clang.
Since
GUL version 1.6
GUL version 1.7 the NAN and INF floating point conversion

◆ toc()

template<class TimeUnitType = std::chrono::duration<double>>
auto gul14::toc ( std::chrono::steady_clock::time_point  t0)

Return the elapsed time in seconds (or a different unit) since the given time point.

This function is intended to be used with the sister function tic() to measure elapsed time. toc() is a function template that returns the elapsed seconds as a double value by default; by specifying a different chrono type as a template parameter, it can also return other time units and other types.

Example

auto t0 = tic();
// <do some work>
// Default: Return seconds as a double
std::cout << "Elapsed time: " << toc(t0) << " seconds.\n";
// Custom type: Return milliseconds as an integer
std::cout << "Elapsed time: " << toc<std::chrono::milliseconds>(t0) << " milliseconds.\n";
Template Parameters
TimeUnitTypeThe type to be used for calculating the elapsed time since t0. By default, this is std::chrono::duration<double>, which means that the elapsed time is returned as a double that represents seconds.
Parameters
t0A time point in the past that should be taken with tic().
Returns
the elapsed time in the units and base representation of TimeUnitType. By default, this is a double that represents elapsed seconds. For a TimeUnitType of std::chrono::milliseconds, it would be an integer representing elapsed milliseconds.
See also
tic()

References tic().

◆ tokenize()

template<typename StringContainer = std::vector<std::string>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer gul14::tokenize ( string_view  str,
string_view  delimiters = default_whitespace_characters,
ContainerInsertFct  insert_fct = detail::emplace_back<StringContainer> 
)
inline

Split the given string into a vector of substrings (tokens) delimited by any of the characters in the delimiters string.

Multiple adjacent delimiters are treated like a single one, and delimiters at the beginning and end of the string are ignored. For example, tokenize(" A B C ") yields a vector with the three entries "A", "B", and "C".

// Default return type std::vector<std::string>
auto tokens = tokenize(" Hello world ");
assert(tokens.size() == 2);
assert(tokens[0] == "Hello");
assert(tokens[1] == "world");
StringContainer tokenize(string_view str, string_view delimiters=default_whitespace_characters, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
Split the given string into a vector of substrings (tokens) delimited by any of the characters in the...
Definition: tokenize.h:110

This function returns a std::vector<std::string> by default, but a compatible container for string/string_view types can be specified via a template parameter:

Template Parameters
StringContainerA container for strings or string_view-like types, e.g. std::vector<std::string> or std::list<gul14::string_view>
ContainerInsertFctType for the insert_fct function parameter.
Parameters
strThe string to be split.
delimitersString with delimiter characters. Any of the characters in this string marks the beginning/end of a token. By default, a wide variety of whitespace and control characters is used.
insert_fctBy default, tokenize() calls the emplace_back() member function on the container to insert strings. This parameter may contain a different function pointer or object with the signature void f(StringContainer&, gul14::string_view) that is called instead. This can be useful for containers that do not provide emplace_back() or for other customizations.
Returns
a container with the single substrings.
// Return string_views instead of strings (like tokenize_sv())
auto parts1 = tokenize<std::vector<gul14::string_view>>("Hello world");
assert(parts1.size() == 2);
assert(parts1[0] == "Hello");
assert(parts1[1] == "world");
// Use a different container that provides emplace_back()
auto parts2 = tokenize<gul14::SmallVector<gul14::string_view, 3>>("a-b-c", "-");
assert(parts2.size() == 3);
assert(parts2[0] == "a");
assert(parts2[1] == "b");
assert(parts2[2] == "c");
// Use a different container with a custom inserter function
using WeirdContainer = std::queue<std::string>;
auto inserter = [](WeirdContainer& c, gul14::string_view sv) { c.emplace(sv); };
auto parts3 = tokenize<WeirdContainer>("a.b", ".", inserter);
assert(parts3.size() == 2);
assert(parts3.front() == "a");
assert(parts3.back() == "b");
Note
tokenize() does not assume a specific encoding for its input strings, but operates on individual chars. This can have surprising effects in code such as this:
auto words = tokenize("Hörgeräteakkustiker hätten es gewußt", "ä");
assert(words.size() == 3); // Might fail or succeed depending on the encoding
See also
gul14::tokenize_sv() returns a vector<string_view> by default, gul14::split() uses a different approach to string splitting.
Since
GUL version 2.5, the return type of split() can be specified as a template parameter and a custom inserter can be specified (it always returned std::vector<std::string> before).

◆ tokenize_sv()

template<typename StringContainer = std::vector<string_view>, typename ContainerInsertFct = void (*)(StringContainer&, string_view)>
StringContainer gul14::tokenize_sv ( string_view  str,
string_view  delimiters = default_whitespace_characters,
ContainerInsertFct  insert_fct = detail::emplace_back<StringContainer> 
)
inline

Split the given string into a vector of substrings (tokens) delimited by any of the characters in the delimiters string.

This function is identical to tokenize(string_view, string_view, ContainerInsertFct) except that it returns a std::vector of string_views instead of strings by default:

auto tokens = tokenize_sv("hello world", " "); // Return type is std::vector<gul14::string_view>
assert(tokens.size() == 2);
assert(tokens[0] == "hello");
assert(tokens[1] == "world");
StringContainer tokenize_sv(string_view str, string_view delimiters=default_whitespace_characters, ContainerInsertFct insert_fct=detail::emplace_back< StringContainer >)
Split the given string into a vector of substrings (tokens) delimited by any of the characters in the...
Definition: tokenize.h:164
See also
gul14::tokenize() returns a vector<string> by default, gul14::split() uses a different approach to string splitting.
Since
GUL version 2.5, the return type of tokenize_sv() can be specified as a template parameter and a custom inserter can be specified (it always returned std::vector<gul14::string_view> before).

◆ trim()

std::string gul14::trim ( string_view  str,
string_view  ws_chars = default_whitespace_characters 
)

Trim leading and trailing whitespace (or a custom set of characters) from a string, returning a new std::string.

Which characters are removed can be customized via the ws_chars parameter.

cout << "[" << trim("\n \b trim(), default whitespace\t \r") << "]\n";
// prints "[trim(), default whitespace]"
cout << "[" << trim(".:.:.:trim(), custom whitespace.:.:.:.", ".:") << "]\n";
// prints "[trim(), custom whitespace]"
GUL_EXPORT std::string trim(string_view str, string_view ws_chars=default_whitespace_characters)
Trim leading and trailing whitespace (or a custom set of characters) from a string,...
Definition: trim.cc:29
Parameters
strThe string that should be trimmed.
ws_charsA string containing all the characters that should be treated as whitespace (i.e. that are trimmed). If this is empty, no characters are trimmed.
Returns
a trimmed copy of the input string.
See also
trim_sv() returns a string_view instead of a copied string,
trim_left() and trim_right() trim only one side of the string,
trim_left_sv() and trim_right_sv() trim only one side and return a string_view.
Examples
trim.cc.

References trim_sv().

◆ trim_left()

std::string gul14::trim_left ( string_view  str,
string_view  ws_chars = default_whitespace_characters 
)

Trim leading whitespace (or a custom set of characters) from a string, returning a new std::string.

Which characters are removed can be customized via the ws_chars parameter.

cout << "[" << trim_left("\n \b trim_left(), default whitespace ") << "]\n";
// prints "[trim_left(), default whitespace ]"
cout << "[" << trim_right(".:.:.:trim_right(), custom whitespace.:.:.:.", ".:") << "]\n";
// prints "[.:.:.:trim_right, custom whitespace]"
GUL_EXPORT std::string trim_left(string_view str, string_view ws_chars=default_whitespace_characters)
Trim leading whitespace (or a custom set of characters) from a string, returning a new std::string.
Definition: trim.cc:46
GUL_EXPORT std::string trim_right(string_view str, string_view ws_chars=default_whitespace_characters)
Trim trailing whitespace (or a custom set of characters) from a string, returning a new std::string.
Definition: trim.cc:61
Parameters
strThe string from which leading characters should be trimmed.
ws_charsA string containing all the characters that should be treated as whitespace (i.e. that are trimmed). If this is empty, no characters are trimmed.
Returns
a trimmed copy of the input string.
See also
trim_left_sv() returns a string_view instead of a copied string,
trim_right() and trim_right_sv() trim the other side of the string,
trim() and trim_sv() trim both sides of the string.
Examples
trim.cc.

References trim_left_sv().

◆ trim_left_sv()

string_view gul14::trim_left_sv ( string_view  str,
string_view  ws_chars = default_whitespace_characters 
)

Trim leading whitespace (or a custom set of characters) from a string, returning a view into the original string.

Which characters are removed can be customized via the ws_chars parameter.

cout << "[" << trim_left_sv("\n \b trim_left_sv(), default whitespace ") << "]\n";
// prints "[trim_left_sv(), default whitespace ]"
cout << "[" << trim_right_sv(".:.:.:trim_right_sv(), custom whitespace.:.:.:.", ".:") << "]\n";
// prints "[.:.:.:trim_right_sv, custom whitespace]"
GUL_EXPORT string_view trim_right_sv(string_view str, string_view ws_chars=default_whitespace_characters)
Trim trailing whitespace (or a custom set of characters) from a string, returning a view into the ori...
Definition: trim.cc:66
GUL_EXPORT string_view trim_left_sv(string_view str, string_view ws_chars=default_whitespace_characters)
Trim leading whitespace (or a custom set of characters) from a string, returning a view into the orig...
Definition: trim.cc:51
Parameters
strThe string from which leading characters should be trimmed.
ws_charsA string containing all the characters that should be treated as whitespace (i.e. that are trimmed). If this is empty, no characters are trimmed.
Returns
a trimmed string_view that points into the input string.
See also
trim_left() returns a copied string instead of a string_view,
trim_right() and trim_right_sv() trim the other side of the string,
trim() and trim_sv() trim both sides of the string.
Examples
trim.cc.

Referenced by trim_left().

◆ trim_right()

std::string gul14::trim_right ( string_view  str,
string_view  ws_chars = default_whitespace_characters 
)

Trim trailing whitespace (or a custom set of characters) from a string, returning a new std::string.

Which characters are removed can be customized via the ws_chars parameter.

cout << "[" << trim_left("\n \b trim_left(), default whitespace ") << "]\n";
// prints "[trim_left(), default whitespace ]"
cout << "[" << trim_right(".:.:.:trim_right(), custom whitespace.:.:.:.", ".:") << "]\n";
// prints "[.:.:.:trim_right, custom whitespace]"
Parameters
strThe string from which trailing characters should be trimmed.
ws_charsA string containing all the characters that should be treated as whitespace (i.e. that are trimmed). If this is empty, no characters are trimmed.
Returns
a trimmed copy of the input string.
See also
trim_right_sv() returns a string_view instead of a copied string,
trim_left() and trim_left_sv() trim the other side of the string,
trim() and trim_sv() trim both sides of the string.
Examples
trim.cc.

References trim_right_sv().

◆ trim_right_sv()

string_view gul14::trim_right_sv ( string_view  str,
string_view  ws_chars = default_whitespace_characters 
)

Trim trailing whitespace (or a custom set of characters) from a string, returning a view into the original string.

Which characters are removed can be customized via the ws_chars parameter.

cout << "[" << trim_left_sv("\n \b trim_left_sv(), default whitespace ") << "]\n";
// prints "[trim_left_sv(), default whitespace ]"
cout << "[" << trim_right_sv(".:.:.:trim_right_sv(), custom whitespace.:.:.:.", ".:") << "]\n";
// prints "[.:.:.:trim_right_sv, custom whitespace]"
Parameters
strThe string from which trailing characters should be trimmed.
ws_charsA string containing all the characters that should be treated as whitespace (i.e. that are trimmed). If this is empty, no characters are trimmed.
Returns
a trimmed string_view that points into the input string.
See also
trim_right() returns a copied string instead of a string_view,
trim_left() and trim_left_sv() trim the other side of the string,
trim() and trim_sv() trim both sides of the string.
Examples
trim.cc.

Referenced by trim_right().

◆ trim_sv()

string_view gul14::trim_sv ( string_view  str,
string_view  ws_chars = default_whitespace_characters 
)

Trim leading and trailing whitespace (or a custom set of characters) from a string, returning a view into the original string.

Which characters are removed can be customized via the ws_chars parameter.

std::string str = " string_view ";
auto sv = trim_sv(str); // sv is a string_view that points to the original string
cout << "[" << sv << "]\n";
// prints "[string_view]"
str[5] = 'o'; // modify the original string
cout << "[" << sv << "]\n";
// prints "[strong_view]"
GUL_EXPORT string_view trim_sv(string_view str, string_view ws_chars=default_whitespace_characters)
Trim leading and trailing whitespace (or a custom set of characters) from a string,...
Definition: trim.cc:34
Parameters
strThe string that should be trimmed.
ws_charsA string containing all the characters that should be treated as whitespace (i.e. that are trimmed). If this is empty, no characters are trimmed.
Returns
a trimmed string_view that points into the input string.
See also
trim() returns a copied string instead of a string_view,
trim_left_sv() and trim_right_sv() trim only one side of the string,
trim_left() and trim_right() trim only one side and return a copied string.
Examples
trim.cc.

Referenced by trim().

◆ type_name()

template<class T >
constexpr string_view gul14::type_name ( )
constexpr

Generate a human readable string describing a type.

Cuts out the most relevant part of __PRETTY_FUNCTION__ of itself, ignoring all the stuff that contains information on the function itself, leaving just the description of the template parameter.

Note: __FUNCSIG__ with MSVC.

This function can only be constexpr if __PRETTY_FUNCTION__ is constexpr. This function is not constexpr with MSVC because of language limits.

Use like this:

auto& literal = "test";
std::cout << "The type is " << gul14::type_name<decltype(literal)>() << '\n';
Template Parameters
TType that shall be described
Returns
a string view that describes the type of the template parameter

◆ unescape()

GUL_EXPORT std::string gul14::unescape ( string_view  in)

Evaluate a string with escaped characters to get the original string back.

Does only know the escape sequences used by gul14::escape() and can be used as in inverse function.

Parameters
inThe string with escape sequences
Returns
A new string where the sequences have been evaluated
Since
GUL version 1.4 parameter in is a string_view (was std::string before)

◆ uppercase_ascii() [1/2]

constexpr char gul14::uppercase_ascii ( char  c)
constexprnoexcept

Return the ASCII uppercase equivalent of the given character (or the unchanged character, if it is not an ASCII letter).

Parameters
cThe original character.
Since
GUL version 1.2
See also
uppercase_ascii(gul14::string_view), uppercase_ascii_inplace(std::string &), lowercase_ascii(char)

Referenced by uppercase_ascii(), and uppercase_ascii_inplace().

◆ uppercase_ascii() [2/2]

std::string gul14::uppercase_ascii ( gul14::string_view  str)

Return a copy of the given string in which all ASCII characters are replaced by their uppercase equivalents.

Parameters
strThe original string.
Since
GUL version 1.2
See also
uppercase_ascii(char), uppercase_ascii_inplace(std::string &), lowercase_ascii(gul14::string_view)

References uppercase_ascii().

◆ uppercase_ascii_inplace()

std::string & gul14::uppercase_ascii_inplace ( std::string &  str)
noexcept

Replace all ASCII characters in a string by their uppercase equivalents.

This function modifies the original string and returns a reference to it (which may be helpful for chaining function calls).

Parameters
strThe string to be modified.
Returns
a reference to the string argument.
Since
GUL version 1.2
See also
uppercase_ascii(char), uppercase_ascii(gul14::string_view), lowercase_ascii_inplace(std::string &)

References uppercase_ascii().

◆ within_abs()

template<typename NumT >
bool gul14::within_abs ( NumT  a,
NumT  b,
NumT  tol 
)
noexcept

Determine if two numbers are almost equal, allowing for an absolute difference.

All arguments must be the same numeric type (floating point or integer).

Parameters
aThe first number to compare
bThe second number to compare
tolThe absolute tolerance
Returns
true if the absolute difference between a and b is smaller than tol.

References abs().

◆ within_orders()

template<typename NumT , typename OrderT , typename = std::enable_if_t< std::is_arithmetic<NumT>::value and std::is_arithmetic<OrderT>::value >>
bool gul14::within_orders ( const NumT  a,
const NumT  b,
const OrderT  orders 
)
noexcept

Determine if two numbers are almost equal, comparing only some significant digits.

The functions compares the specified number of significant decimal digits of the two values and returns true if they are equal within these digits.

a = 23736384; b = 23736228; within_orders(a, b, 5) => true  (first 5 digits equal)
a = 23736384; b = 23735384; within_orders(a, b, 5) => false (digit #5 differs)

Unexpected behavior can result when orders is low (< 3) as the simple concept of orders equals digits does not hold so strict anymore.

Remember that any nonzero number has infinite different significant digits compared with 0.00000000. So if one operand is 0.0 while the other is not 0.0 the result must be false.

Parameters
aThe first number to compare
bThe second number to compare (same type as a)
ordersThe number of digits to take for comparison (any numeric type)
Returns
true if a and b are equal or the difference between a and b is orders orders of magnitude lower than the value of a or b
Since
GUL version 1.4 parameter type NumT can be an integral type (had to be floating point before)
GUL version 2.7.1 return true if a == b == 0.0

References abs(), and maximum().

◆ within_ulp()

template<typename NumT , typename = std::enable_if_t<std::is_floating_point<NumT>::value>>
bool gul14::within_ulp ( NumT  a,
NumT  b,
unsigned int  ulp 
)

Determine if two numbers are almost equal, allowing for a difference of a given number of units-in-the-last-place (ULPs).

One ULP is the spacing between two consecutive floating point representations. There are no possible values in between. Roughly speaking, one ULP is for floating point numbers what the 1 is for integral numbers.

All arguments must be of the same floating point type.

Parameters
aThe first number to compare
bThe second number to compare
ulpAllowed number of floating point steps in between
Returns
true if a and b are equal within the given number of ULPs.

References abs().

Variable Documentation

◆ default_whitespace_characters

const string_view gul14::default_whitespace_characters { " \t\r\n\a\b\f\v" }

The default characters that are treated as whitespace by GUL.

This is a string view that contains the space and the most common control characters, namely (with their ASCII codes):

  • Bell/alert (7)
  • Backspace (8)
  • Horizontal tabulator (9)
  • Newline/line feed (10)
  • Vertical Tab (11)
  • Form feed (12)
  • Carriage return (13)
  • Space (32)
Note
The null character is not treated as whitespace by default.

◆ hex_digits

const std::array< char, 16 > gul14::hex_digits
Initial value:
{
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'} }

The 16 digits for hexadecimal numbers ("0123456789abcdef").

Referenced by hex_string().

◆ version_git

GUL_EXPORT char const* gul14::version_git
extern

Holds the git version tag of the sources that the library has been build with.

It has the format returned by git describe –tags –always –dirty