|
| 1 | +/// @file common/proto_utils.hpp |
| 2 | +/// |
| 3 | +/// @brief Utils that require generated proto includes. These should be #included |
| 4 | +/// in cpp implementation files, but not in wrapper headers consumed by third party code. |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include <viam/api/common/v1/common.pb.h> |
| 8 | + |
| 9 | +namespace viam { |
| 10 | +namespace sdk { |
| 11 | + |
| 12 | +/// @brief Copies elements from a protobuf repeated pointer array into a std::vector. Src type |
| 13 | +/// must be implicitly convertible to Dst (probably via operator on Src). |
| 14 | +template <typename Src, typename Dst> |
| 15 | +void vecToRepeatedPtr(const std::vector<Src>& vec, google::protobuf::RepeatedPtrField<Dst>& dest) { |
| 16 | + dest.Reserve(vec.size()); |
| 17 | + for (auto& x : vec) { |
| 18 | + *dest.Add() = x.to_proto(); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/// @brief Non-member to_proto() version. (necessary for moving generated types out of wrapper headers). |
| 23 | +/// Template param F is a function that converts from Src to Dst. |
| 24 | +template <typename Src, typename Dst> |
| 25 | +void vecToRepeatedPtr(const std::vector<Src>& vec, google::protobuf::RepeatedPtrField<Dst>& dest, Dst& from_proto(const Src&)) { |
| 26 | + dest.Reserve(vec.size()); |
| 27 | + for (auto& x : vec) { |
| 28 | + *dest.Add() = from_proto(x); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/// @brief Copies elements from a std::vector into a protobuf repeated pointer array. Src type |
| 33 | +/// must be implicitly convertible to Dst (probably via constructor on Dst). |
| 34 | +template <typename Src, typename Dst> |
| 35 | +void repeatedPtrToVec(const google::protobuf::RepeatedPtrField<Src>& src, std::vector<Dst>& vec) { |
| 36 | + vec.reserve(src.size()); |
| 37 | + for (auto& x : src) { |
| 38 | + vec.push_back(Dst::from_proto(x)); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/// @brief Non-member to_proto() version. (necessary for moving generated types out of wrapper headers). |
| 43 | +/// Template param F is a function that converts from Src to Dst. |
| 44 | +template <typename Src, typename Dst> |
| 45 | +void repeatedPtrToVec(const google::protobuf::RepeatedPtrField<Src>& src, std::vector<Dst>& vec, Dst& to_proto(const Src&)) { |
| 46 | + vec.reserve(src.size()); |
| 47 | + for (auto& x : src) { |
| 48 | + vec.push_back(to_proto(x)); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +} // namespace sdk |
| 53 | +} // namespace viam |
0 commit comments