1 // Copyright 2021 The Tint Authors 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 SRC_UTILS_TRANSFORM_H_ 16 #define SRC_UTILS_TRANSFORM_H_ 17 18 #include <algorithm> 19 #include <type_traits> 20 #include <utility> 21 #include <vector> 22 23 #include "src/traits.h" 24 25 namespace tint { 26 namespace utils { 27 28 /// Transform performs an element-wise transformation of a vector. 29 /// @param in the input vector. 30 /// @param transform the transformation function with signature: `OUT(IN)` 31 /// @returns a new vector with each element of the source vector transformed by 32 /// `transform`. 33 template <typename IN, typename TRANSFORMER> 34 auto Transform(const std::vector<IN>& in, TRANSFORMER&& transform) 35 -> std::vector<decltype(transform(in[0]))> { 36 std::vector<decltype(transform(in[0]))> result(in.size()); 37 for (size_t i = 0; i < result.size(); ++i) { 38 result[i] = transform(in[i]); 39 } 40 return result; 41 } 42 43 /// Transform performs an element-wise transformation of a vector. 44 /// @param in the input vector. 45 /// @param transform the transformation function with signature: 46 /// `OUT(IN, size_t)` 47 /// @returns a new vector with each element of the source vector transformed by 48 /// `transform`. 49 template <typename IN, typename TRANSFORMER> 50 auto Transform(const std::vector<IN>& in, TRANSFORMER&& transform) 51 -> std::vector<decltype(transform(in[0], 1u))> { 52 std::vector<decltype(transform(in[0], 1u))> result(in.size()); 53 for (size_t i = 0; i < result.size(); ++i) { 54 result[i] = transform(in[i], i); 55 } 56 return result; 57 } 58 59 } // namespace utils 60 } // namespace tint 61 62 #endif // SRC_UTILS_TRANSFORM_H_ 63