9226d36b1309b8271e3850d909b2b9c92d6acf87
[deliverable/tracecompass.git] / common / org.eclipse.tracecompass.common.core / src / org / eclipse / tracecompass / common / core / math / SaturatedArithmetic.java
1 /*******************************************************************************
2 * Copyright (c) 2016 Ericsson
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *******************************************************************************/
9
10 package org.eclipse.tracecompass.common.core.math;
11
12 /**
13 * Saturated arithmetic. These are mathematical helper functions that are used
14 * to clamp numbers to maximum and mimumum and avoid overflows.
15 *
16 * @author Matthew Khouzam
17 * @since 2.1
18 */
19 public final class SaturatedArithmetic {
20
21 private SaturatedArithmetic() {
22 // do nothing
23 }
24
25 /**
26 * Saturated multiplication. It will not overflow but instead clamp the
27 * result to {@link Long#MAX_VALUE} and {@link Long#MIN_VALUE}.
28 *
29 * @param left
30 * The left long to multiply
31 * @param right
32 * The right long to multiply
33 * @return The saturated multiplication result. The mathematical, not Java
34 * version of Min(Max(MIN_VALUE, left*right), MAX_VALUE).
35 * @see <a href="http://en.wikipedia.org/wiki/Saturation_arithmetic">
36 * Saturation arithmetic</a>
37 */
38 public static long multiply(long left, long right) {
39 long retVal = left * right;
40 if ((left != 0) && ((retVal / left) != right)) {
41 return (sameSign(left, right) ? Long.MAX_VALUE : Long.MIN_VALUE);
42 }
43 return retVal;
44 }
45
46 /**
47 * Saturated addition. It will not overflow but instead clamp the result to
48 * {@link Long#MAX_VALUE} and {@link Long#MIN_VALUE}.
49 *
50 * @param left
51 * The left long to add
52 * @param right
53 * The right long to add
54 * @return The saturated addition result. The mathematical, not Java version
55 * of Min(Max(MIN_VALUE, left+right), MAX_VALUE).
56 * @see <a href="http://en.wikipedia.org/wiki/Saturation_arithmetic">
57 * Saturation arithmetic</a>
58 * @since 2.0
59 */
60 public static final long add(final long left, final long right) {
61 long retVal = left + right;
62 if (sameSign(left, right) && !sameSign(left, retVal)) {
63 if (retVal > 0 || left == Long.MIN_VALUE) {
64 return Long.MIN_VALUE;
65 }
66 return Long.MAX_VALUE;
67 }
68 return retVal;
69 }
70
71 /**
72 * Test if two numbers are the same sign or not
73 *
74 * @param left
75 * the left long
76 * @param right
77 * the right long
78 * @return true if both left and right are positive or both negative, false
79 * otherwise
80 */
81 public static boolean sameSign(final long left, final long right) {
82 return (left ^ right) >= 0;
83 }
84 }
This page took 0.034232 seconds and 4 git commands to generate.