Skip to content

Commit 20a8a89

Browse files
Use xtl::endianness instead of bundling it
1 parent e3219e9 commit 20a8a89

2 files changed

Lines changed: 28 additions & 21 deletions

File tree

include/xtensor/xnpy.hpp

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
// relicensed from MIT License with permission
1616

1717
#include <xtl/xsequence.hpp>
18+
#include <xtl/xplatform.hpp>
1819

1920
#include <algorithm>
2021
#include <complex>
@@ -43,24 +44,9 @@ namespace xt
4344
namespace detail
4445
{
4546

46-
/* Test for endianess. Compiler can optimize that to a single constant. */
47-
static inline bool is_big_endian()
48-
{
49-
uint32_t utmp = 0x01020304;
50-
char btmp[sizeof(utmp)];
51-
std::memcpy(&btmp[0], &utmp, sizeof(utmp));
52-
const bool big_endian = btmp[0] == 0x01;
53-
return big_endian;
54-
}
55-
5647
const char magic_string[] = "\x93NUMPY";
57-
const std::size_t magic_string_length = 6;
58-
59-
const char little_endian_char = '<';
60-
const char big_endian_char = '>';
61-
const char no_endian_char = '|';
48+
const std::size_t magic_string_length = sizeof(magic_string) - 1;
6249

63-
const char host_endian_char = (is_big_endian() ? big_endian_char : little_endian_char);
6450

6551
template <class O>
6652
inline void write_magic(O& ostream,
@@ -126,9 +112,23 @@ namespace xt
126112
}
127113

128114
template <class T>
129-
constexpr char get_endianess()
115+
inline char get_endianess()
130116
{
131-
return sizeof(T) <= sizeof(char) ? no_endian_char : host_endian_char;
117+
constexpr char little_endian_char = '<';
118+
constexpr char big_endian_char = '>';
119+
constexpr char no_endian_char = '|';
120+
121+
if(sizeof(T) <= sizeof(char))
122+
return no_endian_char;
123+
124+
switch(xtl::endianness()) {
125+
case xtl::endian::little_endian:
126+
return little_endian_char;
127+
case xtl::endian::big_endian:
128+
return big_endian_char;
129+
default:
130+
return no_endian_char;
131+
}
132132
}
133133

134134
template <class T>

test/test_xnpy.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,17 @@
1818
namespace xt
1919
{
2020
std::string get_load_filename(std::string const& npy_prefix, layout_type lt = layout_type::row_major) {
21-
using detail::is_big_endian;
2221
std::string lts = lt == layout_type::row_major ? "" : "_fortran";
23-
std::string endianess = is_big_endian() ? ".be" : ".le";
24-
return npy_prefix + lts + endianess + ".npy";
22+
std::string endianness;
23+
switch(xtl::endianness()) {
24+
case xtl::endian::big_endian:
25+
endianness = ".be";
26+
break;
27+
case xtl::endian::little_endian:
28+
endianness = ".le";
29+
break;
30+
};
31+
return npy_prefix + lts + endianness + ".npy";
2532
}
2633

2734
TEST(xnpy, load)

0 commit comments

Comments
 (0)