Add assert in ring_buffer.rs#1537
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adds an assertion to the RingBuffer::new constructor to prevent panics in Vec::with_capacity by checking that the capacity doesn't exceed isize::MAX. This is a defensive programming measure to catch potential allocation failures early.
Key Changes:
- Added validation to prevent capacity-related panics in
Vec::with_capacity
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| assert!(capacity < isize::MAX as usize, "capacity must be less than isize::MAX"); | ||
|
|
There was a problem hiding this comment.
The assertion condition is incorrect. According to Rust's documentation, Vec::with_capacity panics if the capacity in bytes (not the number of elements) exceeds isize::MAX. The correct check should account for the size of type T: capacity * core::mem::size_of::<T>() <= isize::MAX as usize. The current assertion checks only the element count, which may be too restrictive for small types or insufficient for large types.
| assert!(capacity < isize::MAX as usize, "capacity must be less than isize::MAX"); | |
| let elem_size = core::mem::size_of::<T>(); | |
| assert!( | |
| capacity | |
| .checked_mul(elem_size) | |
| .map_or(false, |bytes| bytes <= isize::MAX as usize), | |
| "capacity * size_of::<T>() must be <= isize::MAX" | |
| ); |
| "capacity must be a power of two" | ||
| ); | ||
|
|
||
| assert!(capacity < isize::MAX as usize, "capacity must be less than isize::MAX"); |
There was a problem hiding this comment.
The error message should be more specific about why this constraint exists and reference the underlying Vec::with_capacity limitation. Consider changing it to something like "capacity in bytes would exceed isize::MAX" to make the requirement clearer to developers.
| assert!(capacity < isize::MAX as usize, "capacity must be less than isize::MAX"); | |
| assert!( | |
| capacity < isize::MAX as usize, | |
| "capacity in bytes would exceed isize::MAX (Vec::with_capacity limitation)" | |
| ); |
|
这个assert是不必要的,因为内存管理会报错。 |
Add assert to prevent panic in Vec::with_capacity