Skip to content

Commit

Permalink
Merge pull request #6 from elbeno/add-unit-udls
Browse files Browse the repository at this point in the history
✨ Add UDLs for useful byte sizes
  • Loading branch information
mjcaisse-intel authored Sep 12, 2023
2 parents c1d7cb7 + f64f51b commit 9a47918
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
17 changes: 17 additions & 0 deletions docs/utility.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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<not "X"_b>;
----

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
----
28 changes: 28 additions & 0 deletions include/stdx/utility.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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(); }
Expand Down
14 changes: 14 additions & 0 deletions test/udls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 9a47918

Please sign in to comment.