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 
17 package com.android.car.audio;
18 
19 import android.util.ArraySet;
20 
21 import com.android.internal.annotations.GuardedBy;
22 import com.android.internal.annotations.VisibleForTesting;
23 
24 final class RequestIdGenerator {
25 
26     private final Object mLock = new Object();
27 
28     private final long mMaxRequests;
29     @GuardedBy("mLock")
30     private final ArraySet<Long> mUsedRequestIds = new ArraySet<>();
31     @GuardedBy("mLock")
32     private long mRequestIdCounter;
33 
RequestIdGenerator()34     RequestIdGenerator() {
35         this(Long.MAX_VALUE);
36     }
37 
38     @VisibleForTesting
RequestIdGenerator(long maxRequests)39     RequestIdGenerator(long maxRequests) {
40         mMaxRequests = maxRequests;
41     }
42 
generateUniqueRequestId()43     long generateUniqueRequestId() {
44         synchronized (mLock) {
45             while (mRequestIdCounter < mMaxRequests) {
46                 if (mUsedRequestIds.contains(mRequestIdCounter)) {
47                     mRequestIdCounter++;
48                     continue;
49                 }
50 
51                 mUsedRequestIds.add(mRequestIdCounter);
52                 return mRequestIdCounter;
53             }
54 
55             mRequestIdCounter = 0;
56         }
57 
58         throw new IllegalStateException("Could not generate request id");
59     }
60 
releaseRequestId(long requestId)61     void releaseRequestId(long requestId) {
62         synchronized (mLock) {
63             mUsedRequestIds.remove(requestId);
64             // Reset counter back to lower value,
65             // on request the search will automatically assign this value or a newer one.
66             if (mRequestIdCounter > requestId) {
67                 mRequestIdCounter = requestId;
68             }
69         }
70     }
71 }
72