blob: f5dad2c406b22444dbc58a172a390e0ccabcfae5 [file] [log] [blame]
Nicolas Capens0bac2852016-05-07 06:09:58 -04001// 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
Nicolas Capens48461502018-08-06 14:20:45 -040015#ifndef rr_Routine_hpp
16#define rr_Routine_hpp
Nicolas Capens0bac2852016-05-07 06:09:58 -040017
Antonio Maiorano62f49b22019-10-29 09:27:58 -040018#include <memory>
19
Nicolas Capens48461502018-08-06 14:20:45 -040020namespace rr
Nicolas Capens0bac2852016-05-07 06:09:58 -040021{
Nicolas Capens0bac2852016-05-07 06:09:58 -040022 class Routine
23 {
Nicolas Capens0bac2852016-05-07 06:09:58 -040024 public:
Ben Clayton6897e9b2019-07-16 17:27:27 +010025 Routine() = default;
26 virtual ~Routine() = default;
Nicolas Capens0bac2852016-05-07 06:09:58 -040027
Ben Clayton1c82c7b2019-04-30 12:49:27 +010028 virtual const void *getEntry(int index = 0) = 0;
Nicolas Capens0bac2852016-05-07 06:09:58 -040029 };
Antonio Maiorano62f49b22019-10-29 09:27:58 -040030
31 // RoutineT is a type-safe wrapper around a Routine and its callable 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 RoutineT() = default;
40
41 explicit RoutineT(const std::shared_ptr<Routine>& routine)
42 : routine(routine)
43 {
44 if (routine)
45 {
46 callable = reinterpret_cast<CallableType>(const_cast<void*>(routine->getEntry(0)));
47 }
48 }
49
50 operator bool() const
51 {
52 return callable != nullptr;
53 }
54
55 template <typename... Args>
56 Return operator()(Args&&... args) const
57 {
58 return callable(std::forward<Args>(args)...);
59 }
60
61 const void* getEntry() const
62 {
63 return reinterpret_cast<void*>(callable);
64 }
65
66 private:
67 std::shared_ptr<Routine> routine;
68 using CallableType = Return(*)(Arguments...);
69 CallableType callable = nullptr;
70 };
Nicolas Capens0bac2852016-05-07 06:09:58 -040071}
72
Nicolas Capens48461502018-08-06 14:20:45 -040073#endif // rr_Routine_hpp