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 #ifndef ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_1_1_UTILS_H
18 #define ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_1_1_UTILS_H
19 
20 #include "nnapi/hal/1.1/Conversions.h"
21 
22 #include <android-base/logging.h>
23 #include <android/hardware/neuralnetworks/1.1/types.h>
24 #include <nnapi/Result.h>
25 #include <nnapi/TypeUtils.h>
26 #include <nnapi/Types.h>
27 #include <nnapi/Validation.h>
28 #include <nnapi/hal/1.0/Conversions.h>
29 #include <nnapi/hal/HandleError.h>
30 
31 namespace android::hardware::neuralnetworks::V1_1::utils {
32 
33 constexpr auto kDefaultExecutionPreference = ExecutionPreference::FAST_SINGLE_ANSWER;
34 constexpr auto kVersion = nn::Version::ANDROID_P;
35 
36 template <typename Type>
validate(const Type & halObject)37 nn::Result<void> validate(const Type& halObject) {
38     const auto maybeCanonical = nn::convert(halObject);
39     if (!maybeCanonical.has_value()) {
40         return nn::error() << maybeCanonical.error().message;
41     }
42     return {};
43 }
44 
45 template <typename Type>
valid(const Type & halObject)46 bool valid(const Type& halObject) {
47     const auto result = utils::validate(halObject);
48     if (!result.has_value()) {
49         LOG(ERROR) << result.error();
50     }
51     return result.has_value();
52 }
53 
54 template <typename Type>
compliantVersion(const Type & canonical)55 nn::GeneralResult<void> compliantVersion(const Type& canonical) {
56     const auto version = NN_TRY(hal::utils::makeGeneralFailure(nn::validate(canonical)));
57     if (version > kVersion) {
58         return NN_ERROR() << "Insufficient version: " << version << " vs required " << kVersion;
59     }
60     return {};
61 }
62 
63 template <typename Type>
64 auto convertFromNonCanonical(const Type& nonCanonicalObject)
65         -> decltype(convert(nn::convert(nonCanonicalObject).value())) {
66     return convert(NN_TRY(nn::convert(nonCanonicalObject)));
67 }
68 
69 }  // namespace android::hardware::neuralnetworks::V1_1::utils
70 
71 #endif  // ANDROID_HARDWARE_INTERFACES_NEURALNETWORKS_1_1_UTILS_H
72