byte_units.h raw

   1  // Copyright (c) 2025-present The Limenka developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #ifndef LIMENKA_UTIL_BYTE_UNITS_H
   6  #define LIMENKA_UTIL_BYTE_UNITS_H
   7  
   8  #include <util/overflow.h>
   9  
  10  #include <cstdint>
  11  #include <limits>
  12  #include <stdexcept>
  13  
  14  namespace util::detail {
  15  template <unsigned SHIFT>
  16  consteval uint64_t ByteUnitsToBytes(unsigned long long units)
  17  {
  18      const auto bytes{CheckedLeftShift(units, SHIFT)};
  19      if (!bytes || *bytes > std::numeric_limits<uint64_t>::max()) {
  20          throw std::overflow_error("Too large");
  21      }
  22      return *bytes;
  23  }
  24  } // namespace util::detail
  25  
  26  /// Conversion of MiB to bytes.
  27  consteval uint64_t operator""_MiB(unsigned long long mebibytes)
  28  {
  29      return util::detail::ByteUnitsToBytes<20>(mebibytes);
  30  }
  31  
  32  /// Conversion of GiB to bytes.
  33  consteval uint64_t operator""_GiB(unsigned long long gibibytes)
  34  {
  35      return util::detail::ByteUnitsToBytes<30>(gibibytes);
  36  }
  37  
  38  #endif // LIMENKA_UTIL_BYTE_UNITS_H
  39