blob: 2c12f0e26d9d8eaf5740eeae52fdaf2544a50b59 [file] [log] [blame]
Fan Xuffde7862018-11-08 16:29:13 -08001/*
2 * Copyright (C) 2018 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
Fan Xu1c16df52018-11-19 16:27:27 -080017#include <bufferhub/BufferHubIdGenerator.h>
Fan Xu6b4b1e52018-12-18 14:03:44 -080018#include <log/log.h>
Fan Xuffde7862018-11-08 16:29:13 -080019
20namespace android {
21namespace frameworks {
22namespace bufferhub {
23namespace V1_0 {
24namespace implementation {
25
Fan Xu1c16df52018-11-19 16:27:27 -080026BufferHubIdGenerator& BufferHubIdGenerator::getInstance() {
27 static BufferHubIdGenerator generator;
28
29 return generator;
30}
31
Fan Xu6b4b1e52018-12-18 14:03:44 -080032int BufferHubIdGenerator::getId() {
Fan Xuffde7862018-11-08 16:29:13 -080033 std::lock_guard<std::mutex> lock(mIdsInUseMutex);
34
35 do {
Fan Xu6b4b1e52018-12-18 14:03:44 -080036 if (++mLastId >= std::numeric_limits<int>::max()) {
37 mLastId = 0;
Fan Xuffde7862018-11-08 16:29:13 -080038 }
39 } while (mIdsInUse.find(mLastId) != mIdsInUse.end());
40
41 mIdsInUse.insert(mLastId);
42 return mLastId;
43}
44
Fan Xu6b4b1e52018-12-18 14:03:44 -080045void BufferHubIdGenerator::freeId(int id) {
Fan Xuffde7862018-11-08 16:29:13 -080046 std::lock_guard<std::mutex> lock(mIdsInUseMutex);
47 auto iter = mIdsInUse.find(id);
48 if (iter != mIdsInUse.end()) {
49 mIdsInUse.erase(iter);
Fan Xu6b4b1e52018-12-18 14:03:44 -080050 } else {
51 ALOGW("%s: Cannot free nonexistent id #%d", __FUNCTION__, id);
Fan Xuffde7862018-11-08 16:29:13 -080052 }
Fan Xuffde7862018-11-08 16:29:13 -080053}
54
55} // namespace implementation
56} // namespace V1_0
57} // namespace bufferhub
58} // namespace frameworks
59} // namespace android