Blob Blame History Raw
From 33c00d095b5bf1055e32de783d34104829393464 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Miro=20Hron=C4=8Dok?= <miro@hroncok.cz>
Date: Fri, 30 Dec 2016 16:11:26 +0100
Subject: [PATCH] Always use little endian when loading/saving binary STLs

This is neccessary to make this work on big endian architectures,
up until now the saving and loading was arch specific.

Binary STLs saved as little endian (most of the existing STLs)
where not compatible with numpy-stl running on big endian system.

Fixes https://github.com/WoLpH/numpy-stl/issues/43
---
 stl/base.py             | 1 +
 stl/stl.py              | 4 ++--
 tests/stl_corruption.py | 2 +-
 3 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/stl/base.py b/stl/base.py
index b322d8b..c5ea28c 100644
--- a/stl/base.py
+++ b/stl/base.py
@@ -145,6 +145,7 @@ class BaseMesh(logger.Logged, collections.Mapping):
         (s('vectors'), numpy.float32, (3, 3)),
         (s('attr'), numpy.uint16, (1, )),
     ])
+    dtype = dtype.newbyteorder('<')  # Even on big endian arches, use little e.
 
     def __init__(self, data, calculate_normals=True,
                  remove_empty_areas=False,
diff --git a/stl/stl.py b/stl/stl.py
index c438a95..b4753a6 100644
--- a/stl/stl.py
+++ b/stl/stl.py
@@ -97,7 +97,7 @@ def _load_binary(cls, fh, header, check_size=False):
         if len(count_data) != COUNT_SIZE:
             count = 0
         else:
-            count, = struct.unpack(s('@i'), b(count_data))
+            count, = struct.unpack(s('<i'), b(count_data))
         # raise RuntimeError()
         assert count < MAX_COUNT, ('File too large, got %d triangles which '
                                    'exceeds the maximum of %d') % (
@@ -286,7 +286,7 @@ def _write_binary(self, fh, name):
 
         # Make it exactly 80 characters
         header = header[:80].ljust(80, ' ')
-        packed = struct.pack(s('@i'), self.data.size)
+        packed = struct.pack(s('<i'), self.data.size)
 
         if isinstance(fh, io.TextIOWrapper):  # pragma: no cover
             packed = str(packed)
diff --git a/tests/stl_corruption.py b/tests/stl_corruption.py
index 405b9c6..aa6f5e8 100644
--- a/tests/stl_corruption.py
+++ b/tests/stl_corruption.py
@@ -99,7 +99,7 @@ def test_corrupt_ascii_file(tmpdir, speedups):
         fh.seek(40)
         print(' ' * 100, file=fh)
         fh.seek(80)
-        fh.write(struct.pack('@i', 10).decode('utf-8'))
+        fh.write(struct.pack('<i', 10).decode('utf-8'))
         fh.seek(0)
         with pytest.raises(AssertionError):
             mesh.Mesh.from_file(str(tmp_file), fh=fh, speedups=speedups)