Skip to content

fix(number): reject bare dot and repeated plus in string-to-number conversions - #374

Open
fabrianivan wants to merge 1 commit into
spf13:masterfrom
fabrianivan:fix/reject-bare-dot-and-repeated-plus
Open

fabrianivan wants to merge 1 commit into
spf13:masterfrom
fabrianivan:fix/reject-bare-dot-and-repeated-plus

Conversation

@fabrianivan

Copy link
Copy Markdown

Problem

  1. Bare dot treated as zero: In trimDecimal, strings containing only a dot or signed dot (".", "+.", "-.") match stringNumberRe (^([-+]?\d*)(\.\d*)?$). Because digits before and after the dot are both optional, the empty integer part is captured and mapped to "0", "+0", or "-0". As a result, cast.ToIntE(".") returns 0, nil without error, while cast.ToFloat64E(".") and strconv.ParseFloat fail with syntax errors.
  2. Multiple plus signs accepted: In parseUint, strings.TrimLeft(..., "+") was used, which strips all leading plus signs. Consequently, invalid numeric strings like "++5" or "+++5" were parsed as 5, nil instead of being rejected.

Solution

  1. In trimDecimal, immediately return s when s is ".", "+.", or "-." so strconv.ParseInt and strconv.ParseUint can reject it with strconv.ErrSyntax.
  2. In parseUint, use strings.TrimPrefix(..., "+") instead of strings.TrimLeft so only a single optional leading plus sign is stripped.

Verification

  • Added test cases in number_internal_test.go and number_test.go (TestInvalidNumberStrings) for ".", "+.", "-.", and "++5".
  • Verified all tests pass cleanly with go test -v -race ./... and go vet ./....

…nversions

1. In trimDecimal, strings with only a dot or signed dot ('.', '+.', '-.')
previously matched stringNumberRe, capturing an empty integer part that was
then mapped to '0', '+0', or '-0', allowing ToIntE('.') to return 0 with no error
while ToFloat64E('.') failed. This change skips trimming for bare dot inputs so
strconv.ParseInt/ParseUint can properly reject them as invalid syntax.

2. In parseUint, strings.TrimLeft was used on '+', which inadvertently stripped
multiple plus signs (e.g. '++5' parsed as 5). Replaced with strings.TrimPrefix
so only a single optional plus sign is stripped.
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

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.

2 participants