1 /*
2  * Copyright (C) 2024 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.android.app.tracing
18 
19 import androidx.tracing.Trace
20 import java.util.concurrent.ThreadLocalRandom
21 
22 @PublishedApi
isEnablednull23 internal actual fun isEnabled(): Boolean {
24     return Trace.isEnabled()
25 }
26 
traceCounternull27 internal actual fun traceCounter(counterName: String, counterValue: Int) {
28     Trace.setCounter(counterName, counterValue)
29 }
30 
traceBeginnull31 internal actual fun traceBegin(methodName: String) {
32     Trace.beginSection(methodName)
33 }
34 
traceEndnull35 internal actual fun traceEnd() {
36     Trace.endSection()
37 }
38 
asyncTraceBeginnull39 internal actual fun asyncTraceBegin(methodName: String, cookie: Int) {
40     Trace.beginAsyncSection(methodName, cookie)
41 }
42 
asyncTraceEndnull43 internal actual fun asyncTraceEnd(methodName: String, cookie: Int) {
44     Trace.endAsyncSection(methodName, cookie)
45 }
46 
namedSlicenull47 private fun namedSlice(trackName: String, methodName: String) = "$trackName:$methodName"
48 
49 @PublishedApi
50 internal actual fun asyncTraceForTrackBegin(trackName: String, methodName: String, cookie: Int) {
51     if (isEnabled()) {
52         asyncTraceBegin(namedSlice(trackName, methodName), cookie)
53     }
54 }
55 
56 @PublishedApi
asyncTraceForTrackEndnull57 internal actual fun asyncTraceForTrackEnd(trackName: String, methodName: String, cookie: Int) {
58     if (isEnabled()) {
59         asyncTraceEnd(namedSlice(trackName, methodName), cookie)
60     }
61 }
62 
instantnull63 internal actual fun instant(eventName: String) {
64     if (isEnabled()) {
65         traceBegin("instant:$eventName")
66         traceEnd()
67     }
68 }
69 
instantForTracknull70 internal actual fun instantForTrack(trackName: String, eventName: String) {
71     if (Trace.isEnabled()) {
72         val cookie = ThreadLocalRandom.current().nextInt()
73         val name = "instant:${namedSlice(trackName,eventName)}"
74         asyncTraceBegin(name, cookie)
75         asyncTraceEnd(name, cookie)
76     }
77 }
78