userver: utils Namespace Reference
Loading...
Searching...
No Matches
utils Namespace Reference

Detailed Description

Utilities.

Namespaces

namespace  datetime
 Date and time utilities.
 
namespace  generators
 Generators.
 
namespace  log
 Algorithms to aid logging.
 
namespace  text
 Text utilities.
 

Classes

class  AnyMovable
 Replacement for std::any that is not copyable. It allows to store non-copyable and even non-movable types. More...
 
class  AnyStorage
 map-like heterogeneous data storage More...
 
class  AnyStorageDataTag
 
class  AtomicFlags
 Wrapper to extend enum with atomic flags interface. More...
 
class  bad_expected_access
 
class  BadAnyMovableCast
 The exception that is thrown when AnyCast fails. More...
 
class  Box
 Remote storage for a single item. Implemented as a unique pointer that is never null, except when moved from. More...
 
struct  CachedHash
 Holds the key and its hash for faster comparisons and hashing. More...
 
class  CachedHashKeyEqual
 Compares utils::CachedHash only by keys. More...
 
class  CachedHashKeyEqual< Equal, std::false_type >
 
class  CheckedPtr
 Utility template for returning a pointer to an object that is owned by someone else; throws std::runtime_error if nullptr is stored. More...
 
class  CheckedPtr< T & >
 
class  CpuRelax
 
class  CurrentThreadNameGuard
 RAII helper to run some code with a temporary current thread name. More...
 
class  DefaultDict
 Dictionary that for missing keys falls back to a default value stored by key utils::kDefaultDictDefaultName. More...
 
class  expected
 For holding a value or an error. More...
 
class  FastPimpl
 Implements pimpl idiom without dynamic memory allocation. More...
 
class  FastScopeGuard
 a helper class to perform actions on scope exit More...
 
class  FilterBloom
 Space-efficient probabilistic data structure. More...
 
class  FixedArray
 A fixed-size array with the size determined at runtime. More...
 
class  Flags
 Wrapper to extend enum with flags interface. More...
 
struct  HashSeed
 The seed structure used by underlying hashing implementation. More...
 
class  InvariantError
 Exception that is thrown on UINVARIANT violation. More...
 
class  LazyPrvalue
 Can be used with various emplace functions to allow in-place constructing a non-movable value using a callable. More...
 
class  LazySharedPtr
 A lazy wrapper around utils::SharedReadablePtr that fetches the data on first access. More...
 
class  MacaddrBase
 Base class for Macaddr/Macaddr8. More...
 
class  NotNull
 Restricts a pointer or smart pointer to only hold non-null values. More...
 
class  OptionalRef
 Class that behaves as a nullable reference. Main difference from the pointer - value comparison of pointed values. More...
 
struct  Overloaded
 Utility to define std::variant visitors in a simple way. More...
 
class  PeriodicTask
 Task that periodically runs a user callback. Callback is started after the previous callback execution is finished every period + A - B, where: More...
 
class  RandomBase
 Virtualized standard UniformRandomBitGenerator concept, for use with random number distributions. More...
 
class  regex
 Small alias for boost::regex / std::regex without huge includes. More...
 
class  ResultStore
 
class  ResultStore< void >
 
class  RetryBudget
 
struct  RetryBudgetSettings
 
class  ScopeGuard
 a helper class to perform actions on scope exit More...
 
class  ScopeTimePause
 Utility to easily pause ScopeTime, e.g. when yielding. More...
 
class  SharedReadablePtr
 std::shared_ptr<const T> wrapper that makes sure that the pointer is stored before dereferencing. Protects from dangling references: More...
 
class  SlidingInterval
 Sliding interval of values that provides functions to compute average, min and max values from the last window_size values of interval. More...
 
class  SmallString
 An alternative to std::string with a custom SSO (small string optimization) container size. Unlike std::string, SmallString is not null-terminated thus it has no c_str(), data() returns a not null-terminated buffer. More...
 
class  StrCaseHash
 Case sensitive ASCII hashing functor. More...
 
class  StreamingCpuRelax
 
class  StrIcaseCompareThreeWay
 Case insensitive ASCII 3-way comparison functor. More...
 
class  StrIcaseEqual
 Case insensitive ASCII equality comparison functor. More...
 
class  StrIcaseHash
 Case insensitive ASCII hashing functor. More...
 
class  StrIcaseLess
 Case insensitive ASCII less comparison functor. More...
 
class  StrongTypedef
 Strong typedef for a type T. More...
 
class  SwappingSmart
 
class  TokenBucket
 
class  TracefulException
 Exception that remembers the backtrace at the point of its construction. More...
 
class  TracefulExceptionBase
 Base class implementing backtrace storage and message builder, published only for documentation purposes, please inherit from utils::TracefulException instead. More...
 
class  TrivialBiMap
 Bidirectional unordered map for trivial types, including string literals; could be efficiently used as a unordered non-bidirectional map. More...
 
class  TrivialSet
 Unordered set for trivial types, including string literals. More...
 
class  unexpected
 

Typedefs

using Macaddr = MacaddrBase<6>
 48-bit MAC address
 
using Macaddr8 = MacaddrBase<8>
 64-bit MAC address
 
template<typename U >
using SharedRef = NotNull<std::shared_ptr<U>>
 A std::shared_ptr that is guaranteed to be not-null.
 
template<typename U >
using UniqueRef = NotNull<std::unique_ptr<U>>
 A std::unique_ptr that is guaranteed to be not-null.
 
template<typename Value , auto Projection, typename Hash = void, typename Equal = std::equal_to<>, typename Allocator = std::allocator<Value>>
using ProjectedUnorderedSet
 A std::unordered_set that compares its elements (of type Value) based on their Projection. It allows to create, essentially, an equivalent of std::unordered_map where keys are stored inside values.
 
template<typename Value , auto Projection, typename Compare = std::less<>, typename Allocator = std::allocator<Value>>
using ProjectedSet
 Same as ProjectedUnorderedSet, but for std::set.
 
template<class Tag , class T >
using NonLoggable
 
template<typename... T>
using void_t = std::void_t<T...>
 std::void_t implementation with workarounds for compiler bugs
 

Enumerations

enum class  BytesPerSecond : long long
 Data type that represents bytes per second unit. More...
 
enum class  StrongTypedefOps {
  kNoCompare = 0 ,
  kCompareStrong = 1 ,
  kCompareTransparentOnly = 2 ,
  kCompareTransparent = 3 ,
  kNonLoggable = 4
}
 

Functions

template<typename ResultString = std::string, typename... Strings>
ResultString StrCat (const Strings &... strings)
 Concatenates multiple std::string_view-convertible items.
 
template<class Map , class Key >
autoFindOrNullptr (Map &map, const Key &key)
 Returns nullptr if no key in associative container, otherwise returns pointer to value.
 
template<class Map , class Key , class Default >
Map::mapped_type FindOrDefault (Map &map, const Key &key, Default &&def)
 Returns default value if no key in associative container, otherwise returns a copy of the stored value.
 
template<class Map , class Key >
Map::mapped_type FindOrDefault (Map &map, const Key &key)
 Returns default value if no key in associative container, otherwise returns a copy of the stored value.
 
template<class Map , class Key >
std::optional< typename Map::mapped_type > FindOptional (Map &map, const Key &key)
 Returns std::nullopt if no key in associative container, otherwise returns std::optional with a copy of value.
 
template<typename Map , typename Key >
auto CheckedFind (Map &map, const Key &key) -> decltype(utils::MakeCheckedPtr(&map.find(key) ->second))
 Searches a map for an element and return a checked pointer to the found element.
 
template<class ToContainer , class FromContainer >
ToContainer AsContainer (FromContainer &&container)
 Converts one container type to another.
 
template<class Container , class Pred >
auto EraseIf (Container &container, Pred pred)
 Erased elements and returns number of deleted elements.
 
template<class Container , class T >
size_t Erase (Container &container, const T &elem)
 Erased elements and returns number of deleted elements.
 
template<typename Container , typename Pred >
bool ContainsIf (const Container &container, Pred pred)
 returns true if there is an element in container which satisfies the predicate
 
template<typename ValueType >
ValueType * AnyCast (AnyMovable *operand) noexcept
 
template<typename ValueType >
const ValueType * AnyCast (const AnyMovable *operand) noexcept
 
template<typename ValueType >
ValueType AnyCast (AnyMovable &operand)
 
template<typename ValueType >
ValueType AnyCast (const AnyMovable &operand)
 
template<typename ValueType >
ValueType AnyCast (AnyMovable &&operand)
 
template<typename T , typename Func >
AtomicUpdate (std::atomic< T > &atomic, Func updater)
 Atomically performs the operation of updater on atomic
 
template<typename T >
AtomicMin (std::atomic< T > &atomic, T value)
 Concurrently safe sets atomic to a value if value is less.
 
template<typename T >
AtomicMax (std::atomic< T > &atomic, T value)
 Concurrently safe sets atomic to a value if value is greater.
 
boost::uuids::uuid BoostUuidFromString (std::string_view str)
 Parse string into boost::uuids::uuid.
 
std::string ToString (const boost::uuids::uuid &)
 Serialize boost::uuids::uuid to string.
 
template<typename Value , typename T >
Box< T > Parse (const Value &value, formats::parse::To< Box< T > >)
 
template<typename Value , typename T >
Value Serialize (const Box< T > &value, formats::serialize::To< Value >)
 
template<typename StringBuilder , typename T >
void WriteToStream (const Box< T > &value, StringBuilder &sw)
 
template<typename T >
logging::LogHelperoperator<< (logging::LogHelper &lh, const Box< T > &box)
 
constexpr long long ToLongLong (BytesPerSecond x)
 
constexpr bool operator== (BytesPerSecond lhs, BytesPerSecond rhs)
 
constexpr bool operator!= (BytesPerSecond lhs, BytesPerSecond rhs)
 
BytesPerSecond StringToBytesPerSecond (const std::string &data)
 
template<class Value >
BytesPerSecond Parse (const Value &v, formats::parse::To< BytesPerSecond >)
 
template<class T >
constexpr bool operator== (const CachedHash< T > &x, const CachedHash< T > &y)
 Compares utils::CachedHash by hash first and then by keys.
 
template<class T >
constexpr bool operator!= (const CachedHash< T > &x, const CachedHash< T > &y)
 Compares utils::CachedHash by hash first and then by keys.
 
template<typename T >
constexpr CheckedPtr< T > MakeCheckedPtr (T *ptr) noexcept
 
template<std::size_t Count, typename Func >
void ForEachIndex (Func func)
 
template<std::size_t Count, typename Func >
void WithConstexprIndex (std::size_t runtime_index, Func func)
 Calls func with runtime_index wrapped in std::integral_constant.
 
template<typename Value , typename T >
std::enable_if_t< formats::common::kIsFormatValue< Value >, DefaultDict< T > > Parse (const Value &value, formats::parse::To< DefaultDict< T > >)
 
template<typename Container >
constexpr auto enumerate (Container &&iterable)
 Implementation of python-style enumerate function for range-for loops.
 
template<typename T = std::runtime_error>
void LogErrorAndThrow (const std::string &error_message)
 Logs error_message and throws an exception ith that message.
 
template<class E >
 unexpected (E) -> unexpected< E >
 
template<class GeneratorFunc >
auto GenerateFixedArray (std::size_t size, GeneratorFunc &&generator)
 Applies generator to indices in the range [0, size), storing the results in a new utils::FixedArray. The generator is guaranteed to be invoked in the first-to-last order.
 
template<typename Enum >
constexpr Flags< Enum > operator| (Enum, Flags< Enum >)
 
template<typename Enum >
constexpr Flags< Enum > operator& (Enum, Flags< Enum >)
 
template<typename Enum >
constexpr bool operator== (Enum, Flags< Enum >)
 
template<typename Enum >
constexpr bool operator!= (Enum, Flags< Enum >)
 
template<typename Enum >
Flags< Enum > operator| (Enum, const AtomicFlags< Enum > &)
 
template<typename Enum >
Flags< Enum > operator& (Enum, const AtomicFlags< Enum > &)
 
template<typename Enum >
bool operator== (Enum, const AtomicFlags< Enum > &)
 
template<typename Enum >
bool operator!= (Enum, const AtomicFlags< Enum > &)
 
template<typename T , typename StringType , typename = std::enable_if_t< std::is_convertible_v<StringType, std::string_view>>>
FromString (const StringType &str)
 Extract the number contained in the string. No space characters or other extra characters allowed. Supported types:
 
std::int64_t FromHexString (const std::string &str)
 
template<typename Leaf >
constexpr autoGetIf (Leaf &&leaf)
 
template<typename Root , typename Head , typename... Tail>
constexpr autoGetIf (Root &&root, Head &&head, Tail &&... tail)
 Dereferences a chain of indirections and compositions, returns nullptr if one of the chain elements is not set.
 
std::string MacaddrToString (Macaddr macaddr)
 Get 48-bit MAC address as a string in "xx:xx:.." format.
 
std::string Macaddr8ToString (Macaddr8 macaddr)
 Get 64-bit MAC address as a string in "xx:xx:.." format.
 
Macaddr MacaddrFromString (const std::string &str)
 Get 48-bit MAC address from std::string.
 
Macaddr8 Macaddr8FromString (const std::string &str)
 Get 64-bit MAC address from std::string.
 
template<class Target , class... Args>
boost::intrusive_ptr< Targetmake_intrusive_ptr (Args &&... args)
 Factory function for boost::intrusive_ptr, like std::make_unique.
 
template<typename U , typename... Args>
SharedRef< UMakeSharedRef (Args &&... args)
 An equivalent of std::make_shared for SharedRef.
 
template<typename U , typename... Args>
UniqueRef< UMakeUniqueRef (Args &&... args)
 An equivalent of std::make_unique for UniqueRef.
 
template<typename U , typename T >
constexpr U numeric_cast (T input)
 
template<class T , class U >
constexpr bool operator== (OptionalRef< T > lhs, OptionalRef< U > rhs) noexcept
 
template<class T , class U >
constexpr bool operator!= (OptionalRef< T > lhs, OptionalRef< U > rhs) noexcept
 
template<class T >
std::string ToString (const std::optional< T > &from)
 Converts std::optional to a string, empty value represented as "--".
 
template<typename T , typename Func >
auto OptionalTransform (T &&opt, Func func) -> std::optional< decltype(std::move(func)(*std::forward< T >(opt)))>
 A polyfill for C++23 monadic operations for std::optional.
 
template<class... Ts>
 Overloaded (Ts...) -> Overloaded< Ts... >
 
template<class... Args, class... Ts>
constexpr decltype(autoVisit (const std::variant< Args... > &var, Ts &&... ts)
 
template<class... Args, class... Ts>
constexpr decltype(autoVisit (std::variant< Args... > &var, Ts &&... ts)
 
template<class... Args, class... Ts>
constexpr decltype(autoVisit (std::variant< Args... > &&var, Ts &&... ts)
 
template<typename Container , typename Value >
void ProjectedInsertOrAssign (Container &set, Value &&value)
 An equivalent of std::unordered_map::insert_or_assign for utils::ProjectedUnorderedSet and utils::ProjectedSet.
 
template<typename Func >
decltype(autoWithDefaultRandom (Func &&func)
 Calls func with a thread-local UniformRandomBitGenerator (specifically of type utils::RandomBase).
 
template<typename T >
RandRange (T from_inclusive, T to_exclusive)
 Generates a random number in range [from, to)
 
template<typename T >
RandRange (T to_exclusive)
 Generates a random number in range [0, to)
 
template<typename Container >
void Shuffle (Container &container)
 Shuffles the elements within the container.
 
std::uint32_t Rand ()
 Generate a random number in the whole uint32_t range.
 
bool regex_match (std::string_view str, const regex &pattern)
 Determines whether the regular expression matches the entire target character sequence.
 
bool regex_search (std::string_view str, const regex &pattern)
 Determines whether the regular expression matches anywhere in the target character sequence.
 
std::string regex_replace (std::string_view str, const regex &pattern, std::string_view repl)
 Create a new string where all regular expression matches replaced with repl.
 
template<typename T >
bool operator== (const SharedReadablePtr< T > &ptr, std::nullptr_t)
 
template<typename T >
bool operator== (std::nullptr_t, const SharedReadablePtr< T > &ptr)
 
template<typename T >
bool operator!= (const SharedReadablePtr< T > &ptr, std::nullptr_t)
 
template<typename T >
bool operator!= (std::nullptr_t, const SharedReadablePtr< T > &ptr)
 
template<typename T , typename... Args>
SharedReadablePtr< T > MakeSharedReadable (Args &&... args)
 
template<std::size_t N>
bool operator== (const SmallString< N > &str, std::string_view sv)
 
template<std::size_t N>
bool operator== (std::string_view sv, const SmallString< N > &str)
 
template<std::size_t N>
bool operator== (const SmallString< N > &str1, const SmallString< N > &str2)
 
template<std::size_t N>
bool operator!= (const SmallString< N > &str1, const SmallString< N > &str2)
 
template<typename Value , std::size_t N>
Value Serialize (const SmallString< N > &value, formats::serialize::To< Value >)
 
template<typename Value , std::size_t N>
SmallString< NParse (const Value &value, formats::parse::To< SmallString< N > >)
 
template<typename Key , typename Value >
auto WithSafeHash (const std::unordered_map< Key, Value > &map)
 Converts an unordered [multi-]map or set with the default hash to a map with utils::StrCaseHash. This might be useful when converting guaranteed-to-be-safe data to a common operating format.
 
template<typename Key , typename Value >
auto WithSafeHash (std::unordered_map< Key, Value > &&map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Key , typename Value >
auto WithSafeHash (const std::unordered_multimap< Key, Value > &map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Key , typename Value >
auto WithSafeHash (std::unordered_multimap< Key, Value > &&map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Key >
auto WithSafeHash (const std::unordered_set< Key > &map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Key >
auto WithSafeHash (std::unordered_set< Key > &&map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Key >
auto WithSafeHash (const std::unordered_multiset< Key > &map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Key >
auto WithSafeHash (std::unordered_multiset< Key > &&map)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
std::chrono::milliseconds StringToDuration (const std::string &data)
 Converts strings like "10s", "5d", "1h" to durations.
 
constexpr bool operator& (StrongTypedefOps op, StrongTypedefOps mask) noexcept
 
constexpr auto operator| (StrongTypedefOps op1, StrongTypedefOps op2) noexcept
 
template<class Tag , class T , StrongTypedefOps Ops>
std::ostream & operator<< (std::ostream &os, const StrongTypedef< Tag, T, Ops > &v)
 Ostreams and Logging.
 
template<class Tag , class T , StrongTypedefOps Ops>
logging::LogHelperoperator<< (logging::LogHelper &os, const StrongTypedef< Tag, T, Ops > &v)
 
template<class Tag , class T , StrongTypedefOps Ops>
constexpr decltype(autoUnderlyingValue (const StrongTypedef< Tag, T, Ops > &v) noexcept
 
template<class Tag , class T , StrongTypedefOps Ops>
constexprUnderlyingValue (StrongTypedef< Tag, T, Ops > &&v) noexcept
 
constexpr bool IsStrongTypedefLoggable (StrongTypedefOps Ops)
 
template<typename T , typename Value >
std::enable_if_t< formats::common::kIsFormatValue< Value > &&IsStrongTypedef< T >{}, T > Parse (const Value &source, formats::parse::To< T >)
 
template<typename T , typename Value >
std::enable_if_t< IsStrongTypedef< T >{}, Value > Serialize (const T &object, formats::serialize::To< Value >)
 
template<typename T , typename StringBuilder >
std::enable_if_t< IsStrongTypedef< T >{}> WriteToStream (const T &object, StringBuilder &sw)
 
template<typename Tag , StrongTypedefOps Ops>
std::string ToString (const StrongTypedef< Tag, std::string, Ops > &object)
 
template<typename Tag , typename T , StrongTypedefOps Ops, std::enable_if_t< meta::kIsInteger< T >, bool > = true>
std::string ToString (const StrongTypedef< Tag, T, Ops > &object)
 
template<typename Target , typename Tag , typename T , StrongTypedefOps Ops, typename Enable >
constexpr Target StrongCast (const StrongTypedef< Tag, T, Ops, Enable > &src)
 
template<typename Target , typename Tag , typename T , StrongTypedefOps Ops, typename Enable >
constexpr Target StrongCast (StrongTypedef< Tag, T, Ops, Enable > &&src)
 
template<class Tag , class T , StrongTypedefOps Ops>
std::size_t hash_value (const StrongTypedef< Tag, T, Ops > &v)
 
std::string GetCurrentThreadName ()
 Get the name of the current thread.
 
void SetCurrentThreadName (std::string_view name)
 Set the name of the current thread.
 
bool IsMainThread () noexcept
 
void SetCurrentThreadIdleScheduling ()
 Set priority of the OS thread to IDLE (the lowest one)
 
void SetCurrentThreadLowPriorityScheduling ()
 Set priority of the OS thread to low (but not the lowest one)
 
template<typename BuilderFunc >
 TrivialBiMap (BuilderFunc) -> TrivialBiMap< BuilderFunc >
 
template<typename BuilderFunc >
 TrivialSet (BuilderFunc) -> TrivialSet< BuilderFunc >
 
template<typename ExceptionType = void, typename Value , typename BuilderFunc >
auto ParseFromValueString (const Value &value, TrivialBiMap< BuilderFunc > map)
 Parses and returns whatever is specified by map from a formats::*::Value.
 
template<const auto & Keys, const auto & Values>
constexpr auto MakeTrivialBiMap ()
 Zips two global constexpr arrays into an utils::TrivialBiMap.
 
template<const auto & Values>
constexpr auto MakeTrivialSet ()
 
template<class T >
constexpr auto UnderlyingValue (T v) noexcept
 Function that extracts integral value from enum or StrongTypedef.
 
template<typename Function , typename... Args>
auto Async (std::string name, Function &&f, Args &&... args)
 Starts an asynchronous task.
 
template<typename Function , typename... Args>
auto Async (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto CriticalAsync (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto SharedCriticalAsync (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto SharedAsync (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto Async (engine::TaskProcessor &task_processor, std::string name, engine::Deadline deadline, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto SharedAsync (engine::TaskProcessor &task_processor, std::string name, engine::Deadline deadline, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto CriticalAsync (std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto SharedCriticalAsync (std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto SharedAsync (std::string name, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto Async (std::string name, engine::Deadline deadline, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto SharedAsync (std::string name, engine::Deadline deadline, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto AsyncBackground (std::string name, engine::TaskProcessor &task_processor, Function &&f, Args &&... args)
 
template<typename Function , typename... Args>
auto CriticalAsyncBackground (std::string name, engine::TaskProcessor &task_processor, Function &&f, Args &&... args)
 
int DaemonMain (int argc, const char *const argv[], const components::ComponentList &components_list)
 
template<typename Cache >
LazySharedPtr< typename Cache::DataType > MakeLazyCachePtr (Cache &cache)
 Make a lazy pointer to the data of a cache.
 
RetryBudgetSettings Parse (const formats::json::Value &elem, formats::parse::To< RetryBudgetSettings >)
 
const charGetUserverVersion () noexcept
 
const charGetUserverVcsRevision () noexcept
 
const charGetUserverIdentifier () noexcept
 
template<class Tag , class T , StrongTypedefOps Ops>
void PrintTo (const StrongTypedef< Tag, T, Ops > &v, std::ostream *os)
 

Variables

constexpr std::string_view kDefaultDictDefaultName = "__default__"
 Name of the key with default value for utils::DefaultDict.
 
constexpr bool kStrictMatch = true
 Helper constant to use with FastPimpl.
 

Typedef Documentation

◆ NonLoggable

template<class Tag , class T >
using utils::NonLoggable
Initial value:
StrongTypedef<
Tag, T, StrongTypedefOps::kCompareStrong | StrongTypedefOps::kNonLoggable>

A StrongTypedef for data that MUST NOT be logged or outputted in some other way. Also prevents the data from appearing in backtrace prints of debugger.

#include <userver/storages/secdist/provider_component.hpp>
class UserPasswords {
public:
UserPasswords(const formats::json::Value& doc)
: user_passwords_(doc["user-passwords"].As<std::optional<Storage>>()) {}
bool IsMatching(const std::string& user, const Password& password) const {
if (!user_passwords_.has_value()) {
throw std::runtime_error(
"User passwords storage is missing. Field 'user-passwords' was "
"missing in json.");
}
const auto* ptr = utils::FindOrNullptr(user_passwords_.value(), user);
ptr->GetUnderlying(), password.GetUnderlying());
}
private:
using Storage = std::unordered_map<std::string, Password>;
std::optional<Storage> user_passwords_;
};

Definition at line 417 of file strong_typedef.hpp.

Enumeration Type Documentation

◆ StrongTypedefOps

Enumerator
kCompareStrong 

Forbid all comparisons for StrongTypedef.

kCompareTransparentOnly 

Allow comparing two StrongTypedef<Tag, T>

kCompareTransparent 

Allow comparing StrongTypedef<Tag, T> and T.

kNonLoggable 

Allow both of the above.

Definition at line 29 of file strong_typedef.hpp.

Function Documentation

◆ AnyCast() [1/5]

template<typename ValueType >
ValueType utils::AnyCast ( AnyMovable && operand)
Note
Cast to a reference type to avoid extra moves
Exceptions
BadAnyMovableCastif type of the data stored in operand does not match ValueType

Definition at line 222 of file any_movable.hpp.

◆ AnyCast() [2/5]

template<typename ValueType >
ValueType utils::AnyCast ( AnyMovable & operand)
Note
Cast to a reference type to avoid extra copies
Exceptions
BadAnyMovableCastif type of the data stored in operand does not match ValueType

Definition at line 204 of file any_movable.hpp.

◆ AnyCast() [3/5]

template<typename ValueType >
ValueType * utils::AnyCast ( AnyMovable * operand)
noexcept
Returns
nullptr if operand is nullptr or type of the data stored in operand does not match ValueType

Definition at line 192 of file any_movable.hpp.

◆ AnyCast() [4/5]

template<typename ValueType >
ValueType utils::AnyCast ( const AnyMovable & operand)
Note
Cast to a reference type to avoid extra copies
Exceptions
BadAnyMovableCastif type of the data stored in operand does not match ValueType

Definition at line 214 of file any_movable.hpp.

◆ AnyCast() [5/5]

template<typename ValueType >
const ValueType * utils::AnyCast ( const AnyMovable * operand)
noexcept
Returns
nullptr if operand is nullptr or type of the data stored in operand does not match ValueType

Definition at line 197 of file any_movable.hpp.

◆ AsContainer()

ToContainer utils::AsContainer ( FromContainer && container)

Converts one container type to another.

Definition at line 92 of file algo.hpp.

◆ CheckedFind()

template<typename Map , typename Key >
auto utils::CheckedFind ( Map & map,
const Key & key ) -> decltype(utils::MakeCheckedPtr(&map.find(key)->second))

Searches a map for an element and return a checked pointer to the found element.

Definition at line 82 of file algo.hpp.

◆ ContainsIf()

template<typename Container , typename Pred >
bool utils::ContainsIf ( const Container & container,
Pred pred )

returns true if there is an element in container which satisfies the predicate

Definition at line 152 of file algo.hpp.

◆ DaemonMain()

int utils::DaemonMain ( int argc,
const char *const argv[],
const components::ComponentList & components_list )

Parses command line arguments and calls components::Run with config file from –config parameter.

Other command line arguments:

  • –help - show all command line arguments
  • –config CONFIG - path to config.yaml
  • –config_vars CONFIG_VARS - path to config_vars.yaml
  • –config_vars_override CONFIG_VARS - path to config_vars.override.yaml
  • –print-config-schema - print config.yaml YAML Schema
  • –print-dynamic-config-defaults - print JSON with dynamic config defaults
Examples
postgresql/functional_tests/basic_chaos/postgres_service.cpp, samples/config_service/config_service.cpp, samples/flatbuf_service/flatbuf_service.cpp, samples/grpc_middleware_service/src/main.cpp, samples/grpc_service/grpc_service.cpp, samples/hello_service/hello_service.cpp, samples/http_caching/http_caching.cpp, samples/mongo_service/mongo_service.cpp, samples/multipart_service/service.cpp, samples/postgres_auth/postgres_service.cpp, samples/postgres_service/postgres_service.cpp, samples/production_service/production_service.cpp, samples/redis_service/redis_service.cpp, samples/tcp_full_duplex_service/tcp_full_duplex_service.cpp, samples/tcp_service/tcp_service.cpp, and samples/websocket_service/websocket_service.cpp.

◆ enumerate()

template<typename Container >
constexpr auto utils::enumerate ( Container && iterable)
constexpr

Implementation of python-style enumerate function for range-for loops.

Parameters
iterableContainer to iterate
Returns
ContainerWrapper, which iterator after dereference returns pair of index and (!!!)non-const reference to element(it seems impossible to make this reference const). It can be used in "range based for loop" with "structured binding" like this
for (auto [pos, elem] : enumerate(someContainer)) {...}

Definition at line 94 of file enumerate.hpp.

◆ Erase()

template<class Container , class T >
size_t utils::Erase ( Container & container,
const T & elem )

Erased elements and returns number of deleted elements.

Definition at line 137 of file algo.hpp.

◆ EraseIf()

template<class Container , class Pred >
auto utils::EraseIf ( Container & container,
Pred pred )

Erased elements and returns number of deleted elements.

Definition at line 115 of file algo.hpp.

◆ FindOptional()

template<class Map , class Key >
std::optional< typename Map::mapped_type > utils::FindOptional ( Map & map,
const Key & key )

Returns std::nullopt if no key in associative container, otherwise returns std::optional with a copy of value.

Definition at line 70 of file algo.hpp.

◆ FindOrDefault() [1/2]

template<class Map , class Key >
Map::mapped_type utils::FindOrDefault ( Map & map,
const Key & key )

Returns default value if no key in associative container, otherwise returns a copy of the stored value.

Definition at line 59 of file algo.hpp.

◆ FindOrDefault() [2/2]

template<class Map , class Key , class Default >
Map::mapped_type utils::FindOrDefault ( Map & map,
const Key & key,
Default && def )

Returns default value if no key in associative container, otherwise returns a copy of the stored value.

Definition at line 47 of file algo.hpp.

◆ FindOrNullptr()

template<class Map , class Key >
auto * utils::FindOrNullptr ( Map & map,
const Key & key )

Returns nullptr if no key in associative container, otherwise returns pointer to value.

Definition at line 39 of file algo.hpp.

◆ ForEachIndex()

template<std::size_t Count, typename Func >
void utils::ForEachIndex ( Func func)

Calls func with indices from range 0...<Count, wrapped in std::integral_constant.

Definition at line 36 of file constexpr_indices.hpp.

◆ FromString()

template<typename T , typename StringType , typename = std::enable_if_t< std::is_convertible_v<StringType, std::string_view>>>
T utils::FromString ( const StringType & str)

Extract the number contained in the string. No space characters or other extra characters allowed. Supported types:

  • Integer types. Leading plus or minus is allowed. The number is always base-10.
  • Floating-point types. The accepted number format is identical to std::strtod.
Template Parameters
TThe type of the number to be parsed
Parameters
strThe string that contains the number
Returns
The extracted number
Exceptions
std::runtime_errorif the string does not contain an integer or floating-point number in the specified format, or the string contains extra junk, or the number does not fit into the provided type
Examples
postgresql/functional_tests/basic_chaos/postgres_service.cpp.

Definition at line 174 of file from_string.hpp.

◆ GenerateFixedArray()

template<class GeneratorFunc >
auto utils::GenerateFixedArray ( std::size_t size,
GeneratorFunc && generator )

Applies generator to indices in the range [0, size), storing the results in a new utils::FixedArray. The generator is guaranteed to be invoked in the first-to-last order.

Parameters
sizeHow many objects to generate
generatorA functor that takes an index and returns an object for the FixedArray
Returns
FixedArray with the return objects of generator

Definition at line 175 of file fixed_array.hpp.

◆ GetCurrentThreadName()

std::string utils::GetCurrentThreadName ( )

Get the name of the current thread.

Thread names should only be used for debugging purposes. Thread names aren't required to be preserved exactly due to the system limit on thread name length.

Returns
the current thread name
Exceptions
std::system_erroron error

◆ GetIf() [1/2]

template<typename Leaf >
constexpr auto * utils::GetIf ( Leaf && leaf)
constexpr

Definition at line 30 of file get_if.hpp.

◆ GetIf() [2/2]

template<typename Root , typename Head , typename... Tail>
constexpr auto * utils::GetIf ( Root && root,
Head && head,
Tail &&... tail )
constexpr

Dereferences a chain of indirections and compositions, returns nullptr if one of the chain elements is not set.

struct C {};
struct B {
std::unique_ptr<C> c = std::make_unique<C>();
};
struct A {
std::shared_ptr<B> b = std::make_shared<B>();
};
auto a = std::make_optional<A>();
EXPECT_EQ(utils::GetIf(a, &A::b, &B::c), a->b->c.get());
EXPECT_EQ(utils::GetIf(a, &A::b), a->b.get());
EXPECT_EQ(utils::GetIf(a), &*a);
a->b->c.reset();
EXPECT_EQ(utils::GetIf(a, &A::b, &B::c), static_cast<C*>(nullptr));
EXPECT_EQ(utils::GetIf(a, &A::b), a->b.get());
EXPECT_EQ(utils::GetIf(a), &*a);
a->b.reset();
EXPECT_EQ(utils::GetIf(a, &A::b, &B::c), static_cast<C*>(nullptr));
EXPECT_EQ(utils::GetIf(a, &A::b), static_cast<B*>(nullptr));
EXPECT_EQ(utils::GetIf(a), &*a);
a.reset();
EXPECT_EQ(utils::GetIf(a, &A::b, &B::c), static_cast<C*>(nullptr));
EXPECT_EQ(utils::GetIf(a, &A::b), static_cast<B*>(nullptr));
EXPECT_EQ(utils::GetIf(a), static_cast<A*>(nullptr));

Definition at line 43 of file get_if.hpp.

◆ GetUserverIdentifier()

const char * utils::GetUserverIdentifier ( )
noexcept
Returns
zero-terminated string with description of the server as "userver/{GetUserverVersion()} ({__DATE__}; rv: {GetUserverHash()})"

◆ GetUserverVcsRevision()

const char * utils::GetUserverVcsRevision ( )
noexcept
Returns
zero-terminated string with GIT short hash of userver repo

◆ GetUserverVersion()

const char * utils::GetUserverVersion ( )
noexcept
Returns
zero-terminated string with version as "major.minor.patch"

◆ hash_value()

template<class Tag , class T , StrongTypedefOps Ops>
std::size_t utils::hash_value ( const StrongTypedef< Tag, T, Ops > & v)

Definition at line 408 of file strong_typedef.hpp.

◆ IsMainThread()

bool utils::IsMainThread ( )
noexcept
Returns
true if this is the thread in which main() was started

◆ IsStrongTypedefLoggable()

constexpr bool utils::IsStrongTypedefLoggable ( StrongTypedefOps Ops)
constexpr

Definition at line 330 of file strong_typedef.hpp.

◆ LogErrorAndThrow()

template<typename T = std::runtime_error>
void utils::LogErrorAndThrow ( const std::string & error_message)

Logs error_message and throws an exception ith that message.

Definition at line 17 of file exception.hpp.

◆ make_intrusive_ptr()

template<class Target , class... Args>
boost::intrusive_ptr< Target > utils::make_intrusive_ptr ( Args &&... args)

Factory function for boost::intrusive_ptr, like std::make_unique.

Definition at line 17 of file make_intrusive_ptr.hpp.

◆ MakeCheckedPtr()

template<typename T >
constexpr CheckedPtr< T > utils::MakeCheckedPtr ( T * ptr)
constexprnoexcept

Definition at line 73 of file checked_pointer.hpp.

◆ MakeLazyCachePtr()

template<typename Cache >
LazySharedPtr< typename Cache::DataType > utils::MakeLazyCachePtr ( Cache & cache)

Make a lazy pointer to the data of a cache.

The cache type must have:

For example, components::CachingComponentBase satisfies these requirements.

Definition at line 152 of file lazy_shared_ptr.hpp.

◆ MakeSharedReadable()

template<typename T , typename... Args>
SharedReadablePtr< T > utils::MakeSharedReadable ( Args &&... args)

Definition at line 137 of file shared_readable_ptr.hpp.

◆ MakeSharedRef()

template<typename U , typename... Args>
SharedRef< U > utils::MakeSharedRef ( Args &&... args)

An equivalent of std::make_shared for SharedRef.

Definition at line 119 of file not_null.hpp.

◆ MakeTrivialBiMap()

template<const auto & Keys, const auto & Values>
constexpr auto utils::MakeTrivialBiMap ( )
constexpr

Zips two global constexpr arrays into an utils::TrivialBiMap.

Definition at line 956 of file trivial_map.hpp.

◆ MakeTrivialSet()

template<const auto & Values>
constexpr auto utils::MakeTrivialSet ( )
constexpr

Definition at line 963 of file trivial_map.hpp.

◆ MakeUniqueRef()

template<typename U , typename... Args>
UniqueRef< U > utils::MakeUniqueRef ( Args &&... args)

An equivalent of std::make_unique for UniqueRef.

Definition at line 125 of file not_null.hpp.

◆ numeric_cast()

template<typename U , typename T >
constexpr U utils::numeric_cast ( T input)
constexpr

Detects loss of range when a numeric type is converted, and throws an exception if the range cannot be preserved

Example usage:

EXPECT_EQ(utils::numeric_cast<std::uint16_t>(0xffff), 0xffffu);
EXPECT_THROW(utils::numeric_cast<std::uint16_t>(0x10000), std::runtime_error);
EXPECT_THROW(utils::numeric_cast<std::uint16_t>(-1), std::runtime_error);

Definition at line 30 of file numeric_cast.hpp.

◆ operator!=() [1/8]

constexpr bool utils::operator!= ( BytesPerSecond lhs,
BytesPerSecond rhs )
constexpr

Definition at line 28 of file bytes_per_second.hpp.

◆ operator!=() [2/8]

template<class T >
constexpr bool utils::operator!= ( const CachedHash< T > & x,
const CachedHash< T > & y )
constexpr

Compares utils::CachedHash by hash first and then by keys.

Definition at line 30 of file cached_hash.hpp.

◆ operator!=() [3/8]

template<typename T >
bool utils::operator!= ( const SharedReadablePtr< T > & ptr,
std::nullptr_t  )

Definition at line 127 of file shared_readable_ptr.hpp.

◆ operator!=() [4/8]

template<std::size_t N>
bool utils::operator!= ( const SmallString< N > & str1,
const SmallString< N > & str2 )

Definition at line 167 of file small_string.hpp.

◆ operator!=() [5/8]

template<typename Enum >
bool utils::operator!= ( Enum lhs,
const AtomicFlags< Enum > & rhs )

Definition at line 377 of file flags.hpp.

◆ operator!=() [6/8]

template<typename Enum >
constexpr bool utils::operator!= ( Enum lhs,
Flags< Enum > rhs )
constexpr

Definition at line 209 of file flags.hpp.

◆ operator!=() [7/8]

template<class T , class U >
constexpr bool utils::operator!= ( OptionalRef< T > lhs,
OptionalRef< U > rhs )
constexprnoexcept

Definition at line 114 of file optional_ref.hpp.

◆ operator!=() [8/8]

template<typename T >
bool utils::operator!= ( std::nullptr_t ,
const SharedReadablePtr< T > & ptr )

Definition at line 132 of file shared_readable_ptr.hpp.

◆ operator&() [1/3]

template<typename Enum >
Flags< Enum > utils::operator& ( Enum lhs,
const AtomicFlags< Enum > & rhs )

Definition at line 367 of file flags.hpp.

◆ operator&() [2/3]

template<typename Enum >
constexpr Flags< Enum > utils::operator& ( Enum lhs,
Flags< Enum > rhs )
constexpr

Definition at line 199 of file flags.hpp.

◆ operator&() [3/3]

Definition at line 39 of file strong_typedef.hpp.

◆ operator<<() [1/3]

template<typename T >
logging::LogHelper & utils::operator<< ( logging::LogHelper & lh,
const Box< T > & box )

Definition at line 183 of file box.hpp.

◆ operator<<() [2/3]

Definition at line 312 of file strong_typedef.hpp.

◆ operator<<() [3/3]

template<class Tag , class T , StrongTypedefOps Ops>
std::ostream & utils::operator<< ( std::ostream & os,
const StrongTypedef< Tag, T, Ops > & v )

Ostreams and Logging.

Definition at line 305 of file strong_typedef.hpp.

◆ operator==() [1/10]

Definition at line 24 of file bytes_per_second.hpp.

◆ operator==() [2/10]

template<class T >
constexpr bool utils::operator== ( const CachedHash< T > & x,
const CachedHash< T > & y )
constexpr

Compares utils::CachedHash by hash first and then by keys.

Definition at line 24 of file cached_hash.hpp.

◆ operator==() [3/10]

template<typename T >
bool utils::operator== ( const SharedReadablePtr< T > & ptr,
std::nullptr_t  )

Definition at line 117 of file shared_readable_ptr.hpp.

◆ operator==() [4/10]

template<std::size_t N>
bool utils::operator== ( const SmallString< N > & str,
std::string_view sv )

Definition at line 152 of file small_string.hpp.

◆ operator==() [5/10]

template<std::size_t N>
bool utils::operator== ( const SmallString< N > & str1,
const SmallString< N > & str2 )

Definition at line 162 of file small_string.hpp.

◆ operator==() [6/10]

template<typename Enum >
bool utils::operator== ( Enum lhs,
const AtomicFlags< Enum > & rhs )

Definition at line 372 of file flags.hpp.

◆ operator==() [7/10]

template<typename Enum >
constexpr bool utils::operator== ( Enum lhs,
Flags< Enum > rhs )
constexpr

Definition at line 204 of file flags.hpp.

◆ operator==() [8/10]

template<class T , class U >
constexpr bool utils::operator== ( OptionalRef< T > lhs,
OptionalRef< U > rhs )
constexprnoexcept

Definition at line 108 of file optional_ref.hpp.

◆ operator==() [9/10]

template<typename T >
bool utils::operator== ( std::nullptr_t ,
const SharedReadablePtr< T > & ptr )

Definition at line 122 of file shared_readable_ptr.hpp.

◆ operator==() [10/10]

template<std::size_t N>
bool utils::operator== ( std::string_view sv,
const SmallString< N > & str )

Definition at line 157 of file small_string.hpp.

◆ operator|() [1/3]

template<typename Enum >
Flags< Enum > utils::operator| ( Enum lhs,
const AtomicFlags< Enum > & rhs )

Definition at line 362 of file flags.hpp.

◆ operator|() [2/3]

template<typename Enum >
constexpr Flags< Enum > utils::operator| ( Enum lhs,
Flags< Enum > rhs )
constexpr

Definition at line 194 of file flags.hpp.

◆ operator|() [3/3]

Definition at line 43 of file strong_typedef.hpp.

◆ OptionalTransform()

template<typename T , typename Func >
auto utils::OptionalTransform ( T && opt,
Func func ) -> std::optional<decltype(std::move(func)(*std::forward<T>(opt)))>

A polyfill for C++23 monadic operations for std::optional.

Definition at line 26 of file optionals.hpp.

◆ Parse() [1/5]

template<typename T , typename Value >
std::enable_if_t< formats::common::kIsFormatValue< Value > &&IsStrongTypedef< T >{}, T > utils::Parse ( const Value & source,
formats::parse::To< T >  )

Definition at line 339 of file strong_typedef.hpp.

◆ Parse() [2/5]

template<class Value >
BytesPerSecond utils::Parse ( const Value & v,
formats::parse::To< BytesPerSecond >  )

Definition at line 37 of file bytes_per_second.hpp.

◆ Parse() [3/5]

template<typename Value , typename T >
Box< T > utils::Parse ( const Value & value,
formats::parse::To< Box< T > >  )

Definition at line 168 of file box.hpp.

◆ Parse() [4/5]

template<typename Value , typename T >
std::enable_if_t< formats::common::kIsFormatValue< Value >, DefaultDict< T > > utils::Parse ( const Value & value,
formats::parse::To< DefaultDict< T > >  )

Definition at line 166 of file default_dict.hpp.

◆ Parse() [5/5]

template<typename Value , std::size_t N>
SmallString< N > utils::Parse ( const Value & value,
formats::parse::To< SmallString< N > >  )

Definition at line 21 of file small_string_serialization.hpp.

◆ ParseFromValueString()

template<typename ExceptionType = void, typename Value , typename BuilderFunc >
auto utils::ParseFromValueString ( const Value & value,
TrivialBiMap< BuilderFunc > map )

Parses and returns whatever is specified by map from a formats::*::Value.

Exceptions
ExceptionTypeor Value::Exception by default, if value is not a string, or if value is not contained in map.
See also
Formats (JSON, YAML, BSON, ...)

Definition at line 874 of file trivial_map.hpp.

◆ PrintTo()

template<class Tag , class T , StrongTypedefOps Ops>
void utils::PrintTo ( const StrongTypedef< Tag, T, Ops > & v,
std::ostream * os )

Definition at line 50 of file utest.hpp.

◆ ProjectedInsertOrAssign()

template<typename Container , typename Value >
void utils::ProjectedInsertOrAssign ( Container & set,
Value && value )

An equivalent of std::unordered_map::insert_or_assign for utils::ProjectedUnorderedSet and utils::ProjectedSet.

Definition at line 104 of file projected_set.hpp.

◆ Rand()

std::uint32_t utils::Rand ( )

Generate a random number in the whole uint32_t range.

Note
The used random generator is not cryptographically secure
Warning
Don't use Rand() % N, use RandRange instead
Examples
core/src/engine/mutex_benchmark.cpp.

◆ RandRange() [1/2]

template<typename T >
T utils::RandRange ( T from_inclusive,
T to_exclusive )

Generates a random number in range [from, to)

Note
The used random generator is not cryptographically secure
from_inclusive must be less than to_exclusive

Definition at line 86 of file rand.hpp.

◆ RandRange() [2/2]

template<typename T >
T utils::RandRange ( T to_exclusive)

Generates a random number in range [0, to)

Note
The used random generator is not cryptographically secure

Definition at line 104 of file rand.hpp.

◆ Serialize() [1/3]

template<typename Value , typename T >
Value utils::Serialize ( const Box< T > & value,
formats::serialize::To< Value >  )

Definition at line 173 of file box.hpp.

◆ Serialize() [2/3]

template<typename Value , std::size_t N>
Value utils::Serialize ( const SmallString< N > & value,
formats::serialize::To< Value >  )

Definition at line 16 of file small_string_serialization.hpp.

◆ Serialize() [3/3]

template<typename T , typename Value >
std::enable_if_t< IsStrongTypedef< T >{}, Value > utils::Serialize ( const T & object,
formats::serialize::To< Value >  )

Definition at line 344 of file strong_typedef.hpp.

◆ SetCurrentThreadIdleScheduling()

void utils::SetCurrentThreadIdleScheduling ( )

Set priority of the OS thread to IDLE (the lowest one)

Exceptions
std::system_error

◆ SetCurrentThreadLowPriorityScheduling()

void utils::SetCurrentThreadLowPriorityScheduling ( )

Set priority of the OS thread to low (but not the lowest one)

Exceptions
std::system_error

◆ SetCurrentThreadName()

void utils::SetCurrentThreadName ( std::string_view name)

Set the name of the current thread.

This function should only be used from drivers that create their own threads! Users should normally rely on the coroutine engine instead of creating additional threads.

There is a system limit on thread name length, e.g. 15 chars on Linux. The name is automatically cut to fit the limit.

Parameters
namethe new thread name
Exceptions
std::system_erroron error

◆ Shuffle()

template<typename Container >
void utils::Shuffle ( Container & container)

Shuffles the elements within the container.

Note
The method used for determining a random permutation is not cryptographically secure

Definition at line 112 of file rand.hpp.

◆ StrCat()

template<typename ResultString = std::string, typename... Strings>
ResultString utils::StrCat ( const Strings &... strings)

Concatenates multiple std::string_view-convertible items.

Definition at line 24 of file algo.hpp.

◆ StringToBytesPerSecond()

BytesPerSecond utils::StringToBytesPerSecond ( const std::string & data)

Understands all the date-rate unit suffixes from https://en.wikipedia.org/wiki/Data-rate_units#Conversion_table

◆ StringToDuration()

std::chrono::milliseconds utils::StringToDuration ( const std::string & data)

Converts strings like "10s", "5d", "1h" to durations.

Understands the following suffixes: s - seconds ms - milliseconds m - minutes h - hours d - days

◆ StrongCast() [1/2]

constexpr Target utils::StrongCast ( const StrongTypedef< Tag, T, Ops, Enable > & src)
constexpr

Explicitly cast from one strong typedef to another, to replace constructions SomeStrongTydef{utils::UnderlyingValue(another_strong_val)} with utils::StrongCast<SomeStrongTydef>(another_strong_val)

Definition at line 387 of file strong_typedef.hpp.

◆ StrongCast() [2/2]

constexpr Target utils::StrongCast ( StrongTypedef< Tag, T, Ops, Enable > && src)
constexpr

Definition at line 398 of file strong_typedef.hpp.

◆ ToLongLong()

constexpr long long utils::ToLongLong ( BytesPerSecond x)
constexpr

Definition at line 20 of file bytes_per_second.hpp.

◆ ToString() [1/3]

template<class T >
std::string utils::ToString ( const std::optional< T > & from)

Converts std::optional to a string, empty value represented as "--".

Definition at line 20 of file optionals.hpp.

◆ ToString() [2/3]

template<typename Tag , StrongTypedefOps Ops>
std::string utils::ToString ( const StrongTypedef< Tag, std::string, Ops > & object)

Definition at line 358 of file strong_typedef.hpp.

◆ ToString() [3/3]

template<typename Tag , typename T , StrongTypedefOps Ops, std::enable_if_t< meta::kIsInteger< T >, bool > = true>
std::string utils::ToString ( const StrongTypedef< Tag, T, Ops > & object)

Definition at line 366 of file strong_typedef.hpp.

◆ UnderlyingValue() [1/3]

template<class Tag , class T , StrongTypedefOps Ops>
constexpr decltype(auto) utils::UnderlyingValue ( const StrongTypedef< Tag, T, Ops > & v)
constexprnoexcept

Definition at line 320 of file strong_typedef.hpp.

◆ UnderlyingValue() [2/3]

template<class Tag , class T , StrongTypedefOps Ops>
constexpr T utils::UnderlyingValue ( StrongTypedef< Tag, T, Ops > && v)
constexprnoexcept

Definition at line 326 of file strong_typedef.hpp.

◆ UnderlyingValue() [3/3]

template<class T >
constexpr auto utils::UnderlyingValue ( T v)
constexprnoexcept

Function that extracts integral value from enum or StrongTypedef.

Definition at line 15 of file underlying_value.hpp.

◆ Visit() [1/3]

template<class... Args, class... Ts>
constexpr decltype(auto) utils::Visit ( const std::variant< Args... > & var,
Ts &&... ts )
constexpr

Definition at line 24 of file overloaded.hpp.

◆ Visit() [2/3]

template<class... Args, class... Ts>
constexpr decltype(auto) utils::Visit ( std::variant< Args... > && var,
Ts &&... ts )
constexpr

Definition at line 34 of file overloaded.hpp.

◆ Visit() [3/3]

template<class... Args, class... Ts>
constexpr decltype(auto) utils::Visit ( std::variant< Args... > & var,
Ts &&... ts )
constexpr

Definition at line 29 of file overloaded.hpp.

◆ WithConstexprIndex()

template<std::size_t Count, typename Func >
void utils::WithConstexprIndex ( std::size_t runtime_index,
Func func )

Calls func with runtime_index wrapped in std::integral_constant.

Definition at line 42 of file constexpr_indices.hpp.

◆ WithDefaultRandom()

template<typename Func >
decltype(auto) utils::WithDefaultRandom ( Func && func)

Calls func with a thread-local UniformRandomBitGenerator (specifically of type utils::RandomBase).

Note
The provided RandomBase instance is not cryptographically secure.

func should not contain any task context switches. That is, it should not use any userver synchronization primitives and should not access userver-based web or database clients.

func should not store the reference to the provided thread-local variable for use outside of the WithThreadLocal scope.

Prefer utils::RandRange if possible.

Usage example

Standard distributions can be passed to WithDefaultRandom directly:

std::uniform_int_distribution<std::uint64_t> distribution{1, 6};
const auto x = utils::WithDefaultRandom(distribution);

A lambda can be passed to perform a series of operations more efficiently:

std::vector<std::uint64_t> random_numbers;
random_numbers.reserve(kIterations);
// utils::WithDefaultRandom induces some overhead to ensure coroutine-safety.
// In a performance-critical code section, a single WithDefaultRandom call is
// more efficient than multiple `WithDefaultRandom(distribution)`.
std::uniform_int_distribution<std::uint64_t> distribution{1, 6};
for (int iter = 0; iter < kIterations; ++iter) {
random_numbers.push_back(distribution(rng));
}
});
Parameters
funcfunctor that will be invoked with the RNG
Returns
The invocation result of func

Definition at line 77 of file rand.hpp.

◆ WithSafeHash() [1/8]

template<typename Key , typename Value >
auto utils::WithSafeHash ( const std::unordered_map< Key, Value > & map)

Converts an unordered [multi-]map or set with the default hash to a map with utils::StrCaseHash. This might be useful when converting guaranteed-to-be-safe data to a common operating format.

Definition at line 22 of file str_icase_containers.hpp.

◆ WithSafeHash() [2/8]

template<typename Key , typename Value >
auto utils::WithSafeHash ( const std::unordered_multimap< Key, Value > & map)

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

Definition at line 36 of file str_icase_containers.hpp.

◆ WithSafeHash() [3/8]

template<typename Key >
auto utils::WithSafeHash ( const std::unordered_multiset< Key > & map)

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

Definition at line 63 of file str_icase_containers.hpp.

◆ WithSafeHash() [4/8]

template<typename Key >
auto utils::WithSafeHash ( const std::unordered_set< Key > & map)

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

Definition at line 50 of file str_icase_containers.hpp.

◆ WithSafeHash() [5/8]

template<typename Key , typename Value >
auto utils::WithSafeHash ( std::unordered_map< Key, Value > && map)

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

Definition at line 29 of file str_icase_containers.hpp.

◆ WithSafeHash() [6/8]

template<typename Key , typename Value >
auto utils::WithSafeHash ( std::unordered_multimap< Key, Value > && map)

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

Definition at line 43 of file str_icase_containers.hpp.

◆ WithSafeHash() [7/8]

template<typename Key >
auto utils::WithSafeHash ( std::unordered_multiset< Key > && map)

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

Definition at line 70 of file str_icase_containers.hpp.

◆ WithSafeHash() [8/8]

template<typename Key >
auto utils::WithSafeHash ( std::unordered_set< Key > && map)

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

Definition at line 56 of file str_icase_containers.hpp.

◆ WriteToStream() [1/2]

template<typename StringBuilder , typename T >
void utils::WriteToStream ( const Box< T > & value,
StringBuilder & sw )

Definition at line 178 of file box.hpp.

◆ WriteToStream() [2/2]

template<typename T , typename StringBuilder >
std::enable_if_t< IsStrongTypedef< T >{}> utils::WriteToStream ( const T & object,
StringBuilder & sw )

Definition at line 351 of file strong_typedef.hpp.

Variable Documentation

◆ kDefaultDictDefaultName

constexpr std::string_view utils::kDefaultDictDefaultName = "__default__"
inlineconstexpr

Name of the key with default value for utils::DefaultDict.

Definition at line 19 of file default_dict.hpp.

◆ kStrictMatch

constexpr bool utils::kStrictMatch = true
inlineconstexpr

Helper constant to use with FastPimpl.

Definition at line 16 of file fast_pimpl.hpp.