Home | History | Annotate | Download | only in all-versions
      1 /*
      2  * Copyright (C) 2018 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_audio_common_VersionUtils_H_
     18 #define android_hardware_audio_common_VersionUtils_H_
     19 
     20 #include <hidl/HidlSupport.h>
     21 #include <type_traits>
     22 
     23 namespace android {
     24 namespace hardware {
     25 namespace audio {
     26 namespace common {
     27 namespace utils {
     28 
     29 /** Similar to static_cast but also casts to hidl_bitfield depending on
     30  * return type inference (emulated through user-define conversion).
     31  */
     32 template <class Source, class Destination = Source>
     33 class EnumConverter {
     34    public:
     35     static_assert(std::is_enum<Source>::value || std::is_enum<Destination>::value,
     36                   "Source or destination should be an enum");
     37 
     38     explicit EnumConverter(Source source) : mSource(source) {}
     39 
     40     operator Destination() const { return static_cast<Destination>(mSource); }
     41 
     42     template <class = std::enable_if_t<std::is_enum<Destination>::value>>
     43     operator ::android::hardware::hidl_bitfield<Destination>() {
     44         return static_cast<std::underlying_type_t<Destination>>(mSource);
     45     }
     46 
     47    private:
     48     const Source mSource;
     49 };
     50 template <class Destination, class Source>
     51 auto mkEnumConverter(Source source) {
     52     return EnumConverter<Source, Destination>{source};
     53 }
     54 
     55 /** Allows converting an enum to its bitfield or itself. */
     56 template <class Enum>
     57 EnumConverter<Enum> mkBitfield(Enum value) {
     58     return EnumConverter<Enum>{value};
     59 }
     60 
     61 }  // namespace utils
     62 }  // namespace common
     63 }  // namespace audio
     64 }  // namespace hardware
     65 }  // namespace android
     66 
     67 #endif  // android_hardware_audio_common_VersionUtils_H_
     68