Skip to content

Commit 808af95

Browse files
authored
Merge pull request #172 from SAY-5/fix-try-read-char-boundary
fix: avoid char-boundary panic in NBReader::try_read
2 parents f21a254 + 740defa commit 808af95

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

src/reader.rs

Lines changed: 14 additions & 5 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

@@ -457,4 +455,15 @@ mod tests {
457455
assert_eq!(None, r.try_read());
458456
assert_eq!(None, r.try_read());
459457
}
458+
459+
#[test]
460+
fn test_try_read_multibyte() {
461+
// Filling `buffer` directly keeps the test fully synchronous.
462+
let f = io::Cursor::new("");
463+
let mut r = NBReader::new(f, Options::default());
464+
r.buffer.push_str("\u{c3}\u{83}");
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());
468+
}
460469
}

0 commit comments

Comments
 (0)