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 {Trace, TraceEntry} from './trace';
18import {TracePosition} from './trace_position';
19import {TraceTypeUtils} from './trace_type';
20
21export class TraceEntryFinder {
22  static findCorrespondingEntry<T>(
23    trace: Trace<T>,
24    position: TracePosition,
25  ): TraceEntry<T> | undefined {
26    if (trace.lengthEntries === 0) {
27      return undefined;
28    }
29
30    if (trace.isDumpWithoutTimestamp()) {
31      // always display dumps regardless of the current trace position
32      return trace.getEntry(0);
33    }
34
35    if (position.entry?.getFullTrace() === trace.getEntry(0).getFullTrace()) {
36      return position.entry as TraceEntry<T>;
37    }
38
39    if (position.frame !== undefined && trace.hasFrameInfo()) {
40      const frame = trace.getFrame(position.frame);
41      if (frame.lengthEntries > 0) {
42        return frame.getEntry(0);
43      }
44    }
45
46    if (position.entry) {
47      const entryTraceType = position.entry.getFullTrace().type;
48      const timestamp = position.entry.getTimestamp();
49      if (TraceTypeUtils.compareByUiPipelineOrder(entryTraceType, trace.type)) {
50        return (
51          trace.findFirstGreaterEntry(timestamp) ??
52          trace.findFirstGreaterOrEqualEntry(timestamp)
53        );
54      } else {
55        return (
56          trace.findLastLowerEntry(timestamp) ??
57          trace.findLastLowerOrEqualEntry(timestamp)
58        );
59      }
60    }
61
62    return trace.findLastLowerOrEqualEntry(position.timestamp);
63  }
64}
65