Account for self.extra in size_hint for EncodeWide

This commit is contained in:
Deadbeef 2021-06-19 12:59:22 +08:00
parent ec57c60c50
commit 15cdb28f5b
2 changed files with 14 additions and 1 deletions

View file

@ -853,10 +853,11 @@ impl<'a> Iterator for EncodeWide<'a> {
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (low, high) = self.code_points.size_hint();
let ext = (self.extra != 0) as usize;
// every code point gets either one u16 or two u16,
// so this iterator is between 1 or 2 times as
// long as the underlying iterator.
(low, high.and_then(|n| n.checked_mul(2)))
(low + ext, high.and_then(|n| n.checked_mul(2)).and_then(|n| n.checked_add(ext)))
}
}

View file

@ -395,3 +395,15 @@ fn wtf8_encode_wide() {
vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]
);
}
#[test]
fn wtf8_encode_wide_size_hint() {
let string = Wtf8Buf::from_str("\u{12345}");
let mut iter = string.encode_wide();
assert_eq!((1, Some(8)), iter.size_hint());
iter.next().unwrap();
assert_eq!((1, Some(1)), iter.size_hint());
iter.next().unwrap();
assert_eq!((0, Some(0)), iter.size_hint());
assert!(iter.next().is_none());
}