synapse-app-sdk
C++ SDK for Synapse Apps
Loading...
Searching...
No Matches
conversions.hpp
1#pragma once
2
3#include <optional>
4
5#include "api/datatype.pb.h"
6
7#include "zmq.h"
8
9namespace synapse {
10
18template <typename T>
19std::optional<T> parse_protobuf_message(zmq::message_t message) {
20 static_assert(std::is_base_of<google::protobuf::Message, T>::value,
21 "T must be a protobuf message type");
22 if (message.size() == 0) {
23 return std::nullopt;
24 }
25 // TODO: We should probably pass a reference here instead of copying
26 T output;
27
28 // Parse the protobuf message from the ZMQ message data
29 bool success = output.ParseFromArray(message.data(), static_cast<int>(message.size()));
30
31 if (!success) {
32 // Failed to parse the message
33 return std::nullopt;
34 }
35 return output;
36}
37
46template <typename T>
47zmq::message_t protobuf_to_zmq_message(const T& message) {
48 static_assert(std::is_base_of<google::protobuf::Message, T>::value,
49 "T must be a protobuf message type");
50 const size_t message_size = message.ByteSizeLong();
51 zmq::message_t out_message(message_size);
52 if (!message.SerializeToArray(out_message.data(), message_size)) {
53 return zmq::message_t(0);
54 }
55 return out_message;
56}
57
66template <typename T>
67std::string pack_tensor_data(const std::vector<T>& data) {
68 static_assert(std::is_arithmetic_v<T>, "Only arithmetic types are supported");
69
70 if (data.empty()) {
71 return "";
72 }
73 std::string result;
74 result.resize(data.size() * sizeof(T));
75 std::memcpy(result.data(), data.data(), result.size());
76 return result;
77}
78
87template <typename T>
88std::string pack_tensor_data(std::initializer_list<T> data) {
89 return pack_tensor_data(std::vector<T>(data));
90}
91
92} // namespace synapse