1 /* 2 * Copyright (C) 2019 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 15 package com.google.common.base; 16 17 import com.google.common.annotations.GwtIncompatible; 18 import com.google.common.annotations.J2ktIncompatible; 19 import java.time.Duration; 20 21 /** This class is for {@code com.google.common.base} use only! */ 22 @J2ktIncompatible 23 @GwtIncompatible // java.time.Duration 24 @ElementTypesAreNonnullByDefault 25 final class Internal { 26 27 /** 28 * Returns the number of nanoseconds of the given duration without throwing or overflowing. 29 * 30 * <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either 31 * {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing 32 * a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair. 33 */ 34 @SuppressWarnings({ 35 // We use this method only for cases in which we need to decompose to primitives. 36 "GoodTime-ApiWithNumericTimeUnit", 37 "GoodTime-DecomposeToPrimitive", 38 // We use this method only from within APIs that require a Duration. 39 "Java7ApiChecker", 40 }) 41 @IgnoreJRERequirement toNanosSaturated(Duration duration)42 static long toNanosSaturated(Duration duration) { 43 // Using a try/catch seems lazy, but the catch block will rarely get invoked (except for 44 // durations longer than approximately +/- 292 years). 45 try { 46 return duration.toNanos(); 47 } catch (ArithmeticException tooBig) { 48 return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE; 49 } 50 } 51 Internal()52 private Internal() {} 53 } 54