userver: userver/utils/strong_typedef.hpp Source File
Loading...
Searching...
No Matches
strong_typedef.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/strong_typedef.hpp
4/// @brief @copybrief utils::StrongTypedef
5
6#include <compare>
7#include <functional>
8#include <iosfwd>
9#include <string>
10#include <type_traits>
11#include <utility>
12
13#include <userver/compiler/impl/lifetime.hpp>
14#include <userver/formats/common/meta.hpp>
15#include <userver/utils/fmt_compat.hpp>
16#include <userver/utils/meta.hpp>
17#include <userver/utils/strong_typedef_fwd.hpp>
18#include <userver/utils/underlying_value.hpp>
19
20// clang-format off
21#include <fmt/format.h>
22#include <boost/functional/hash_fwd.hpp>
23// clang-format on
24
25namespace boost::uuids {
26struct uuid;
27}
28
29/// @brief GoogleTest-related helpers used from headers in test-only paths.
30namespace testing {
31
32template <typename T>
33std::string PrintToString(const T& value);
34
35} // namespace testing
36
37USERVER_NAMESPACE_BEGIN
38
39namespace logging {
40class LogHelper; // Forward declaration
41}
42
43namespace utils {
44
45constexpr bool operator&(StrongTypedefOps op, StrongTypedefOps mask) noexcept {
47}
48
49constexpr auto operator|(StrongTypedefOps op1, StrongTypedefOps op2) noexcept {
50 return StrongTypedefOps{utils::UnderlyingValue(op1) | utils::UnderlyingValue(op2)};
51}
52
53// Helpers
54namespace impl::strong_typedef {
55
56template <class T>
57struct InitializerListImpl {
58 struct DoNotMatch;
59 using type = DoNotMatch;
60};
61
62template <class T>
63requires requires { typename T::value_type; }
64struct InitializerListImpl<T> {
65 using type = std::initializer_list<typename T::value_type>;
66};
67
68// We have to invent this alias to avoid hard error in StrongTypedef<Tag, T> for
69// types T that does not have T::value_type.
70template <class T>
71using InitializerList = typename InitializerListImpl<T>::type;
72
73template <class T, class U>
74constexpr void CheckStrongCompare() {
75 static_assert(
76 std::is_same_v<typename T::UnderlyingType, typename U::UnderlyingType> &&
77 std::is_same_v<typename T::TagType, typename U::TagType> && T::kOps == U::kOps &&
78 (T::kOps & StrongTypedefOps::kCompareStrong),
79 "Comparing those StrongTypedefs is forbidden"
80 );
81}
82
83template <class Typedef>
84constexpr void CheckTransparentCompare() {
85 static_assert(
86 Typedef::kOps & StrongTypedefOps::kCompareTransparentOnly,
87 "Comparing this StrongTypedef to a raw value is forbidden"
88 );
89}
90
91template <class T>
92const auto& UnwrapIfStrongTypedef(const T& value) {
93 if constexpr (IsStrongTypedef<T>) {
94 return value.GetUnderlying();
95 } else {
96 return value;
97 }
98}
99
100// For 'std::string', begin-end methods are not forwarded, because otherwise
101// it might get serialized as an array.
102template <typename T>
103concept Range =
104 meta::IsRange<T> && !meta::IsInstantiationOf<std::remove_const_t<T>, std::basic_string> &&
105 !meta::IsRecursiveRange<T> && !std::is_same_v<boost::uuids::uuid, std::remove_const_t<T>>;
106
107template <typename T>
108constexpr void CheckIfAllowsLogging() {
109 static_assert(IsStrongTypedef<T>);
110
111 if constexpr (T::kOps & StrongTypedefOps::kNonLoggable) {
112 static_assert(!sizeof(T), "Trying to print a non-loggable StrongTypedef");
113 }
114}
115
116template <class To, class... Args>
117constexpr bool IsStrongToStrongConversion() noexcept {
118 static_assert(IsStrongTypedef<To>);
119
120 if constexpr (sizeof...(Args) == 1) {
121 using FromDecayed = std::decay_t<decltype((std::declval<Args>(), ...))>;
122 if constexpr (IsStrongTypedef<FromDecayed>) {
123 // Required to make `MyVariant v{MySpecialInt{10}};` compile.
124 return !std::is_same_v<FromDecayed, To> &&
125 (std::is_same_v<typename FromDecayed::UnderlyingType, typename To::UnderlyingType> ||
126 std::is_arithmetic_v<typename To::UnderlyingType>);
127 }
128 }
129
130 return false;
131}
132
133} // namespace impl::strong_typedef
134
135/// @ingroup userver_universal userver_containers
136///
137/// @brief Strong typedef for a type T.
138///
139/// Typical usage:
140/// @snippet universal/src/utils/strong_typedef_test.cpp StrongTypedef typical usage
141///
142/// Has all the:
143/// * comparison (see "Operators" below)
144/// * hashing
145/// * streaming operators
146/// * optimized logging for LOG_XXX()
147///
148/// If used with container-like type also has common STL functions:
149/// * begin()
150/// * end()
151/// * cbegin()
152/// * cend()
153/// * size()
154/// * empty()
155/// * clear()
156/// * operator[]
157///
158/// Operators:
159/// You can customize the operators that are available by passing the third
160/// argument of type StrongTypedefOps. See its docs for more info.
161template <class Tag, class T, StrongTypedefOps Ops>
162class StrongTypedef : public impl::strong_typedef::StrongTypedefTag {
163 static_assert(!std::is_reference_v<T>);
164 static_assert(!std::is_pointer_v<T>);
165
166 static_assert(!std::is_reference_v<Tag>);
167 static_assert(!std::is_pointer_v<Tag>);
168
169public:
170 using UnderlyingType = T;
171 using TagType = Tag;
172 static constexpr StrongTypedefOps kOps = Ops;
173
174 StrongTypedef() = default;
175 StrongTypedef(const StrongTypedef&) = default;
176 StrongTypedef(StrongTypedef&&) noexcept = default;
177 StrongTypedef& operator=(const StrongTypedef&) = default;
178 StrongTypedef& operator=(StrongTypedef&&) noexcept = default;
179
180 constexpr StrongTypedef(impl::strong_typedef::InitializerList<T> lst)
181 : data_(lst)
182 {}
183
184 template <typename... Args>
185 requires std::is_constructible_v<T, Args...>
186 constexpr explicit StrongTypedef(Args&&... args) noexcept(noexcept(T(std::forward<Args>(args)...)))
187 : data_(std::forward<Args>(args)...)
188 {
189 using impl::strong_typedef::IsStrongToStrongConversion;
190 static_assert(
191 !IsStrongToStrongConversion<StrongTypedef, Args...>(),
192 "Attempt to convert one StrongTypedef to another. Use "
193 "utils::StrongCast to do that"
194 );
195 }
196
197 constexpr explicit operator const T&() const& noexcept USERVER_IMPL_LIFETIME_BOUND { return data_; }
198 constexpr explicit operator T() && noexcept { return std::move(data_); }
199 constexpr explicit operator T&() & noexcept USERVER_IMPL_LIFETIME_BOUND { return data_; }
200
201 constexpr const T& GetUnderlying() const& noexcept USERVER_IMPL_LIFETIME_BOUND { return data_; }
202 constexpr T GetUnderlying() && noexcept { return std::move(data_); }
203 constexpr T& GetUnderlying() & noexcept USERVER_IMPL_LIFETIME_BOUND { return data_; }
204
205 auto begin()
206 requires impl::strong_typedef::Range<T>
207 {
208 return std::begin(data_);
209 }
210
211 auto end()
212 requires impl::strong_typedef::Range<T>
213 {
214 return std::end(data_);
215 }
216
217 auto begin() const
218 requires impl::strong_typedef::Range<T>
219 {
220 return std::begin(data_);
221 }
222
223 auto end() const
224 requires impl::strong_typedef::Range<T>
225 {
226 return std::end(data_);
227 }
228
229 auto cbegin() const
230 requires impl::strong_typedef::Range<T>
231 {
232 return std::cbegin(data_);
233 }
234
235 auto cend() const
236 requires impl::strong_typedef::Range<T>
237 {
238 return std::cend(data_);
239 }
240
241 auto size() const
242 requires meta::IsSizable<T>
243 {
244 return std::size(data_);
245 }
246
247 auto empty() const { return data_.empty(); }
248
249 auto clear() { return data_.clear(); }
250
251 template <class Arg>
252 decltype(auto) operator[](Arg&& i) {
253 return data_[std::forward<Arg>(i)];
254 }
255 template <class Arg>
256 decltype(auto) operator[](Arg&& i) const {
257 return data_[std::forward<Arg>(i)];
258 }
259
260private:
261 T data_{};
262};
263
264// Relational operators
265
266// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
267#define UTILS_STRONG_TYPEDEF_REL_OP(OPERATOR)
268 template <
269 class T,
270 class U,
271 std::enable_if_t<
272 impl::strong_typedef::IsStrongTypedef<T> || impl::strong_typedef::IsStrongTypedef<U>,
273 int> /*Enable*/
274 = 0>
275 constexpr auto operator OPERATOR(const T& lhs, const U& rhs)
276 ->decltype(impl::strong_typedef::UnwrapIfStrongTypedef(lhs
277 ) OPERATOR impl::strong_typedef::UnwrapIfStrongTypedef(rhs)) {
278 if constexpr (impl::strong_typedef::IsStrongTypedef<T>) {
279 if constexpr (impl::strong_typedef::IsStrongTypedef<U>) {
280 impl::strong_typedef::CheckStrongCompare<T, U>();
281 return lhs.GetUnderlying() OPERATOR rhs.GetUnderlying();
282 } else {
283 impl::strong_typedef::CheckTransparentCompare<T>();
284 return lhs.GetUnderlying() OPERATOR rhs;
285 }
286 } else {
287 impl::strong_typedef::CheckTransparentCompare<U>();
288 return lhs OPERATOR rhs.GetUnderlying();
289 }
290 }
291
292// Replacing std::enable_if_t with constraints leads to the return type always being computed,
293// which results in infinite recursion for non-StrongTypedef types.
294// NOLINTBEGIN(modernize-use-constraints)
302// NOLINTEND(modernize-use-constraints)
303
304#undef UTILS_STRONG_TYPEDEF_REL_OP
305
306/// Ostreams and Logging
307
308template <class Tag, class T, StrongTypedefOps Ops>
309std::ostream& operator<<(std::ostream& os, const StrongTypedef<Tag, T, Ops>& v) {
310 impl::strong_typedef::CheckIfAllowsLogging<StrongTypedef<Tag, T, Ops>>();
311 return os << v.GetUnderlying();
312}
313
314template <class Tag, class T, StrongTypedefOps Ops>
315logging::LogHelper& operator<<(logging::LogHelper& os, const StrongTypedef<Tag, T, Ops>& v) {
316 impl::strong_typedef::CheckIfAllowsLogging<StrongTypedef<Tag, T, Ops>>();
317 return os << v.GetUnderlying();
318}
319
320// UnderlyingValue
321template <class Tag, class T, StrongTypedefOps Ops>
322constexpr decltype(auto) UnderlyingValue(const StrongTypedef<Tag, T, Ops>& v) noexcept {
323 return v.GetUnderlying();
324}
325
326template <class Tag, class T, StrongTypedefOps Ops>
327constexpr T UnderlyingValue(StrongTypedef<Tag, T, Ops>&& v) noexcept {
328 return std::move(v).GetUnderlying();
329}
330
331constexpr bool IsStrongTypedefLoggable(StrongTypedefOps ops) { return !(ops & StrongTypedefOps::kNonLoggable); }
332
333// Serialization
334
335template <impl::strong_typedef::IsStrongTypedef T, formats::common::IsFormatValue Value>
336T Parse(const Value& source, formats::parse::To<T>) {
337 return T{source.template As<typename T::UnderlyingType>()};
338}
339
340template <impl::strong_typedef::IsStrongTypedef T, typename Value>
341Value Serialize(const T& object, formats::serialize::To<Value>) {
342 impl::strong_typedef::CheckIfAllowsLogging<T>();
343 return typename Value::Builder(object.GetUnderlying()).ExtractValue();
344}
345
346template <impl::strong_typedef::IsStrongTypedef T, typename StringBuilder>
347void WriteToStream(const T& object, StringBuilder& sw) {
348 impl::strong_typedef::CheckIfAllowsLogging<T>();
349 WriteToStream(object.GetUnderlying(), sw);
350}
351
352template <typename Tag, StrongTypedefOps Ops>
353std::string ToString(const StrongTypedef<Tag, std::string, Ops>& object) {
354 impl::strong_typedef::CheckIfAllowsLogging<StrongTypedef<Tag, std::string, Ops>>();
355 return object.GetUnderlying();
356}
357
358template <typename Tag, meta::IsInteger T, StrongTypedefOps Ops>
359std::string ToString(const StrongTypedef<Tag, T, Ops>& object) {
360 impl::strong_typedef::CheckIfAllowsLogging<StrongTypedef<Tag, std::string, Ops>>();
361 return std::to_string(object.GetUnderlying());
362}
363
364template <typename Tag, std::floating_point T, StrongTypedefOps Ops>
365std::string ToString(const StrongTypedef<Tag, T, Ops>& object) {
366 impl::strong_typedef::CheckIfAllowsLogging<StrongTypedef<Tag, std::string, Ops>>();
367 return fmt::to_string(object.GetUnderlying());
368}
369
370// Explicit casting
371
372/// Explicitly cast from one strong typedef to another, to replace constructions
373/// `SomeStrongTydef{utils::UnderlyingValue(another_strong_val)}` with
374/// `utils::StrongCast<SomeStrongTydef>(another_strong_val)`
375template <typename Target, typename Tag, typename T, StrongTypedefOps Ops>
376constexpr Target StrongCast(const StrongTypedef<Tag, T, Ops>& src) {
377 static_assert(impl::strong_typedef::IsStrongTypedef<Target>, "Expected strong typedef as target type");
378 static_assert(
379 std::is_convertible_v<T, typename Target::UnderlyingType>,
380 "Source strong typedef underlying type must be convertible to "
381 "target's underlying type"
382 );
383 return Target{src.GetUnderlying()};
384}
385
386template <typename Target, typename Tag, typename T, StrongTypedefOps Ops>
387constexpr Target StrongCast(StrongTypedef<Tag, T, Ops>&& src) {
388 static_assert(impl::strong_typedef::IsStrongTypedef<Target>, "Expected strong typedef as target type");
389 static_assert(
390 std::is_convertible_v<T, typename Target::UnderlyingType>,
391 "Source strong typedef underlying type must be convertible to "
392 "target's underlying type"
393 );
394 return Target{std::move(src).GetUnderlying()};
395}
396
397template <class Tag, class T, StrongTypedefOps Ops>
398std::size_t hash_value(const StrongTypedef<Tag, T, Ops>& v) { // NOLINT(readability-identifier-naming)
399 return boost::hash<T>{}(v.GetUnderlying());
400}
401
402/// gtest formatter for utils::StrongTypedef
403template <class Tag, class T, StrongTypedefOps Ops>
404void PrintTo(const StrongTypedef<Tag, T, Ops>& v, std::ostream* os) {
405 *os << testing::PrintToString(v.GetUnderlying());
406}
407
408/// A StrongTypedef for data that MUST NOT be logged or outputted in some other
409/// way. Also prevents the data from appearing in backtrace prints of debugger.
410///
411/// @snippet core/src/storages/secdist/secdist_test.cpp UserPasswords
412template <class Tag, class T>
413using NonLoggable = StrongTypedef<Tag, T, StrongTypedefOps::kCompareStrong | StrongTypedefOps::kNonLoggable>;
414
415} // namespace utils
416
417USERVER_NAMESPACE_END
418
419// std::hash support
420template <class Tag, class T, USERVER_NAMESPACE::utils::StrongTypedefOps Ops>
421struct std::hash<USERVER_NAMESPACE::utils::StrongTypedef<Tag, T, Ops>> : std::hash<T> {
422 std::size_t operator()(const USERVER_NAMESPACE::utils::StrongTypedef<Tag, T, Ops>& v
423 ) const noexcept(noexcept(std::declval<const std::hash<T>>()(std::declval<const T&>()))) {
424 return std::hash<T>::operator()(v.GetUnderlying());
425 }
426};
427
428// fmt::format support
429template <USERVER_NAMESPACE::utils::impl::strong_typedef::IsStrongTypedef T, class Char>
430requires(!USERVER_NAMESPACE::utils::impl::strong_typedef::Range<T>)
431struct fmt::formatter<T, Char> : fmt::formatter<typename T::UnderlyingType, Char> {
432 template <typename FormatContext>
433 auto format(const T& v, FormatContext& ctx) USERVER_FMT_CONST {
434 USERVER_NAMESPACE::utils::impl::strong_typedef::CheckIfAllowsLogging<T>();
435 return fmt::formatter<typename T::UnderlyingType, Char>::format(v.GetUnderlying(), ctx);
436 }
437};