Skip to content

Return an error instead of panicking on integer division by zero - #567

Open
shaurya703 wants to merge 1 commit into
TomWright:masterfrom
shaurya703:fix/integer-divide-by-zero
Open

shaurya703 wants to merge 1 commit into
TomWright:masterfrom
shaurya703:fix/integer-divide-by-zero

Conversation

@shaurya703

Copy link
Copy Markdown

Bug

Dividing or taking the modulo of two integers by zero crashes dasel:

$ echo '{}' | dasel -i json '1 / 0'
panic: runtime error: integer divide by zero

goroutine 1 [running]:
github.com/tomwright/dasel/v3/model.(*Value).Divide(...)
	model/value_math.go:177

5 % 0 panics the same way. The same happens through the Go API (dasel.Select, Query), so a library caller evaluating a user-supplied selector gets a panic rather than an error.

Cause

Value.Divide and Value.Modulo apply Go's / and % directly in the int/int branch, and Go panics on integer division by zero. The float branches don't panic (they produce +Inf/NaN), so this only affects the int/int case.

Fix

Check for a zero divisor in the int/int branches and return a new model.ErrDivisionByZero. After the change:

$ echo '{}' | dasel -i json '1 / 0'
dasel: error: error executing selector: execution error when processing ast.BinaryExpr: integer division by zero

Test

TestValue_IntegerDivisionByZero in model/value_math_test.go covers Divide and Modulo. It panics before the change and passes after. go test ./... and golangci-lint run ./model/... pass.

No documentation changes needed.

Value.Divide and Value.Modulo used Go's integer / and % directly when both
operands were ints, so a selector such as `1 / 0` or `5 % 0` crashed the
process with "panic: runtime error: integer divide by zero". Check the
divisor first and return ErrDivisionByZero instead.

This branch has not been deployed

No deployments
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