Skip to content

Commit

Permalink
Avoid panic branches in TextDecoder
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Jan 7, 2025
1 parent dce3c57 commit d773b99
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/base/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ impl SharedEncoding {
#[must_use]
pub fn get(&self) -> &'static Encoding {
let encoding = self.encoding.load(Ordering::Relaxed);
ALL_ENCODINGS[encoding]
// it will never be out of range, but get() avoids a panic branch
ALL_ENCODINGS.get(encoding).unwrap_or(&ALL_ENCODINGS[0])
}

pub fn set(&self, encoding: AsciiCompatibleEncoding) {
Expand Down
10 changes: 8 additions & 2 deletions src/rewritable_units/text_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,13 @@ impl TextDecoder {
// the last call to feed_text() may make multiple calls to output_handler,
// but only one call to output_handler can be *the* last one.
let really_last = last_in_text_node && finished_decoding;
(output_handler)(&buffer[..written], really_last, encoding)?;

(output_handler)(
// this will always be in bounds, but unwrap_or_default optimizes better
buffer.get(..written).unwrap_or_default(),
really_last,
encoding,
)?;
}

if finished_decoding {
Expand All @@ -76,7 +82,7 @@ impl TextDecoder {
}
return Ok(());
}
raw_input = &raw_input[read..];
raw_input = raw_input.get(read..).unwrap_or_default();
}
}

Expand Down

0 comments on commit d773b99

Please sign in to comment.