1/*
2 * Copyright (C) 2016 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 <hidl/HidlTransportUtils.h>
18
19#include <android/hidl/base/1.0/IBase.h>
20
21namespace android {
22namespace hardware {
23namespace details {
24
25using ::android::hidl::base::V1_0::IBase;
26
27Return<bool> canCastInterface(IBase* interface, const char* castTo, bool emitError) {
28    if (interface == nullptr) {
29        return false;
30    }
31
32    // b/68217907
33    // Every HIDL interface is a base interface.
34    if (std::string(IBase::descriptor) == castTo) {
35        return true;
36    }
37
38    bool canCast = false;
39    auto chainRet = interface->interfaceChain([&](const hidl_vec<hidl_string> &types) {
40        for (size_t i = 0; i < types.size(); i++) {
41            if (types[i] == castTo) {
42                canCast = true;
43                break;
44            }
45        }
46    });
47
48    if (!chainRet.isOk()) {
49        // call fails, propagate the error if emitError
50        return emitError
51                ? details::StatusOf<void, bool>(chainRet)
52                : Return<bool>(false);
53    }
54
55    return canCast;
56}
57
58std::string getDescriptor(IBase* interface) {
59    std::string myDescriptor{};
60    auto ret = interface->interfaceDescriptor([&](const hidl_string &types) {
61        myDescriptor = types.c_str();
62    });
63    ret.isOk(); // ignored, return empty string if not isOk()
64    return myDescriptor;
65}
66
67}  // namespace details
68}  // namespace hardware
69}  // namespace android
70