1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef rr_Routine_hpp 16 #define rr_Routine_hpp 17 18 #include <memory> 19 20 namespace rr { 21 22 class Routine 23 { 24 public: 25 Routine() = default; 26 virtual ~Routine() = default; 27 28 virtual const void *getEntry(int index = 0) const = 0; 29 }; 30 31 // RoutineT is a type-safe wrapper around a Routine and its function entry, returned by FunctionT 32 template<typename FunctionType> 33 class RoutineT; 34 35 template<typename Return, typename... Arguments> 36 class RoutineT<Return(Arguments...)> 37 { 38 public: 39 using FunctionType = Return (*)(Arguments...); 40 41 RoutineT() = default; 42 RoutineT(const std::shared_ptr<Routine> & routine)43 explicit RoutineT(const std::shared_ptr<Routine> &routine) 44 : routine(routine) 45 { 46 if(routine) 47 { 48 function = reinterpret_cast<FunctionType>(const_cast<void *>(routine->getEntry(0))); 49 } 50 } 51 operator bool() const52 operator bool() const 53 { 54 return function != nullptr; 55 } 56 57 template<typename... Args> operator ()(Args &&...args) const58 Return operator()(Args &&...args) const 59 { 60 return function(std::forward<Args>(args)...); 61 } 62 getEntry() const63 const FunctionType getEntry() const 64 { 65 return function; 66 } 67 68 private: 69 std::shared_ptr<Routine> routine; 70 FunctionType function = nullptr; 71 }; 72 73 } // namespace rr 74 75 #endif // rr_Routine_hpp 76