Advertisement
alaestor

[FGL utility] make_byte_array

Oct 3rd, 2021
768
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #pragma once
  2. #ifndef FGL_MAKE_BYTE_ARRAY_HPP_INCLUDED
  3. #define FGL_MAKE_BYTE_ARRAY_HPP_INCLUDED
  4.  
  5. #include <cstddef> // size_t, byte
  6. #include <utility> // index_sequence, make_index_sequence
  7. #include <array>
  8. #include <type_traits>
  9. #include <concepts>
  10.  
  11. namespace fgl {
  12.  
  13. template <class T>
  14. concept StdArrayOfBytes = requires
  15. {
  16.     requires std::same_as<
  17.         std::byte,
  18.         std::remove_cv_t<typename T::value_type>>;
  19.  
  20.     requires std::same_as<
  21.         std::array<typename T::value_type, sizeof(T)>,
  22.         std::remove_cv_t<T>>;
  23. };
  24.  
  25. template <class T>
  26. concept StdArrayOfConstBytes = requires
  27. {
  28.     requires StdArrayOfBytes<T>;
  29.     requires std::is_const_v<typename T::value_type>;
  30. };
  31.  
  32. /// returns a std::array<std::byte> from cstring literal. removes null term.
  33. template<std::size_t LEN> [[nodiscard]]
  34. constexpr std::array<const std::byte, LEN-1> make_byte_array(
  35.     const char (&cstr)[LEN])
  36. {
  37.     return
  38.         [&]<std::size_t ... I>(std::index_sequence<I...>)
  39.         constexpr -> std::array<const std::byte, LEN-1>
  40.         {
  41.             return {{static_cast<const std::byte>(cstr[I])...}};
  42.         }(std::make_index_sequence<LEN-1>());
  43. }
  44.  
  45. } // namespace fgl
  46.  
  47. #endif // FGL_MAKE_BYTE_ARRAY_HPP_INCLUDED
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement