Skip to content

Commit 740defa

Browse files
committed
fix: avoid char-boundary panic in NBReader::try_read
1 parent 4138c86 commit 740defa

1 file changed

Lines changed: 7 additions & 10 deletions

File tree

src/reader.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -203,11 +203,9 @@ impl NBReader {
203203
pub fn try_read(&mut self) -> Option<char> {
204204
// discard eventual errors, EOF will be handled in read_until correctly
205205
let _ = self.read_into_buffer();
206-
if !self.buffer.is_empty() {
207-
self.buffer.drain(..1).last()
208-
} else {
209-
None
210-
}
206+
let first = self.buffer.chars().next()?;
207+
self.buffer.drain(..first.len_utf8());
208+
Some(first)
211209
}
212210
}
213211

@@ -459,14 +457,13 @@ mod tests {
459457
}
460458

461459
#[test]
462-
#[should_panic(expected = "is_char_boundary")]
463460
fn test_try_read_multibyte() {
464-
// Reproduces the char-boundary panic when the buffer holds a
465-
// multi-byte UTF-8 char. Filling `buffer` directly keeps the
466-
// test fully synchronous.
461+
// Filling `buffer` directly keeps the test fully synchronous.
467462
let f = io::Cursor::new("");
468463
let mut r = NBReader::new(f, Options::default());
469464
r.buffer.push_str("\u{c3}\u{83}");
470-
let _ = r.try_read();
465+
assert_eq!(Some('\u{c3}'), r.try_read());
466+
assert_eq!(Some('\u{83}'), r.try_read());
467+
assert_eq!(None, r.try_read());
471468
}
472469
}

0 commit comments

Comments
 (0)