|
| 1 | +/* |
| 2 | + * Copyright 2024 The gRPC 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.grpc.internal; |
| 18 | + |
| 19 | +import static com.google.common.math.LongMath.saturatedAdd; |
| 20 | + |
| 21 | +import java.lang.reflect.InvocationTargetException; |
| 22 | +import java.lang.reflect.Method; |
| 23 | +import java.util.concurrent.TimeUnit; |
| 24 | + |
| 25 | +/** |
| 26 | + * {@link InstantTimeProvider} resolves InstantTimeProvider which implements {@link TimeProvider}. |
| 27 | + */ |
| 28 | +final class InstantTimeProvider implements TimeProvider { |
| 29 | + private Method now; |
| 30 | + private Method getNano; |
| 31 | + private Method getEpochSecond; |
| 32 | + |
| 33 | + public InstantTimeProvider(Class<?> instantClass) { |
| 34 | + try { |
| 35 | + this.now = instantClass.getMethod("now"); |
| 36 | + this.getNano = instantClass.getMethod("getNano"); |
| 37 | + this.getEpochSecond = instantClass.getMethod("getEpochSecond"); |
| 38 | + } catch (NoSuchMethodException ex) { |
| 39 | + throw new AssertionError(ex); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public long currentTimeNanos() { |
| 45 | + try { |
| 46 | + Object instant = now.invoke(null); |
| 47 | + int nanos = (int) getNano.invoke(instant); |
| 48 | + long epochSeconds = (long) getEpochSecond.invoke(instant); |
| 49 | + return saturatedAdd(TimeUnit.SECONDS.toNanos(epochSeconds), nanos); |
| 50 | + } catch (IllegalAccessException | InvocationTargetException ex) { |
| 51 | + throw new RuntimeException(ex); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments