unchecked-* functions have different behavior on primitive longs vs boxed Longs

Description

The behavior of unchecked-* functions such as unchecked-add, unchecked-subtract, and unchecked-multiply give different results for primitive longs (expected) and boxed longs (can get overflow exceptions). For example:

user=> *clojure-version* {:major 1, :minor 7, :incremental 0, :qualifier nil} user=> (doc unchecked-multiply) ------------------------- clojure.core/unchecked-multiply ([x y]) Returns the product of x and y, both long. Note - uses a primitive operator subject to overflow. nil user=> (unchecked-multiply 2432902008176640000 21) -4249290049419214848 user=> (unchecked-multiply 2432902008176640000 (Long. 21)) ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1501)

Normally no one would use explicit boxed Long arguments like in the example above, but these can easily occur, unintentionally, if the arguments to the unchecked functions are not explicitly type hinted as primitive long values.

Approach: clj-1832.patch

Screened: Alex Miller

Environment

None

Attachments

1
  • 13 Feb 2016, 10:14 AM

Activity

Show:

Alex MillerFebruary 24, 2016 at 9:01 PM

This looks good to me but I do not see a Contributor Agreement on file for you Alexander. Can you sign one per here: http://clojure.org/community/contributing

Alexander KielFebruary 13, 2016 at 10:14 AM

This patch correctly implements all unchecked-* functions. It assumes that the issue exists only for longs because doubles are unchecked anyway and ratios have bigints.

Alexander KielFebruary 12, 2016 at 8:38 PM

After a suggestion from Alex Miller, I started with the implementation route here: https://github.com/alexanderkiel/clojure/tree/clj-1832 But it's still work in progress.

gfredericksFebruary 11, 2016 at 5:33 PM

It's probably also worth mentioning that speed is not the only use case for unchecked operations – sometimes, e.g. with crypto algorithms, you actually want the weirder kind of arithmetic, and might not want to bother with primitives at first.

Alexander KielFebruary 11, 2016 at 10:38 AM

This costs me an hour today.

I'm with Gary as I see no performance issue. But I see a code amount issue, because the whole tree of add, multiply ... methods has to be repeated.

I would opt for a doc amendment which explains that the unchecked-* functions only work with primitive types. User which see a need for using unchecked math certainly have no problem doing a cast if necessary.

Completed

Details

Assignee

Reporter

Labels

Approval

Ok

Patch

Code and Test

Priority

Affects versions

Fix versions

Created October 26, 2015 at 7:11 AM
Updated September 14, 2018 at 10:21 PM
Resolved September 14, 2018 at 10:21 PM

Flag notifications