Saturated addition for signed and unsigned longs
Original issue created by finnw1 on 2011-10-13 at 01:46 AM
The various saturatedCast methods allow saturated addition of bytes/shorts/ints, e.g.
byte x = 99, y = 99; // ... byte z = SignedBytes.saturatedCast((long) x + (long) y); // => 127
This does not work for longs however, because there is no primitive type large enough to hold the intermediate result.
So it would be nice to have methods to perform saturated adds directly.
I have not included saturatedMultiply because I don't know whether it is feasible or whether there is any demand for it.
Original comment posted by wasserman.louis on 2011-10-16 at 11:23 PM
We considered this, but came to the conclusion that saturatedAdd, etc. wasn't nearly as common a use case as checkedAdd. Do you have an actual use case?
Status: Triaged
Original comment posted by finnw1 on 2011-10-17 at 01:08 AM
I use it to implement longValue() in a subclass of Number. I don't know how common that is though.
Original comment posted by wasserman.louis on 2011-10-18 at 05:59 PM
FYI, these methods would definitely go into common.math, not common.primitives.
Original comment posted by [email protected] on 2011-11-15 at 10:15 PM
I'd like to have more evidence of actual user demand for this.
Labels: Type-Enhancement
Original comment posted by [email protected] on 2011-12-10 at 04:21 PM
(No comment entered for this change.)
Labels: Package-Primitives
Original comment posted by [email protected] on 2012-02-16 at 07:17 PM
(No comment entered for this change.)
Status: Acknowledged
Original comment posted by [email protected] on 2012-05-30 at 07:43 PM
(No comment entered for this change.)
Labels: -Type-Enhancement, Type-Addition
Original comment posted by [email protected] on 2012-06-22 at 06:16 PM
(No comment entered for this change.)
Status: Research
Original comment posted by kasperni on 2013-01-07 at 03:05 PM
FWIW I use a saturated long add to calculate deadlines in the form of
void await(long timeout, TimeUnit unit) { long deadline=saturatedAdd(System.nanoTime(), unit.toNanos(timeout))
for(;;) { sleep(deadline-System.nanoTime(); } }
I just wanted this for the exact same purpose mentioned by _kasperni_.
We added this in 2015 to IntMath and LongMath. I don't think we've done it for UnsignedLongs.