Home | History | Annotate | Download | only in internal
      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.implcore.internal;
     18 
     19 import io.opencensus.common.Clock;
     20 import io.opencensus.common.Timestamp;
     21 import javax.annotation.concurrent.Immutable;
     22 
     23 /**
     24  * This class provides a mechanism for converting {@link System#nanoTime() nanoTime} values to
     25  * {@link Timestamp}.
     26  */
     27 @Immutable
     28 public final class TimestampConverter {
     29   private final Timestamp timestamp;
     30   private final long nanoTime;
     31 
     32   // Returns a WallTimeConverter initialized to now.
     33   public static TimestampConverter now(Clock clock) {
     34     return new TimestampConverter(clock.now(), clock.nowNanos());
     35   }
     36 
     37   /**
     38    * Converts a {@link System#nanoTime() nanoTime} value to {@link Timestamp}.
     39    *
     40    * @param nanoTime value to convert.
     41    * @return the {@code Timestamp} representation of the {@code time}.
     42    */
     43   public Timestamp convertNanoTime(long nanoTime) {
     44     return timestamp.addNanos(nanoTime - this.nanoTime);
     45   }
     46 
     47   private TimestampConverter(Timestamp timestamp, long nanoTime) {
     48     this.timestamp = timestamp;
     49     this.nanoTime = nanoTime;
     50   }
     51 }
     52