Skip to content

fix(mathutil): stop inclusive ranges at MaxInt - #337

Open
Muneer320 wants to merge 1 commit into
gookit:masterfrom
Muneer320:fix/inclusive-range-overflow
Open

Muneer320 wants to merge 1 commit into
gookit:masterfrom
Muneer320:fix/inclusive-range-overflow

Conversation

@Muneer320

Copy link
Copy Markdown
Contributor

An inclusive integer range ending at MaxInt increments its counter after emitting the endpoint, wraps to MinInt, and continues. Even a one-value range such as MaxInt-MaxInt emits extra values instead of returning. The expansion helper has the same loop.

Iterate values below the upper bound, then emit the inclusive endpoint separately in both Range and Expand. This avoids incrementing past MaxInt while preserving singleton, reversed and negative ranges.

A bounded public API reproduction:

package main

import (
	"fmt"

	"github.com/gookit/goutil/mathutil"
)

func main() {
	maxInt := int(^uint(0) >> 1)
	expression := fmt.Sprintf("%d-%d", maxInt, maxInt)
	calls := 0
	err := mathutil.Range(expression, func(value int) {
		calls++
		if calls > 1 {
			// Bound the reproducer if iteration continues past the endpoint.
			panic(fmt.Sprintf("unexpected callback %d with value %d", calls, value))
		}
		fmt.Println("range value:", value)
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("callbacks:", calls)
	values, err := mathutil.Expand(expression)
	if err != nil {
		panic(err)
	}
	fmt.Println("expanded:", values)
}

On original master, it prints the maximum value and then the guard panics on callback 2 with the minimum value. The guard deliberately prevents runaway iteration; Expand is not reached on the original code. With the fix, the program returns after one callback and expands the expression to a one-element slice.

Verification on Windows/Go 1.25.1:

  • The bounded public reproduction fails before and succeeds after.
  • Local endpoint probes cover both functions at maximum/minimum integers, adjacent endpoints, reversed ranges, ordinary ranges, crossing zero and singleton values.
  • Existing mathutil package: 112 passing test/subtest results.
  • Both functions pass all 18 local endpoint cases (20 results including their parent tests).
  • Formatting and diff whitespace checks pass.

Extra probes remain local. The full repository suite, other Go versions and other platforms have not been run locally; the upstream matrix will provide those checks.

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.

1 participant