Skip to content

natural comparison can cause panic due to numerical overflow #9

@z33ky

Description

@z33ky

The natural comparison functions can cause a panic if the strings contain numbers that do not fit in u64.
Example:

#!/usr/bin/env -S cargo +nightly -Z script
```cargo
[dependencies]
lexical-sort = { version = "*" }
```

fn main() {
    lexical_sort::natural_cmp("00000000000000000000", "18446744073709551616");
}

Result:

thread 'main' panicked at src/cmp.rs:152:21:
attempt to add with overflow

caused by

n1 = n1 * 10 + ascii_to_u64(lhs);

A potential fix could be to compare ASCII digits iteratively, instead of trying to convert the whole number to do the comparison.
I have a POC here, and while it works I feel the implementation is a bit hard to read and understand and can probably be improved (hence I'm not opening a PR right now).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions