1 /*
2 * Copyright (C) 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 <algorithm>
20
21 #include "common/libs/utils/result.h"
22
23 namespace cuttlefish {
24
25 /**
26 * return all the elements in container that satisfies predicate.
27 *
28 * Container could be mostly any type, and Set should be any sort of set.
29 */
30 template <typename T, typename Set, typename Container>
Collect(const Container & container,std::function<bool (const T &)> predicate)31 Set Collect(const Container& container,
32 std::function<bool(const T&)> predicate) {
33 Set output;
34 std::copy_if(container.cbegin(), container.cend(),
35 std::inserter(output, output.end()), predicate);
36 return output;
37 }
38
39 /**
40 * Collect all Ts from each container inside the "Containers"
41 *
42 * Containers are a set/list of Container. Container can be viewed as a set/list
43 * of Ts.
44 *
45 */
46 template <typename T, typename Set, typename Containers>
Flatten(const Containers & containers)47 Set Flatten(const Containers& containers) {
48 Set output;
49 for (const auto& container : containers) {
50 output.insert(container.cbegin(), container.cend());
51 }
52 return output;
53 }
54
55 template <typename S>
AtMostN(S && s,const size_t n)56 Result<typename std::remove_reference<S>::type> AtMostN(S&& s, const size_t n) {
57 CF_EXPECT(s.size() <= n);
58 return {std::forward<S>(s)};
59 }
60
61 } // namespace cuttlefish
62