Skip to content
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

Fix panic when trying to compare big numbers #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

z33ky
Copy link

@z33ky z33ky commented Jul 25, 2024

The previous version tried to convert numeric strings to u64 to compare the values numerically.
This results in a panic if the number exceeds the bounds of u64. To fix this, numbers are now compared digit-by-digit instead.

Fixes #1.
This PR is pretty much identical to Aloso/lexical-sort#11. I'm copying the PR comments from there.

The previous version tried to convert numeric strings to u64 to compare
the values numerically.
This results in a panic if the number exceeds the bounds of u64.
To fix this, numbers are now compared digit-by-digit instead.

Fixes surrealdb#1.
iter::Peekable,
};

fn cmp_ascii_digits(lhs: &mut Peekable<impl Iterator<Item=char>>, rhs: &mut Peekable<impl Iterator<Item=char>>) -> Option<Ordering> {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not big on macros that change control-flow outside their scope, like cmd_ascii_digits!() did via return. I've opted to replace it with a regular function, but that's personal preference. If you liked the macro with return for the caller better, I can change it back.

}
}
(Some(_), None) => {
let _ = lhs.next();
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In practice, callers don't continue using the iterators when this returns an ordering != Ordering::Equal, so consuming the ascii digit in the non-exhausted iterator is not actually used for anything.
I just didn't feel comfortable to make this assumption in the function implementation, but I can remove it if you feel this is unnecessary.

// The loop below iterates through both iterators at once and handles ascii digits for comparison.
// If one iterator runs out of ascii digits, it is stored in this struct together with the
// information where it originated from.
struct NonDigit {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may be a bit overengineered for what can also be tracked with a (char, bool), but I think/hope this makes the use more clear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Panic due to attempt to multiply with overflow
1 participant