From 29e38253b57823cc386c6b483439e6016730cdec Mon Sep 17 00:00:00 2001 From: Michael Hebert Date: Thu, 2 Jan 2025 10:29:09 -0500 Subject: [PATCH 1/2] Add test for binary STLs with 'solid' header and fix STLDocument --- src/STLDocument.cs | 31 ++++++++++++--------------- tests/Data/BinaryWithSolidHeader.stl | Bin 0 -> 684 bytes tests/STLDocumentTests.cs | 13 +++++++++++ 3 files changed, 27 insertions(+), 17 deletions(-) create mode 100644 tests/Data/BinaryWithSolidHeader.stl diff --git a/src/STLDocument.cs b/src/STLDocument.cs index db9d317..0db288b 100644 --- a/src/STLDocument.cs +++ b/src/STLDocument.cs @@ -125,22 +125,7 @@ public void AppendFacets(IEnumerable facets) /// True if the is text-based, otherwise false. public static bool IsText(Stream stream) { - if (stream == null) throw new NullReferenceException(nameof(stream)); - - const string solid = "solid"; - - byte[] buffer = new byte[5]; - string header; - - // Reset the stream to tbe beginning and read the first few bytes, then reset the stream to the beginning again. - stream.Seek(0, SeekOrigin.Begin); - stream.Read(buffer, 0, buffer.Length); - stream.Seek(0, SeekOrigin.Begin); - - // Read the header as ASCII. - header = Encoding.ASCII.GetString(buffer); - - return solid.Equals(header, StringComparison.InvariantCultureIgnoreCase); + return !IsBinary(stream); } /// Determines if the contained within the is binary-based. @@ -149,7 +134,19 @@ public static bool IsText(Stream stream) /// True if the is binary-based, otherwise false. public static bool IsBinary(Stream stream) { - return !IsText(stream); + if (stream == null) throw new NullReferenceException(nameof(stream)); + + using var reader = new BinaryReader(stream, Encoding.Default, true); + + stream.Seek(80, SeekOrigin.Begin); + + var numTriangles = reader.ReadUInt32(); + + var expectedSize = 84 + numTriangles * 50; + + stream.Seek(0, SeekOrigin.Begin); + + return stream.Length == expectedSize; } /// Reads the contained within the into a new . diff --git a/tests/Data/BinaryWithSolidHeader.stl b/tests/Data/BinaryWithSolidHeader.stl new file mode 100644 index 0000000000000000000000000000000000000000..2b6574634474680940996aa6490b124d58fe1c97 GIT binary patch literal 684 zcmb`BO$vih5Q9BH58+L`OKTT}LKmfbZ|2pUFZ1I=9@2$@ktCCh@B4Yb=JD~nKgUaO z8(J)rsnth3baB(-Rq8e}#iitXBV7Fl7tMg&xr* Date: Thu, 2 Jan 2025 15:30:22 -0500 Subject: [PATCH 2/2] rm line break --- src/STLDocument.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/STLDocument.cs b/src/STLDocument.cs index 0db288b..c5b729c 100644 --- a/src/STLDocument.cs +++ b/src/STLDocument.cs @@ -140,9 +140,8 @@ public static bool IsBinary(Stream stream) stream.Seek(80, SeekOrigin.Begin); - var numTriangles = reader.ReadUInt32(); - - var expectedSize = 84 + numTriangles * 50; + const numTriangles = reader.ReadUInt32(); + const expectedSize = 84 + numTriangles * 50; stream.Seek(0, SeekOrigin.Begin);