-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Fix int respect sys.set_int_max_str_digits value
#6094
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
Merged
youknowone
merged 5 commits into
RustPython:main
from
ShaharNaveh:fix-int-respect-max-str-sys
Aug 21, 2025
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,113 +29,119 @@ pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> { | |
| }) | ||
| } | ||
|
|
||
| pub fn bytes_to_int(lit: &[u8], mut base: u32) -> Option<BigInt> { | ||
| #[derive(Debug, Eq, PartialEq)] | ||
| pub enum BytesToIntError { | ||
| InvalidLiteral { base: u32 }, | ||
| InvalidBase, | ||
| DigitLimit { got: usize, limit: usize }, | ||
| } | ||
|
|
||
| // https://github.com/python/cpython/blob/4e665351082c50018fb31d80db25b4693057393e/Objects/longobject.c#L2977 | ||
| // https://github.com/python/cpython/blob/4e665351082c50018fb31d80db25b4693057393e/Objects/longobject.c#L2884 | ||
| pub fn bytes_to_int( | ||
| buf: &[u8], | ||
| mut base: u32, | ||
| digit_limit: usize, | ||
| ) -> Result<BigInt, BytesToIntError> { | ||
| if base != 0 && !(2..=36).contains(&base) { | ||
| return Err(BytesToIntError::InvalidBase); | ||
| } | ||
|
|
||
| let mut buf = buf.trim_ascii(); | ||
|
|
||
| // split sign | ||
| let mut lit = lit.trim_ascii(); | ||
| let sign = match lit.first()? { | ||
| b'+' => Some(Sign::Plus), | ||
| b'-' => Some(Sign::Minus), | ||
| let sign = match buf.first() { | ||
| Some(b'+') => Some(Sign::Plus), | ||
| Some(b'-') => Some(Sign::Minus), | ||
| None => return Err(BytesToIntError::InvalidLiteral { base }), | ||
| _ => None, | ||
| }; | ||
|
|
||
| if sign.is_some() { | ||
| lit = &lit[1..]; | ||
| buf = &buf[1..]; | ||
| } | ||
|
|
||
| // split radix | ||
| let first = *lit.first()?; | ||
| let has_radix = if first == b'0' { | ||
| match base { | ||
| 0 => { | ||
| if let Some(parsed) = lit.get(1).and_then(detect_base) { | ||
| base = parsed; | ||
| true | ||
| } else { | ||
| if let [_first, others @ .., last] = lit { | ||
| let is_zero = | ||
| others.iter().all(|&c| c == b'0' || c == b'_') && *last == b'0'; | ||
| if !is_zero { | ||
| return None; | ||
| } | ||
| } | ||
| return Some(BigInt::zero()); | ||
| } | ||
| let mut error_if_nonzero = false; | ||
| if base == 0 { | ||
| match (buf.first(), buf.get(1)) { | ||
| (Some(v), _) if *v != b'0' => base = 10, | ||
| (_, Some(b'x' | b'X')) => base = 16, | ||
| (_, Some(b'o' | b'O')) => base = 8, | ||
| (_, Some(b'b' | b'B')) => base = 2, | ||
| (_, _) => { | ||
| // "old" (C-style) octal literal, now invalid. it might still be zero though | ||
| base = 10; | ||
| error_if_nonzero = true; | ||
| } | ||
| 16 => lit.get(1).is_some_and(|&b| matches!(b, b'x' | b'X')), | ||
| 2 => lit.get(1).is_some_and(|&b| matches!(b, b'b' | b'B')), | ||
| 8 => lit.get(1).is_some_and(|&b| matches!(b, b'o' | b'O')), | ||
| _ => false, | ||
| } | ||
| } else { | ||
| if base == 0 { | ||
| base = 10; | ||
| } | ||
| false | ||
| }; | ||
| if has_radix { | ||
| lit = &lit[2..]; | ||
| if lit.first()? == &b'_' { | ||
| lit = &lit[1..]; | ||
| } | ||
| } | ||
|
|
||
| // remove zeroes | ||
| let mut last = *lit.first()?; | ||
| if last == b'0' { | ||
| let mut count = 0; | ||
| for &cur in &lit[1..] { | ||
| if cur == b'_' { | ||
| if last == b'_' { | ||
| return None; | ||
| } | ||
| } else if cur != b'0' { | ||
| break; | ||
| }; | ||
| count += 1; | ||
| last = cur; | ||
| } | ||
| let prefix_last = lit[count]; | ||
| lit = &lit[count + 1..]; | ||
| if lit.is_empty() && prefix_last == b'_' { | ||
| return None; | ||
| if error_if_nonzero { | ||
| if let [_first, others @ .., last] = buf { | ||
| let is_zero = *last == b'0' && others.iter().all(|&c| c == b'0' || c == b'_'); | ||
| if !is_zero { | ||
| return Err(BytesToIntError::InvalidLiteral { base }); | ||
| } | ||
| } | ||
| return Ok(BigInt::zero()); | ||
| } | ||
|
|
||
| // validate | ||
| for c in lit { | ||
| let c = *c; | ||
| if !(c.is_ascii_alphanumeric() || c == b'_') { | ||
| return None; | ||
| if buf.first().is_some_and(|&v| v == b'0') | ||
| && buf.get(1).is_some_and(|&v| { | ||
| (base == 16 && (v == b'x' || v == b'X')) | ||
| || (base == 8 && (v == b'o' || v == b'O')) | ||
| || (base == 2 && (v == b'b' || v == b'B')) | ||
| }) | ||
| { | ||
| buf = &buf[2..]; | ||
|
|
||
| // One underscore allowed here | ||
| if buf.first().is_some_and(|&v| v == b'_') { | ||
| buf = &buf[1..]; | ||
| } | ||
| } | ||
|
|
||
| if c == b'_' && last == b'_' { | ||
| return None; | ||
| // Reject empty strings | ||
| let mut prev = *buf | ||
| .first() | ||
| .ok_or(BytesToIntError::InvalidLiteral { base })?; | ||
|
|
||
| // Leading underscore not allowed | ||
| if prev == b'_' || !prev.is_ascii_alphanumeric() { | ||
| return Err(BytesToIntError::InvalidLiteral { base }); | ||
| } | ||
|
|
||
|
Comment on lines
+109
to
+113
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Count only valid digits for the given base and strip underscores before parsing Two issues here:
Recommend:
Proposed patch: @@
- // Leading underscore not allowed
- if prev == b'_' || !prev.is_ascii_alphanumeric() {
- return Err(BytesToIntError::InvalidLiteral { base });
- }
-
- // Verify all characters are digits and underscores
- let mut digits = 1;
- for &cur in buf.iter().skip(1) {
- if cur == b'_' {
- // Double underscore not allowed
- if prev == b'_' {
- return Err(BytesToIntError::InvalidLiteral { base });
- }
- } else if cur.is_ascii_alphanumeric() {
- digits += 1;
- } else {
- return Err(BytesToIntError::InvalidLiteral { base });
- }
-
- prev = cur;
- }
+ // Leading underscore not allowed; also first char must be a valid digit for the base
+ #[inline]
+ fn to_digit(b: u8) -> Option<u32> {
+ match b {
+ b'0'..=b'9' => Some((b - b'0') as u32),
+ b'a'..=b'z' => Some((b - b'a' + 10) as u32),
+ b'A'..=b'Z' => Some((b - b'A' + 10) as u32),
+ _ => None,
+ }
+ }
+ if prev == b'_' || to_digit(prev).map_or(true, |v| v >= base) {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+
+ // Verify all characters are valid digits (for base) or underscores; count only valid digits
+ let mut digits = 1;
+ let mut saw_underscore = false;
+ for &cur in buf.iter().skip(1) {
+ if cur == b'_' {
+ // Double underscore not allowed
+ if prev == b'_' {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+ saw_underscore = true;
+ } else if let Some(v) = to_digit(cur) {
+ if v >= base {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+ digits += 1;
+ } else {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+
+ prev = cur;
+ }
@@
- if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
+ if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
return Err(BytesToIntError::DigitLimit {
got: digits,
limit: digit_limit,
});
}
- let uint = BigUint::parse_bytes(buf, base).ok_or(BytesToIntError::InvalidLiteral { base })?;
+ // Strip underscores before parsing
+ let uint = if saw_underscore {
+ let stripped: Vec<u8> = buf.iter().copied().filter(|&b| b != b'_').collect();
+ BigUint::parse_bytes(&stripped, base)
+ } else {
+ BigUint::parse_bytes(buf, base)
+ }
+ .ok_or(BytesToIntError::InvalidLiteral { base })?;
Ok(BigInt::from_biguint(sign.unwrap_or(Sign::Plus), uint))This keeps the same validation rules but ensures:
Also applies to: 114-129, 131-135, 136-142, 143-145 🤖 Prompt for AI Agents |
||
| // Verify all characters are digits and underscores | ||
| let mut digits = 1; | ||
| for &cur in buf.iter().skip(1) { | ||
| if cur == b'_' { | ||
| // Double underscore not allowed | ||
| if prev == b'_' { | ||
| return Err(BytesToIntError::InvalidLiteral { base }); | ||
| } | ||
| } else if cur.is_ascii_alphanumeric() { | ||
| digits += 1; | ||
| } else { | ||
| return Err(BytesToIntError::InvalidLiteral { base }); | ||
| } | ||
|
|
||
| last = c; | ||
| prev = cur; | ||
| } | ||
| if last == b'_' { | ||
| return None; | ||
|
|
||
| // Trailing underscore not allowed | ||
| if prev == b'_' { | ||
| return Err(BytesToIntError::InvalidLiteral { base }); | ||
| } | ||
|
|
||
| // parse | ||
| let number = if lit.is_empty() { | ||
| BigInt::zero() | ||
| } else { | ||
| let uint = BigUint::parse_bytes(lit, base)?; | ||
| BigInt::from_biguint(sign.unwrap_or(Sign::Plus), uint) | ||
| }; | ||
| Some(number) | ||
| } | ||
| if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit { | ||
| return Err(BytesToIntError::DigitLimit { | ||
| got: digits, | ||
| limit: digit_limit, | ||
| }); | ||
| } | ||
|
|
||
| #[inline] | ||
| pub const fn detect_base(c: &u8) -> Option<u32> { | ||
| let base = match c { | ||
| b'x' | b'X' => 16, | ||
| b'b' | b'B' => 2, | ||
| b'o' | b'O' => 8, | ||
| _ => return None, | ||
| }; | ||
| Some(base) | ||
| let uint = BigUint::parse_bytes(buf, base).ok_or(BytesToIntError::InvalidLiteral { base })?; | ||
| Ok(BigInt::from_biguint(sign.unwrap_or(Sign::Plus), uint)) | ||
| } | ||
|
|
||
| // num-bigint now returns Some(inf) for to_f64() in some cases, so just keep that the same for now | ||
|
|
@@ -144,15 +150,59 @@ pub fn bigint_to_finite_float(int: &BigInt) -> Option<f64> { | |
| int.to_f64().filter(|f| f.is_finite()) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_bytes_to_int() { | ||
| assert_eq!(bytes_to_int(&b"0b101"[..], 2).unwrap(), BigInt::from(5)); | ||
| assert_eq!(bytes_to_int(&b"0x_10"[..], 16).unwrap(), BigInt::from(16)); | ||
| assert_eq!(bytes_to_int(&b"0b"[..], 16).unwrap(), BigInt::from(11)); | ||
| assert_eq!(bytes_to_int(&b"+0b101"[..], 2).unwrap(), BigInt::from(5)); | ||
| assert_eq!(bytes_to_int(&b"0_0_0"[..], 10).unwrap(), BigInt::from(0)); | ||
| assert_eq!(bytes_to_int(&b"09_99"[..], 0), None); | ||
| assert_eq!(bytes_to_int(&b"000"[..], 0).unwrap(), BigInt::from(0)); | ||
| assert_eq!(bytes_to_int(&b"0_"[..], 0), None); | ||
| assert_eq!(bytes_to_int(&b"0_100"[..], 10).unwrap(), BigInt::from(100)); | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| const DIGIT_LIMIT: usize = 4300; // Default of Cpython | ||
|
|
||
| #[test] | ||
| fn bytes_to_int_valid() { | ||
| for ((buf, base), expected) in [ | ||
| (("0b101", 2), BigInt::from(5)), | ||
| (("0x_10", 16), BigInt::from(16)), | ||
| (("0b", 16), BigInt::from(11)), | ||
| (("+0b101", 2), BigInt::from(5)), | ||
| (("0_0_0", 10), BigInt::from(0)), | ||
| (("000", 0), BigInt::from(0)), | ||
| (("0_100", 10), BigInt::from(100)), | ||
| ] { | ||
| assert_eq!( | ||
| bytes_to_int(buf.as_bytes(), base, DIGIT_LIMIT), | ||
| Ok(expected) | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytes_to_int_invalid_literal() { | ||
| for ((buf, base), expected) in [ | ||
| (("09_99", 0), BytesToIntError::InvalidLiteral { base: 10 }), | ||
| (("0_", 0), BytesToIntError::InvalidLiteral { base: 10 }), | ||
| (("0_", 2), BytesToIntError::InvalidLiteral { base: 2 }), | ||
| ] { | ||
| assert_eq!( | ||
| bytes_to_int(buf.as_bytes(), base, DIGIT_LIMIT), | ||
| Err(expected) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytes_to_int_invalid_base() { | ||
| for base in [1, 37] { | ||
| assert_eq!( | ||
| bytes_to_int("012345".as_bytes(), base, DIGIT_LIMIT), | ||
| Err(BytesToIntError::InvalidBase) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn bytes_to_int_digit_limit() { | ||
| assert_eq!( | ||
| bytes_to_int("012345".as_bytes(), 10, 5), | ||
| Err(BytesToIntError::DigitLimit { got: 6, limit: 5 }) | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then skip() on line 116 will not be required.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually, we can't do it.
because we after we count the digits we pass the unmodified buf to bigint. so unless we want to split it, save the original first element, then iterate over the buffer, and then concat the original first element with the rest of the slice.
I think this option is a more complicated than it needs to be. but it's not a deal breaker for me