Skip to content

Commit 2921ca6

Browse files
kawadakksdroege
authored andcommitted
glib: Fix overflow in StrV::reserve when checking capacity
The left hand side of the condition `self.len + additional + 1 <= self. capacity` could overflow and wrap around if `additional` was set to a huge value, causing `reserve` to return without reserving a specified capacity.
1 parent 6f3e317 commit 2921ca6

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

glib/src/collections/strv.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -712,7 +712,7 @@ impl StrV {
712712
#[allow(clippy::int_plus_one)]
713713
pub fn reserve(&mut self, additional: usize) {
714714
// Nothing new to reserve as there's still enough space
715-
if self.len + additional + 1 <= self.capacity {
715+
if additional < self.capacity - self.len {
716716
return;
717717
}
718718

@@ -1781,4 +1781,14 @@ mod test {
17811781
assert!(strv.contains("str2"));
17821782
assert!(!strv.contains("str4"));
17831783
}
1784+
1785+
#[test]
1786+
#[should_panic]
1787+
fn test_reserve_overflow() {
1788+
let mut strv = StrV::from(&[crate::gstr!("foo"); 3][..]);
1789+
1790+
// An old implementation of `reserve` used the condition `self.len +
1791+
// additional + 1 <= self.capacity`, which was prone to overflow
1792+
strv.reserve(usize::MAX - 3);
1793+
}
17841794
}

0 commit comments

Comments
 (0)