Winson | 62ac8b5 | 2019-12-04 08:36:48 -0800 | [diff] [blame] | 1 | /* |
| 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> |
MÃ¥rten Kongstad | c4799eb | 2020-06-04 20:48:11 +0200 | [diff] [blame^] | 20 | #include <string> |
| 21 | #include <vector> |
Winson | 62ac8b5 | 2019-12-04 08:36:48 -0800 | [diff] [blame] | 22 | |
| 23 | #include "android-base/strings.h" |
| 24 | #include "idmap2/Policies.h" |
| 25 | |
| 26 | using android::idmap2::policy::kPolicyStringToFlag; |
| 27 | |
| 28 | namespace android::idmap2::utils { |
| 29 | |
| 30 | Result<PolicyBitmask> PoliciesToBitmaskResult(const std::vector<std::string>& policies) { |
| 31 | std::vector<std::string> unknown_policies; |
| 32 | PolicyBitmask bitmask = 0; |
| 33 | for (const std::string& policy : policies) { |
| 34 | const auto result = std::find_if(kPolicyStringToFlag.begin(), kPolicyStringToFlag.end(), |
| 35 | [policy](const auto& it) { return policy == it.first; }); |
| 36 | if (result != kPolicyStringToFlag.end()) { |
| 37 | bitmask |= result->second; |
| 38 | } else { |
| 39 | unknown_policies.emplace_back(policy.empty() ? "empty" : policy); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | if (unknown_policies.empty()) { |
| 44 | return Result<PolicyBitmask>(bitmask); |
| 45 | } |
| 46 | |
| 47 | auto prefix = unknown_policies.size() == 1 ? "policy" : "policies"; |
| 48 | return Error("unknown %s: \"%s\"", prefix, android::base::Join(unknown_policies, ",").c_str()); |
| 49 | } |
| 50 | |
| 51 | std::vector<std::string> BitmaskToPolicies(const PolicyBitmask& bitmask) { |
| 52 | std::vector<std::string> policies; |
| 53 | |
| 54 | for (const auto& policy : kPolicyStringToFlag) { |
| 55 | if ((bitmask & policy.second) != 0) { |
| 56 | policies.emplace_back(policy.first.to_string()); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return policies; |
| 61 | } |
| 62 | |
| 63 | } // namespace android::idmap2::utils |