1/* 2 * Copyright (C) 2023 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 17import {Segment} from 'app/components/timeline/segment'; 18import {TimeRange, Timestamp} from 'common/time'; 19import {ComponentTimestampConverter} from 'common/timestamp_converter'; 20 21export class Transformer { 22 private fromWidth: bigint; 23 private targetWidth: number; 24 25 private fromOffset: bigint; 26 private toOffset: number; 27 28 constructor( 29 private fromRange: TimeRange, 30 private toRange: Segment, 31 private timestampConverter: ComponentTimestampConverter, 32 ) { 33 this.fromWidth = 34 this.fromRange.to.getValueNs() - this.fromRange.from.getValueNs(); 35 // Needs to be a whole number to be compatible with bigints 36 this.targetWidth = Math.round(this.toRange.to - this.toRange.from); 37 38 this.fromOffset = this.fromRange.from.getValueNs(); 39 // Needs to be a whole number to be compatible with bigints 40 this.toOffset = this.toRange.from; 41 } 42 43 transform(x: Timestamp): number { 44 return ( 45 this.toOffset + 46 (this.targetWidth * Number(x.getValueNs() - this.fromOffset)) / 47 Number(this.fromWidth) 48 ); 49 } 50 51 untransform(x: number): Timestamp { 52 x = Math.round(x); 53 const valueNs = 54 this.fromOffset + 55 (BigInt(x - this.toOffset) * this.fromWidth) / BigInt(this.targetWidth); 56 return this.timestampConverter.makeTimestampFromNs(valueNs); 57 } 58} 59