From f64f51b88de9d870c8e2a8b9898a137d3f92171f Mon Sep 17 00:00:00 2001 From: Ben Deane Date: Mon, 11 Sep 2023 16:49:33 -0600 Subject: [PATCH] :sparkles: Add UDLs for useful byte sizes --- docs/utility.adoc | 17 +++++++++++++++++ include/stdx/utility.hpp | 28 ++++++++++++++++++++++++++++ test/udls.cpp | 14 ++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/docs/utility.adoc b/docs/utility.adoc index 80dd9bf..39cabbe 100644 --- a/docs/utility.adoc +++ b/docs/utility.adoc @@ -45,3 +45,20 @@ using my_type_without_X = my_type<"X"_false>; using my_type_with_X_alt = my_type<"X"_b>; using my_type_without_X_alt = my_type; ---- + +And some UDLs that are useful when specifying sizes in bytes: + +[source,cpp] +---- +using namespace stdx::literals; + +// decimal SI prefixes +constexpr auto a = 1_k; // 1,000 +constexpr auto b = 1_M; // 1,000,000 +constexpr auto c = 1_G; // 1,000,000,000 + +// binary equivalents +constexpr auto d = 1_ki; // 1,024 +constexpr auto e = 1_Mi; // 1,048,567 +constexpr auto f = 1_Gi; // 1,073,741,824 +---- diff --git a/include/stdx/utility.hpp b/include/stdx/utility.hpp index c710fb8..4e64b35 100644 --- a/include/stdx/utility.hpp +++ b/include/stdx/utility.hpp @@ -23,6 +23,34 @@ CONSTEVAL auto operator""_true(char const *, std::size_t) -> bool { CONSTEVAL auto operator""_false(char const *, std::size_t) -> bool { return false; } + +// NOLINTBEGIN(google-runtime-int) +CONSTEVAL auto operator""_k(unsigned long long int n) + -> unsigned long long int { + return n * 1'000u; +} +CONSTEVAL auto operator""_M(unsigned long long int n) + -> unsigned long long int { + return n * 1'000'000u; +} +CONSTEVAL auto operator""_G(unsigned long long int n) + -> unsigned long long int { + return n * 1'000'000'000u; +} + +CONSTEVAL auto operator""_ki(unsigned long long int n) + -> unsigned long long int { + return n * 1'024u; +} +CONSTEVAL auto operator""_Mi(unsigned long long int n) + -> unsigned long long int { + return n * 1'024ull * 1'024ull; +} +CONSTEVAL auto operator""_Gi(unsigned long long int n) + -> unsigned long long int { + return n * 1'024ull * 1'024ull * 1'024ull; +} +// NOLINTEND(google-runtime-int) } // namespace literals [[noreturn]] inline auto unreachable() -> void { __builtin_unreachable(); } diff --git a/test/udls.cpp b/test/udls.cpp index af6ac13..775fcce 100644 --- a/test/udls.cpp +++ b/test/udls.cpp @@ -10,3 +10,17 @@ TEST_CASE("compile-time named bools", "[utility]") { static_assert("variable"_true); static_assert(not "variable"_false); } + +TEST_CASE("decimal units", "[units]") { + using namespace stdx::literals; + static_assert(1_k == 1'000ull); + static_assert(1_M == 1'000'000ull); + static_assert(1_G == 1'000'000'000ull); +} + +TEST_CASE("binary units", "[units]") { + using namespace stdx::literals; + static_assert(1_ki == 1'024ull); + static_assert(1_Mi == 1'024ull * 1'024ull); + static_assert(1_Gi == 1'024ull * 1'024ull * 1'024ull); +}