blob: fc5182af61c1270d2aa7e134b7dc594d23895f69 [file] [log] [blame]
Winson62ac8b52019-12-04 08:36:48 -08001/*
2 * Copyright (C) 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#include "include/idmap2/PolicyUtils.h"
18
19#include <sstream>
20
21#include "android-base/strings.h"
22#include "idmap2/Policies.h"
23
24using android::idmap2::policy::kPolicyStringToFlag;
25
26namespace android::idmap2::utils {
27
28Result<PolicyBitmask> PoliciesToBitmaskResult(const std::vector<std::string>& policies) {
29 std::vector<std::string> unknown_policies;
30 PolicyBitmask bitmask = 0;
31 for (const std::string& policy : policies) {
32 const auto result = std::find_if(kPolicyStringToFlag.begin(), kPolicyStringToFlag.end(),
33 [policy](const auto& it) { return policy == it.first; });
34 if (result != kPolicyStringToFlag.end()) {
35 bitmask |= result->second;
36 } else {
37 unknown_policies.emplace_back(policy.empty() ? "empty" : policy);
38 }
39 }
40
41 if (unknown_policies.empty()) {
42 return Result<PolicyBitmask>(bitmask);
43 }
44
45 auto prefix = unknown_policies.size() == 1 ? "policy" : "policies";
46 return Error("unknown %s: \"%s\"", prefix, android::base::Join(unknown_policies, ",").c_str());
47}
48
49std::vector<std::string> BitmaskToPolicies(const PolicyBitmask& bitmask) {
50 std::vector<std::string> policies;
51
52 for (const auto& policy : kPolicyStringToFlag) {
53 if ((bitmask & policy.second) != 0) {
54 policies.emplace_back(policy.first.to_string());
55 }
56 }
57
58 return policies;
59}
60
61} // namespace android::idmap2::utils