blob: e7c69a8094d7ba4071cbc3d4b451690f6da7fc76 [file] [log] [blame]
Marin Shalamanov0f10d0d2020-08-06 20:04:06 +02001/*
2 * Copyright 2020 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#pragma once
18
19#include <ui/DisplayId.h>
20
21#include <limits>
22#include <optional>
23#include <random>
24#include <unordered_set>
25
26#include <log/log.h>
27
28namespace android {
29
30template <typename T>
31class DisplayIdGenerator {
32public:
33 virtual std::optional<T> nextId() = 0;
34 virtual void markUnused(T id) = 0;
35
36protected:
37 ~DisplayIdGenerator() {}
38};
39
40template <typename T>
41class RandomDisplayIdGenerator final : public DisplayIdGenerator<T> {
42public:
43 explicit RandomDisplayIdGenerator(size_t maxIdsCount = std::numeric_limits<size_t>::max())
44 : mMaxIdsCount(maxIdsCount) {}
45
46 std::optional<T> nextId() override {
47 if (mUsedIds.size() >= mMaxIdsCount) {
48 return std::nullopt;
49 }
50
51 constexpr int kMaxAttempts = 1000;
52
53 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
54 const auto baseId = mDistribution(mGenerator);
55 const T id(baseId);
56 if (mUsedIds.count(id) == 0) {
57 mUsedIds.insert(id);
58 return id;
59 }
60 }
61
62 LOG_ALWAYS_FATAL("Couldn't generate ID after %d attempts", kMaxAttempts);
63 }
64
65 void markUnused(T id) override { mUsedIds.erase(id); }
66
67private:
68 const size_t mMaxIdsCount;
69
70 std::unordered_set<T> mUsedIds;
71 std::default_random_engine mGenerator{std::random_device()()};
72 std::uniform_int_distribution<typename T::BaseId> mDistribution;
73};
74
75} // namespace android