Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perf: Don't allocate as much in Decoder::string #168

Merged
merged 1 commit into from
Oct 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions rspirv/binary/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::spirv;
use super::DecodeError as Error;
use std::convert::TryInto;
use std::result;
use std::str;

pub type Result<T> = result::Result<T, Error>;

Expand Down Expand Up @@ -160,20 +161,31 @@ impl<'a> Decoder<'a> {
/// null character (`\0`), or reaching the limit or end of the stream
/// and erroring out.
pub fn string(&mut self) -> Result<String> {
let start_offset = self.offset;
let mut bytes = vec![];
loop {
let word = self.word()?;
bytes.extend(&word.to_le_bytes());
if bytes.last() == Some(&0) {
break;
}
}
while !bytes.is_empty() && bytes.last() == Some(&0) {
bytes.pop();
// If we have a limit, then don't search further than we need to.
let slice = match self.limit {
Some(limit) => &self.bytes[self.offset..(self.offset + limit * WORD_NUM_BYTES)],
None => &self.bytes[self.offset..],
};
// Find the null terminator.
let first_null_byte =
slice
.iter()
.position(|&c| c == 0)
.ok_or_else(|| match self.limit {
Some(_) => Error::LimitReached(self.offset + slice.len()),
None => Error::StreamExpected(self.offset),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this also be self.offset + slice.len() since previously this would only happen scanning one of the last words in the slice?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, tests assert this behavior. I don't know why, but, they do.

})?;
// Validate the string is utf8.
let result = str::from_utf8(&slice[..first_null_byte])
.map_err(|e| Error::DecodeStringFailed(self.offset, format!("{}", e)))?;
// Round up consumed words to include null byte(s).
let consumed_words = (first_null_byte / WORD_NUM_BYTES) + 1;
self.offset += consumed_words * WORD_NUM_BYTES;
if let Some(ref mut limit) = self.limit {
// This is guaranteed to be enough due to the slice limit above.
*limit -= consumed_words;
}
String::from_utf8(bytes)
.map_err(|e| Error::DecodeStringFailed(start_offset, format!("{}", e)))
Ok(result.to_string())
}

/// Decodes and returns the next SPIR-V word as a 32-bit
Expand Down