Skip to content

refactor(helpers): safely convert usize to u64 and add unit tests for resize_to_next_power_of_two #1016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 47 additions & 3 deletions crates/math/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,54 @@ pub fn resize_to_next_power_of_two<F: IsFFTField>(
trace_colums: &mut [alloc::vec::Vec<FieldElement<F>>],
) {
trace_colums.iter_mut().for_each(|col| {
// TODO: Remove this unwrap. This may panic if the usize cant be
// casted into a u64.
let col_len = col.len().try_into().unwrap();
// Convert usize to u64 safely, handling potential overflow
let col_len = match col.len().try_into() {
Ok(len) => len,
Err(_) => {
// If usize is larger than u64::MAX, use u64::MAX as a reasonable fallback
u64::MAX
}
};
let next_power_of_two_len = next_power_of_two(col_len);
col.resize(next_power_of_two_len as usize, FieldElement::<F>::zero())
})
}

#[cfg(test)]
mod tests {
use super::*;
use crate::field::test_fields::u64_test_field::U64TestField;

#[test]
fn test_resize_to_next_power_of_two() {
let mut trace_columns = vec![
vec![FieldElement::<U64TestField>::one(); 5],
vec![FieldElement::<U64TestField>::one(); 3],
];

resize_to_next_power_of_two(&mut trace_columns);

// First column should be resized to 8 (next power of 2 after 5)
assert_eq!(trace_columns[0].len(), 8);
// Second column should be resized to 4 (next power of 2 after 3)
assert_eq!(trace_columns[1].len(), 4);

// Check that the original values are preserved
for i in 0..5 {
assert_eq!(trace_columns[0][i], FieldElement::<U64TestField>::one());
}

for i in 0..3 {
assert_eq!(trace_columns[1][i], FieldElement::<U64TestField>::one());
}

// Check that new elements are zeros
for i in 5..8 {
assert_eq!(trace_columns[0][i], FieldElement::<U64TestField>::zero());
}

for i in 3..4 {
assert_eq!(trace_columns[1][i], FieldElement::<U64TestField>::zero());
}
}
}