Skip to content

Add checked arithmetic to prevent integer overflow in dense trie lookups #7442

@IshaanXCoder

Description

@IshaanXCoder

Description

The ZeroAsciiDenseSparse2dTrieBorrowed::get() method currently uses unchecked arithmetic for matrix index calculations and value additions. This could potentially cause integer overflow on edge cases or with malformed data.

Current Code

File: utils/zerotrie/src/dense.rs

let suffix_count = usize::from(self.suffix_count);
let Some(offset) = self.dense.get(suffix_count * row_index + column_index) else {
    // The row and column indexes should be in-range
    debug_assert!(false);
    return None;
};
// ...
Some(usize::from(offset) + row_value_offset)

Proposed Changes

  1. Use checked arithmetic for matrix indexing:
let index = row_index
    .checked_mul(suffix_count)
    .and_then(|v| v.checked_add(column_index))?;
let Some(offset) = self.dense.get(index) else {
    unreachable!(
        "matrix index out of bounds: row={}, col={}, suffix_count={}",
        row_index, column_index, suffix_count
    );
};
  1. Use checked arithmetic for final value calculation:
usize::from(offset).checked_add(row_value_offset)

Metadata

Metadata

Assignees

Labels

C-zerovecComponent: Yoke, ZeroVec, DataBake

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions