HidlTransportSupport.h revision 12f04d913dae2fb287089f6db24f144731c79d9c
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#ifndef ANDROID_HIDL_TRANSPORT_SUPPORT_H
18#define ANDROID_HIDL_TRANSPORT_SUPPORT_H
19
20#include <hidl/HidlBinderSupport.h>
21#include <hidl/HidlSupport.h>
22#include <hidl/HidlTransportUtils.h>
23
24namespace android {
25namespace hardware {
26
27// cast the interface IParent to IChild.
28// Return nullptr if parent is null or any failure.
29template<typename IChild, typename IParent, typename BpChild, typename BpParent>
30sp<IChild> castInterface(sp<IParent> parent, const char *childIndicator) {
31    if (parent.get() == nullptr) {
32        // casts always succeed with nullptrs.
33        return nullptr;
34    }
35    bool canCast = canCastInterface(parent.get(), childIndicator);
36
37    if (!canCast) {
38        return sp<IChild>(nullptr); // cast failed.
39    }
40    // TODO b/32001926 Needs to be fixed for socket mode.
41    if (parent->isRemote()) {
42        // binderized mode. Got BpChild. grab the remote and wrap it.
43        return sp<IChild>(new BpChild(toBinder<IParent, BpParent>(parent)));
44    }
45    // Passthrough mode. Got BnChild and BsChild.
46    return sp<IChild>(static_cast<IChild *>(parent.get()));
47}
48
49}  // namespace hardware
50}  // namespace android
51
52
53#endif  // ANDROID_HIDL_TRANSPORT_SUPPORT_H
54