1 /*
2 * Copyright 2022 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 <vector>
20
21 namespace android::surfaceflinger::frontend {
22 // Erases the first element in vec that matches value. This is a more optimal way to
23 // remove an element from a vector that avoids relocating all the elements after the one
24 // that is erased.
25 template <typename T>
swapErase(std::vector<T> & vec,const T & value)26 bool swapErase(std::vector<T>& vec, const T& value) {
27 bool found = false;
28 auto it = std::find(vec.begin(), vec.end(), value);
29 if (it != vec.end()) {
30 std::iter_swap(it, vec.end() - 1);
31 vec.erase(vec.end() - 1);
32 found = true;
33 }
34 return found;
35 }
36
37 // Similar to swapErase(std::vector<T>& vec, const T& value) but erases the first element
38 // that returns true for predicate.
39 template <typename T, class P>
swapErase(std::vector<T> & vec,P predicate)40 void swapErase(std::vector<T>& vec, P predicate) {
41 auto it = std::find_if(vec.begin(), vec.end(), predicate);
42 if (it != vec.end()) {
43 std::iter_swap(it, vec.end() - 1);
44 vec.erase(vec.end() - 1);
45 }
46 }
47
48 } // namespace android::surfaceflinger::frontend
49