1 /* 2 * Copyright (C) 2018 The Android Open Source Project 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 com.google.android.setupcompat.internal; 18 19 import androidx.annotation.VisibleForTesting; 20 import java.util.concurrent.TimeUnit; 21 22 /** Provider for time in nanos and millis. Allows overriding time during tests. */ 23 public class ClockProvider { 24 timeInNanos()25 public static long timeInNanos() { 26 return ticker.read(); 27 } 28 timeInMillis()29 public static long timeInMillis() { 30 return TimeUnit.NANOSECONDS.toMillis(timeInNanos()); 31 } 32 33 @VisibleForTesting resetInstance()34 public static void resetInstance() { 35 ticker = SYSTEM_TICKER; 36 } 37 38 @VisibleForTesting setInstance(Supplier<Long> nanoSecondSupplier)39 public static void setInstance(Supplier<Long> nanoSecondSupplier) { 40 ticker = () -> nanoSecondSupplier.get(); 41 } 42 read()43 public long read() { 44 return ticker.read(); 45 } 46 47 private static final Ticker SYSTEM_TICKER = () -> System.nanoTime(); 48 private static Ticker ticker = SYSTEM_TICKER; 49 50 @VisibleForTesting 51 public interface Supplier<T> { get()52 T get(); 53 } 54 } 55