Skip to content

Commit

Permalink
fix: more robust probing of ascii
Browse files Browse the repository at this point in the history
See nschloe/meshio#530

Some binary files from Solidworks start with `solid` and have a `\n` on
the 80th byte, tricking the parser into thinking that it's ascii, not binary.
  • Loading branch information
razielgn committed Sep 27, 2023
1 parent d45e12b commit d71c275
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,14 @@ where
R: ::std::io::Read + ::std::io::Seek,
{
match AsciiStlReader::probe(read) {
Ok(()) => AsciiStlReader::create_triangle_iterator(read),
Err(_) => BinaryStlReader::create_triangle_iterator(read),
Ok(()) => {
read.seek(::std::io::SeekFrom::Start(0))?;
AsciiStlReader::create_triangle_iterator(read)
}
Err(_) => {
read.seek(::std::io::SeekFrom::Start(0))?;
BinaryStlReader::create_triangle_iterator(read)
}
}
}

Expand Down Expand Up @@ -382,18 +388,25 @@ impl<'a> ::std::iter::Iterator for AsciiStlReader<'a> {
impl<'a> AsciiStlReader<'a> {
/// Test whether or not read is an ascii STL file.
pub fn probe<F: ::std::io::Read + ::std::io::Seek>(read: &mut F) -> Result<()> {
let mut header = String::new();
let maybe_read_error = BufReader::new(&mut *read).read_line(&mut header);
// Try to seek back to start before evaluating potential read errors.
read.seek(::std::io::SeekFrom::Start(0))?;
maybe_read_error?;
if !header.starts_with("solid ") {
let mut header = [0u8; 80];
let len = read.read(&mut header)?;

if len != header.len() && header.starts_with(b"solid ") {
return Ok(());
}

let mut after_header = [0u8; 80];
read.read(&mut after_header)?;

if header.starts_with(b"solid ") && ::std::str::from_utf8(&after_header).is_ok() {
println!("ascii");
Ok(())
} else {
println!("binary");
Err(::std::io::Error::new(
::std::io::ErrorKind::InvalidData,
"ascii STL does not start with \"solid \"",
))
} else {
Ok(())
}
}
/// Factory to create a new ascii STL Reader from read.
Expand Down

0 comments on commit d71c275

Please sign in to comment.