SeqAn3  3.2.0-rc.1
The Modern C++ library for sequence analysis.
to_little_endian.hpp
Go to the documentation of this file.
1 // -----------------------------------------------------------------------------------------------------
2 // Copyright (c) 2006-2022, Knut Reinert & Freie Universität Berlin
3 // Copyright (c) 2016-2022, Knut Reinert & MPI für molekulare Genetik
4 // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
5 // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
6 // -----------------------------------------------------------------------------------------------------
7 
13 #pragma once
14 
15 #include <bit>
16 #include <concepts>
17 
18 // Find correct header for byte-order conversion functions.
19 #if __has_include(<endian.h>) // unix GLIBC
20 # include <endian.h>
21 #elif __has_include(<sys/endian.h>) // *BSD
22 # include <sys/endian.h>
23 #endif // __has_include(endian.h)
24 
25 #include <seqan3/core/platform.hpp>
26 
27 namespace seqan3::detail
28 {
41 template <std::integral type>
42 constexpr type to_little_endian(type const in) noexcept
43 {
44  if constexpr (std::endian::native == std::endian::little)
45  {
46  return in;
47  }
48  else if constexpr (std::endian::native == std::endian::big)
49  {
50  static_assert(sizeof(type) <= 8,
51  "Can only convert the byte encoding for integral numbers with a size of up to 8 bytes.");
52  static_assert(std::has_single_bit(sizeof(type)),
53  "Can only convert the byte encoding for integral numbers whose byte size is a power of two.");
54 
55  if constexpr (sizeof(type) == 2)
56  return htole16(in);
57  else if constexpr (sizeof(type) == 4)
58  return htole32(in);
59  else if constexpr (sizeof(type) == 8)
60  return htole64(in);
61  else
62  return in; // single byte.
63  }
64  else
65  {
66  static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big,
67  "Expected a little-endian or big-endian platform.");
68  }
69 }
70 
71 } // namespace seqan3::detail
The <bit> header from C++20's standard library.
The <concepts> header from C++20's standard library.
Provides platform and dependency checks.