blob: 0061c53e62d89d80d9beed443309f6946463f6c6 [file] [log] [blame]
Vishnu Nairdc4d31b2022-11-17 03:20:58 +00001/*
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
21namespace 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.
25template <typename T>
Vishnu Naira9c43762023-01-27 19:10:25 +000026bool swapErase(std::vector<T>& vec, const T& value) {
27 bool found = false;
Vishnu Nairdc4d31b2022-11-17 03:20:58 +000028 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);
Vishnu Naira9c43762023-01-27 19:10:25 +000032 found = true;
Vishnu Nairdc4d31b2022-11-17 03:20:58 +000033 }
Vishnu Naira9c43762023-01-27 19:10:25 +000034 return found;
Vishnu Nairdc4d31b2022-11-17 03:20:58 +000035}
36
37// Similar to swapErase(std::vector<T>& vec, const T& value) but erases the first element
38// that returns true for predicate.
39template <typename T, class P>
40void 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