1/* 2 * Copyright (C) 2022 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 17export enum TimestampType { 18 ELAPSED = 'ELAPSED', 19 REAL = 'REAL', 20} 21 22export class Timestamp { 23 private readonly type: TimestampType; 24 private readonly valueNs: bigint; 25 26 constructor(type: TimestampType, valueNs: bigint) { 27 this.type = type; 28 this.valueNs = valueNs; 29 } 30 31 static from( 32 timestampType: TimestampType, 33 elapsedTimestamp: bigint, 34 realToElapsedTimeOffsetNs: bigint | undefined = undefined 35 ) { 36 switch (timestampType) { 37 case TimestampType.REAL: 38 if (realToElapsedTimeOffsetNs === undefined) { 39 throw new Error("realToElapsedTimeOffsetNs can't be undefined to use real timestamp"); 40 } 41 return new Timestamp(TimestampType.REAL, elapsedTimestamp + realToElapsedTimeOffsetNs); 42 case TimestampType.ELAPSED: 43 return new Timestamp(TimestampType.ELAPSED, elapsedTimestamp); 44 default: 45 throw new Error('Unhandled timestamp type'); 46 } 47 } 48 49 getType(): TimestampType { 50 return this.type; 51 } 52 53 getValueNs(): bigint { 54 return this.valueNs; 55 } 56 57 valueOf(): bigint { 58 return this.getValueNs(); 59 } 60 61 add(nanoseconds: bigint): Timestamp { 62 return new Timestamp(this.type, this.valueNs + nanoseconds); 63 } 64} 65 66export class RealTimestamp extends Timestamp { 67 constructor(valueNs: bigint) { 68 super(TimestampType.REAL, valueNs); 69 } 70} 71 72export class ElapsedTimestamp extends Timestamp { 73 constructor(valueNs: bigint) { 74 super(TimestampType.ELAPSED, valueNs); 75 } 76} 77