• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017, OpenCensus Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package io.opencensus.common;
18 
19 import java.math.BigInteger;
20 
21 /** Util class for {@link Timestamp} and {@link Duration}. */
22 final class TimeUtils {
23   static final long MAX_SECONDS = 315576000000L;
24   static final int MAX_NANOS = 999999999;
25   static final long MILLIS_PER_SECOND = 1000L;
26   static final long NANOS_PER_MILLI = 1000 * 1000;
27   static final long NANOS_PER_SECOND = NANOS_PER_MILLI * MILLIS_PER_SECOND;
28 
TimeUtils()29   private TimeUtils() {}
30 
31   /**
32    * Compares two longs. This functionality is provided by {@code Long.compare(long, long)} in Java
33    * 7.
34    */
compareLongs(long x, long y)35   static int compareLongs(long x, long y) {
36     if (x < y) {
37       return -1;
38     } else if (x == y) {
39       return 0;
40     } else {
41       return 1;
42     }
43   }
44 
45   private static final BigInteger MAX_LONG_VALUE = BigInteger.valueOf(Long.MAX_VALUE);
46   private static final BigInteger MIN_LONG_VALUE = BigInteger.valueOf(Long.MIN_VALUE);
47 
48   /**
49    * Adds two longs and throws an {@link ArithmeticException} if the result overflows. This
50    * functionality is provided by {@code Math.addExact(long, long)} in Java 8.
51    */
checkedAdd(long x, long y)52   static long checkedAdd(long x, long y) {
53     BigInteger sum = BigInteger.valueOf(x).add(BigInteger.valueOf(y));
54     if (sum.compareTo(MAX_LONG_VALUE) > 0 || sum.compareTo(MIN_LONG_VALUE) < 0) {
55       throw new ArithmeticException("Long sum overflow: x=" + x + ", y=" + y);
56     }
57     return x + y;
58   }
59 }
60