VLink  2.3.0
A high-performance communication middleware
serializer-inl.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 #pragma once
25 
26 #include <cstring>
27 #include <exception>
28 #include <limits>
29 #include <sstream>
30 #include <string>
31 #include <type_traits>
32 #include <utility>
33 
34 #include "../base/helpers.h"
35 #include "../base/logger.h"
36 #include "../base/name_detector.h"
37 #include "../base/traits.h"
38 #include "../serializer.h"
39 
40 #ifndef VLINK_DDS_IDL_PREFIX
41 #define VLINK_DDS_IDL_PREFIX "dds::"
42 #endif
43 
44 #if defined(VLINK_SUPPORT_CDR) || defined(VLINK_SUPPORT_ROS2)
45 #if __has_include(<fastcdr/Cdr.h>)
46 #include <fastcdr/Cdr.h>
47 #if FASTCDR_VERSION_MAJOR >= 2
48 #include <fastcdr/CdrSizeCalculator.hpp>
49 #endif
50 #ifndef VLINK_HAS_CDR
51 #define VLINK_HAS_CDR
52 #endif
53 #else
54 #warning "Fast CDR headers are required when CDR serialization support is enabled."
55 #endif
56 #endif
57 
58 #ifdef VLINK_SUPPORT_ROS2
59 #if defined(VLINK_HAS_CDR) && __has_include(<rosidl_typesupport_fastrtps_cpp/message_type_support.h>)
60 #include <rosidl_typesupport_fastrtps_cpp/message_type_support.h>
61 
62 #include <rosidl_runtime_cpp/traits.hpp>
63 #include <rosidl_typesupport_fastrtps_cpp/message_type_support_decl.hpp>
64 #ifndef VLINK_HAS_ROS2
65 #define VLINK_HAS_ROS2
66 #endif
67 #elif defined(VLINK_HAS_CDR)
68 #warning "ROS 2 message headers are required when ROS 2 message support is enabled."
69 #endif
70 #endif
71 
72 #if __has_include(<google/protobuf/message_lite.h>)
73 #ifndef VLINK_HAS_PROTOBUF
74 #define VLINK_HAS_PROTOBUF
75 #endif
76 #include <google/protobuf/message_lite.h>
77 #endif
78 
79 #if __has_include(<flatbuffers/flatbuffers.h>)
80 #ifndef VLINK_HAS_FLATBUFFERS
81 #define VLINK_HAS_FLATBUFFERS
82 #endif
83 #include <flatbuffers/flatbuffers.h>
84 #endif
85 
86 namespace vlink {
87 
88 namespace Serializer { // NOLINT(readability-identifier-naming)
89 
90 [[maybe_unused]] inline constexpr bool is_supported(Type type) noexcept { return type != kUnknownType; }
91 
92 #ifdef VLINK_HAS_ROS2
93 template <typename T>
94 inline constexpr bool is_ros2_msg_type() noexcept {
95  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
96  return rosidl_generator_traits::is_message<RealType>::value;
97 }
98 
99 template <typename T>
100 inline const message_type_support_callbacks_t* get_ros2_msg_callbacks() noexcept {
101  const auto* type_support = rosidl_typesupport_fastrtps_cpp::get_message_type_support_handle<T>();
102  return type_support ? static_cast<const message_type_support_callbacks_t*>(type_support->data) : nullptr;
103 }
104 #endif
105 
106 template <typename T>
107 inline constexpr Type get_type_of() noexcept {
108  if constexpr (Traits::IsSharedPtr<T>::value) {
109  if constexpr (!std::is_same_v<typename T::weak_type, std::weak_ptr<typename T::element_type>>) {
110  return kUnknownType;
111  }
112  }
113 
114  if constexpr (is_bytes_type<T>()) {
115  return kBytesType;
116  } else if constexpr (is_dynamic_type<T>()) {
117  return kDynamicType;
118  } else if constexpr (is_someip_type<T>()) {
119  return kSomeipType;
120 #ifdef VLINK_HAS_CDR
121  } else if constexpr (is_cdr_type<T>()) {
122  return kCdrType;
123 #endif
124 #ifdef VLINK_HAS_PROTOBUF
125  } else if constexpr (is_proto_type<T>()) {
126  return kProtoType;
127  } else if constexpr (is_proto_ptr_type<T>()) {
128  return kProtoPtrType;
129 #endif
130 #ifdef VLINK_HAS_FLATBUFFERS
131  } else if constexpr (is_flat_table_type<T>()) {
132  return kFlatTableType;
133  } else if constexpr (is_flat_ptr_type<T>()) {
134  return kFlatPtrType;
135  } else if constexpr (is_flat_builder_type<T>()) {
136  return kFlatBuilderType;
137 #endif
138  } else if constexpr (is_custom_type<T>()) {
139  return kCustomType;
140  } else if constexpr (is_string_type<T>()) {
141  return kStringType;
142  } else if constexpr (is_chars_type<T>()) {
143  return kCharsType;
144  } else if constexpr (is_standard_type<T>()) {
145  return kStandardType;
146  } else if constexpr (is_standard_ptr_type<T>()) {
147  return kStandardPtrType;
148  } else if constexpr (is_stream_type<T>()) {
149  return kStreamType;
150  } else {
151  return kUnknownType;
152  }
153 }
154 
155 template <Type TypeT, typename T>
156 inline static constexpr SchemaType get_schema_type() noexcept {
157  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
158 
159  if constexpr (TypeT == kBytesType) {
160  return SchemaType::kRaw;
161  } else if constexpr (TypeT == kCustomType) {
162  if constexpr (VLINK_HAS_MEMBER(RealType, kZerocopyTypes)) {
163  if constexpr (RealType::kZerocopyTypes) {
164  return SchemaType::kZeroCopy;
165  } else {
166  return SchemaType::kRaw;
167  }
168  } else if constexpr (VLINK_HAS_MEMBER(RealType, get_schema_type())) {
169  return RealType::get_schema_type();
170  } else {
171  return SchemaType::kRaw;
172  }
173 #ifdef VLINK_HAS_PROTOBUF
174  } else if constexpr (TypeT == kProtoType || TypeT == kProtoPtrType) {
175  return SchemaType::kProtobuf;
176 #endif
177 #ifdef VLINK_HAS_FLATBUFFERS
178  } else if constexpr (TypeT == kFlatTableType || TypeT == kFlatPtrType || TypeT == kFlatBuilderType) {
180 #endif
181 #ifdef VLINK_HAS_CDR
182  } else if constexpr (TypeT == kCdrType) {
183  return SchemaType::kCdr;
184 #endif
185  } else {
186  return SchemaType::kRaw;
187  }
188 }
189 
190 template <typename T>
191 inline static constexpr SchemaType get_schema_type() noexcept {
192  constexpr auto kType = get_type_of<T>();
193 
194  return get_schema_type<kType, T>();
195 }
196 
197 template <Type TypeT, typename T>
198 inline std::string get_serialized_type() noexcept {
199  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
200  using NamedType = std::remove_pointer_t<RealType>;
201 
202  if constexpr (TypeT == kBytesType) {
203  return "";
204  } else if constexpr (TypeT == kDynamicType) {
205  return "vlink::DynamicData";
206  } else if constexpr (TypeT == kCustomType && VLINK_HAS_MEMBER(RealType, get_serialized_type())) {
208 #ifdef VLINK_HAS_PROTOBUF
209  } else if constexpr (TypeT == kProtoType || TypeT == kProtoPtrType) {
210  return std::string(NamedType{}.GetTypeName());
211 #endif
212 #ifdef VLINK_HAS_FLATBUFFERS
213  } else if constexpr (TypeT == kFlatTableType) {
214  using TableType = typename RealType::TableType;
215  if constexpr (VLINK_HAS_MEMBER(TableType, GetFullyQualifiedName)) {
216  return TableType::GetFullyQualifiedName();
217  } else {
218  std::string name = NameDetector::get<TableType>().data();
219  Helpers::replace_string(name, "::", ".");
220  return name;
221  }
222  } else if constexpr (TypeT == kFlatBuilderType) {
223  using TableType = typename RealType::Table;
224  if constexpr (VLINK_HAS_MEMBER(TableType, GetFullyQualifiedName)) {
225  return TableType::GetFullyQualifiedName();
226  } else {
227  std::string name = NameDetector::get<TableType>().data();
228  Helpers::replace_string(name, "::", ".");
229  return name;
230  }
231  } else if constexpr (TypeT == kFlatPtrType) {
232  using TableType = std::remove_pointer_t<T>;
233  if constexpr (VLINK_HAS_MEMBER(TableType, GetFullyQualifiedName)) {
234  return TableType::GetFullyQualifiedName();
235  } else {
236  std::string name = NameDetector::get<TableType>().data();
237  Helpers::replace_string(name, "::", ".");
238  return name;
239  }
240 #endif
241 #ifdef VLINK_HAS_ROS2
242  } else if constexpr (TypeT == kCdrType && is_ros2_msg_type<RealType>()) {
243  const auto* callbacks = get_ros2_msg_callbacks<RealType>();
244 
245  if VUNLIKELY (!callbacks || !callbacks->message_namespace_ || !callbacks->message_name_) {
246  return "";
247  }
248 
249  std::string name(callbacks->message_namespace_);
250  name.append("::dds_::").append(callbacks->message_name_).append("_");
251 
252  return name;
253 #endif
254  } else if constexpr (TypeT == kStringType || TypeT == kCharsType) {
255  return "string";
256  } else if constexpr (NameDetector::is_support<NamedType>()) {
257  return NameDetector::get<NamedType>().data();
258  } else {
259  return "";
260  }
261 }
262 
263 template <typename T>
264 inline std::string get_serialized_type() noexcept {
265  constexpr auto kType = get_type_of<T>();
266 
267  return get_serialized_type<kType, T>();
268 }
269 
270 template <Type TypeT, typename T>
271 inline size_t get_serialized_size(const T& src) noexcept {
272  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
273 
274  if constexpr (Traits::IsSharedPtr<T>()) {
275  if VUNLIKELY (!src) {
276  return 0U;
277  }
278  }
279 
280  if constexpr (TypeT == kBytesType) {
281  return 0;
282  } else if constexpr (TypeT == kDynamicType) {
283  return 0;
284 #ifdef VLINK_HAS_CDR
285  } else if constexpr (TypeT == kCdrType) {
286  try {
287 #ifdef VLINK_HAS_ROS2
288  if constexpr (is_ros2_msg_type<RealType>()) {
289  const auto* callbacks = get_ros2_msg_callbacks<RealType>();
290 
291  if VUNLIKELY (!callbacks || !callbacks->get_serialized_size) {
292  return 0U;
293  }
294 
295  const size_t payload_size = callbacks->get_serialized_size(&deref(src));
296  return payload_size <= std::numeric_limits<uint32_t>::max() - 4U ? payload_size + 4U : 0U;
297  } else {
298 #endif
299  if constexpr (VLINK_HAS_MEMBER(RealType, getCdrSerializedSize(deref(src)))) {
300  const size_t payload_size = RealType::getCdrSerializedSize(deref(src));
301  return payload_size <= std::numeric_limits<uint32_t>::max() - 4U ? payload_size + 4U : 0U;
302 #if FASTCDR_VERSION_MAJOR >= 2
303  } else {
304  eprosima::fastcdr::CdrSizeCalculator calculator(eprosima::fastcdr::CdrVersion::XCDRv1);
305  size_t current_alignment = 0;
306  const size_t payload_size = calculator.calculate_serialized_size(deref(src), current_alignment);
307  return payload_size <= std::numeric_limits<uint32_t>::max() - 4U ? payload_size + 4U : 0U;
308 #else
309  } else {
310  return 0;
311 #endif
312  }
313 #ifdef VLINK_HAS_ROS2
314  }
315 #endif
316  } catch (const eprosima::fastcdr::exception::Exception&) {
317  return 0;
318  } catch (const std::exception&) {
319  return 0;
320  }
321 #endif
322 #ifdef VLINK_HAS_PROTOBUF
323  } else if constexpr (TypeT == kProtoType) {
324  if constexpr (VLINK_HAS_MEMBER(RealType, ByteSizeLong())) {
325  return deref(src).ByteSizeLong();
326  } else {
327  return deref(src).ByteSize();
328  }
329  } else if constexpr (TypeT == kProtoPtrType) {
330  if constexpr (VLINK_HAS_MEMBER(std::remove_pointer_t<T>, ByteSizeLong())) {
331  return src->ByteSizeLong();
332  } else {
333  return src->ByteSize();
334  }
335 #endif
336  } else if constexpr (TypeT == kCustomType || TypeT == kSomeipType) {
337  if constexpr (VLINK_HAS_MEMBER(RealType, get_serialized_size())) {
338  return deref(src).get_serialized_size();
339  } else {
340  return 0;
341  }
342  } else {
343  return 0;
344  }
345 }
346 
347 template <typename T>
348 inline size_t get_serialized_size(const T& src) noexcept {
349  constexpr auto kType = get_type_of<T>();
350 
351  return get_serialized_size<kType>(src);
352 }
353 
354 template <Type TypeT, typename T>
355 inline bool serialize(const T& src, Bytes& des, [[maybe_unused]] TransportType transport,
356  [[maybe_unused]] uint8_t offset) {
357  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
358 
359  if constexpr (Traits::IsSharedPtr<T>()) {
360  if VUNLIKELY (!src) {
361  return false;
362  }
363  }
364 
365  if constexpr (TypeT == kBytesType) {
366  des = Bytes::deep_copy(src.data(), src.size(), offset);
367  } else if constexpr (TypeT == kDynamicType) {
368  using ReturnT = decltype(deref(src) >> des);
369 
370  if constexpr (std::is_convertible_v<ReturnT, bool>) {
371  if VUNLIKELY (!(deref(src) >> des)) {
372  VLOG_T("Serializer: Dynamic serialize failed.");
373  return false;
374  }
375  } else {
376  deref(src) >> des;
377  }
378 #ifdef VLINK_HAS_CDR
379  } else if constexpr (TypeT == kCdrType) {
380  const size_t target_size = get_serialized_size<TypeT>(src);
381 
382  if VUNLIKELY (target_size < 4U || target_size > std::numeric_limits<uint32_t>::max()) {
383  VLOG_W("Serializer: FastBuffer serialized size is invalid.");
384  return false;
385  }
386 
387  if (!des.is_loaned()) {
388  if VUNLIKELY (des.size() != target_size) {
389  des = Bytes::create(target_size, offset);
390  }
391  }
392 
393  if VUNLIKELY (!des.data() || des.size() != target_size) {
394  return false;
395  }
396 
397  try {
398  eprosima::fastcdr::FastBuffer buffer(reinterpret_cast<char*>(des.data()), des.size());
399 #if FASTCDR_VERSION_MAJOR >= 2
400  constexpr auto kCdrVersion = VLINK_HAS_MEMBER(RealType, serialize(std::declval<eprosima::fastcdr::Cdr&>()))
401  ? eprosima::fastcdr::CdrVersion::DDS_CDR
402  : eprosima::fastcdr::CdrVersion::XCDRv1;
403  eprosima::fastcdr::Cdr cdr(buffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, kCdrVersion);
404  if constexpr (kCdrVersion == eprosima::fastcdr::CdrVersion::XCDRv1) {
405  cdr.set_encoding_flag(eprosima::fastcdr::EncodingAlgorithmFlag::PLAIN_CDR);
406  }
407 #else
408  eprosima::fastcdr::Cdr cdr(buffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, eprosima::fastcdr::Cdr::DDS_CDR);
409 #endif
410  cdr.serialize_encapsulation();
411 
412 #ifdef VLINK_HAS_ROS2
413  if constexpr (is_ros2_msg_type<RealType>()) {
414  const auto* callbacks = get_ros2_msg_callbacks<RealType>();
415 
416  if VUNLIKELY (!callbacks || !callbacks->cdr_serialize || !callbacks->cdr_serialize(&deref(src), cdr)) {
417  return false;
418  }
419  } else {
420 #endif
421  if constexpr (VLINK_HAS_MEMBER(RealType, serialize(cdr))) {
422  deref(src).serialize(cdr);
423 #if FASTCDR_VERSION_MAJOR >= 2
424  } else {
425  cdr << deref(src);
426 #endif
427  }
428 #ifdef VLINK_HAS_ROS2
429  }
430 #endif
431  } catch (const eprosima::fastcdr::exception::Exception& e) {
432  VLOG_T("Serializer: FastBuffer serialize failed: ", e.what(), ".");
433  return false;
434  } catch (const std::exception& e) {
435  VLOG_T("Serializer: CDR serialize failed: ", e.what(), ".");
436  return false;
437  }
438 #endif
439 #ifdef VLINK_HAS_PROTOBUF
440  } else if constexpr (TypeT == kProtoType) {
441  if (!des.is_loaned()) {
442  if constexpr (VLINK_HAS_MEMBER(RealType, ByteSizeLong())) {
443  size_t target_size = deref(src).ByteSizeLong();
444 
445  if VUNLIKELY (des.size() != target_size || des.offset() != offset) {
446  des = Bytes::create(target_size, offset);
447  }
448  } else {
449  size_t target_size = deref(src).ByteSize();
450 
451  if VUNLIKELY (des.size() != target_size || des.offset() != offset) {
452  des = Bytes::create(target_size, offset);
453  }
454  }
455  }
456 
457  if VUNLIKELY (!deref(src).SerializeToArray(des.data(), des.size())) {
458  VLOG_T("Serializer: Protobuf serialize failed.");
459  return false;
460  }
461  } else if constexpr (TypeT == kProtoPtrType) {
462  if (!des.is_loaned()) {
463  if constexpr (VLINK_HAS_MEMBER(std::remove_pointer_t<T>, ByteSizeLong())) {
464  size_t target_size = src->ByteSizeLong();
465 
466  if VUNLIKELY (des.size() != target_size || des.offset() != offset) {
467  des = Bytes::create(target_size, offset);
468  }
469  } else {
470  size_t target_size = src->ByteSize();
471 
472  if VUNLIKELY (des.size() != target_size || des.offset() != offset) {
473  des = Bytes::create(target_size, offset);
474  }
475  }
476  }
477 
478  if VUNLIKELY (!src->SerializeToArray(des.data(), des.size())) {
479  VLOG_T("Serializer: Protobuf ptr serialize failed.");
480  return false;
481  }
482 #endif
483 #ifdef VLINK_HAS_FLATBUFFERS
484  } else if constexpr (TypeT == kFlatTableType) {
485  flatbuffers::FlatBufferBuilder fbb;
486  fbb.Finish(RealType::TableType::Pack(fbb, &deref(src)));
487 
488  if (des.is_loaned() && des.size() >= fbb.GetSize() + offset) {
489  std::memcpy(des.data() + offset, fbb.GetBufferPointer(), fbb.GetSize());
490  } else {
491  des = Bytes::deep_copy(fbb.GetBufferPointer(), fbb.GetSize(), offset);
492  }
493  } else if constexpr (TypeT == kFlatBuilderType) {
494  if VUNLIKELY (des.is_loaned()) {
495  return false;
496  }
497 
498  auto& mutable_src = const_cast<T&>(src);
499  mutable_src.fbb_.Finish(mutable_src.Finish());
500  des = Bytes::deep_copy(mutable_src.fbb_.GetBufferPointer(), mutable_src.fbb_.GetSize(), offset);
501  } else if constexpr (TypeT == kFlatPtrType) {
502  static_assert(Traits::ExpectFalse<T>(), "Not support flat ptr type.");
503 #endif
504  } else if constexpr (TypeT == kSomeipType) {
505  if VUNLIKELY (!deref(src).serialize(des, offset)) {
506  VLOG_T("Serializer: SOME/IP serialize failed.");
507  return false;
508  }
509  } else if constexpr (TypeT == kCustomType) {
510  using ReturnT = decltype(const_cast<RealType&>(deref(src)) >> des);
511 
512  if constexpr (std::is_convertible_v<ReturnT, bool>) {
513  if VUNLIKELY (!(const_cast<RealType&>(deref(src)) >> des)) {
514  VLOG_T("Serializer: Custom serialize failed.");
515  return false;
516  }
517  } else {
518  const_cast<RealType&>(deref(src)) >> des;
519  }
520 
521  if VUNLIKELY (offset > 0) {
522  des = Bytes::deep_copy(des.data(), des.size(), offset);
523  }
524  } else if constexpr (TypeT == kStringType) {
525  des = Bytes::deep_copy(reinterpret_cast<const uint8_t*>(deref(src).data()), deref(src).size(), offset);
526  } else if constexpr (TypeT == kCharsType) {
527  size_t size = 0;
528 
529  if constexpr (std::is_array_v<T>) {
530  constexpr size_t kExtent = std::extent_v<T>;
531  const auto* terminator = static_cast<const char*>(std::memchr(src, '\0', kExtent));
532 
533  if VUNLIKELY (!terminator) {
534  VLOG_T("Serializer: Chars array is not null-terminated.");
535  return false;
536  }
537 
538  size = static_cast<size_t>(terminator - src);
539  } else {
540  if VUNLIKELY (!src) {
541  VLOG_T("Serializer: Chars source is null.");
542  return false;
543  }
544 
545  size = std::strlen(src);
546  }
547 
548  des = Bytes::deep_copy(reinterpret_cast<const uint8_t*>(src), size, offset);
549  } else if constexpr (TypeT == kStreamType) {
550  std::stringstream ss;
551  ss << deref(src);
552  const std::string str = ss.str();
553  des = Bytes::deep_copy(reinterpret_cast<const uint8_t*>(str.data()), str.size(), offset);
554  } else if constexpr (TypeT == kStandardType) {
555  const auto* src_ptr = reinterpret_cast<const uint8_t*>(&deref(src));
556  des = Bytes::deep_copy(src_ptr, sizeof(RealType), offset);
557  } else if constexpr (TypeT == kStandardPtrType) {
558  if VUNLIKELY (offset > 0) {
559  VLOG_T("Serializer: Standard ptr does not support offset.");
560  return false;
561  }
562 
563  const auto* src_ptr = reinterpret_cast<const uint8_t*>(src);
564  constexpr size_t kSize = sizeof(std::remove_pointer_t<T>);
565 
566  if (des.is_loaned() && des.size() >= kSize) {
567  std::memcpy(des.data(), src_ptr, kSize);
568  } else {
569  des = Bytes::shallow_copy(src_ptr, kSize);
570  }
571  } else {
572  static_assert(Traits::ExpectFalse<T>(), "Not support serialize.");
573  return false;
574  }
575 
576  return true;
577 }
578 
579 template <typename T>
580 inline bool serialize(const T& src, Bytes& des) {
581  constexpr auto kType = get_type_of<T>();
582 
583  return serialize<kType>(src, des, TransportType::kUnknown);
584 }
585 
586 template <Type TypeT, typename T, typename LoanCallbackT>
587 inline bool serialize_to_transport(const T& src, Bytes& des, TransportType transport, bool use_loan,
588  LoanCallbackT&& loan) {
589 #ifdef VLINK_HAS_FLATBUFFERS
590  if constexpr (TypeT == kFlatBuilderType) {
591  auto& mutable_src = const_cast<T&>(src);
592  mutable_src.fbb_.Finish(mutable_src.Finish());
593 
594  const size_t size = mutable_src.fbb_.GetSize();
595 
596  if (use_loan) {
597  des = std::forward<LoanCallbackT>(loan)(size);
598 
599  if VUNLIKELY (des.empty() || des.size() != size) {
600  return false;
601  }
602 
603  std::memcpy(des.data(), mutable_src.fbb_.GetBufferPointer(), size);
604  } else {
605  des = Bytes::shallow_copy(mutable_src.fbb_.GetBufferPointer(), size);
606  }
607 
608  return true;
609  } else {
610 #endif
611  if (use_loan) {
612  const size_t size = get_serialized_size<TypeT>(src);
613 
614  if (size == 0) {
615  des = Bytes{};
616  } else {
617  des = std::forward<LoanCallbackT>(loan)(size);
618 
619  if VUNLIKELY (des.empty() || des.size() != size) {
620  return false;
621  }
622  }
623  }
624 
625  const bool had_loan = des.is_loaned();
626  auto* loan_data = des.data();
627  const size_t loan_size = des.size();
628  const bool ret = serialize<TypeT>(src, des, transport);
629 
630  if VUNLIKELY (had_loan && (!des.is_loaned() || des.data() != loan_data || des.size() != loan_size)) {
631  des = Bytes::loan_internal(loan_data, loan_size);
632  return false;
633  }
634 
635  return ret;
636 #ifdef VLINK_HAS_FLATBUFFERS
637  }
638 #endif
639 }
640 
641 template <Type TypeT, typename T>
642 inline bool deserialize(const Bytes& src, T& des, [[maybe_unused]] TransportType transport) {
643  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
644 
645  if constexpr (Traits::IsSharedPtr<T>()) {
646  if VUNLIKELY (!des) {
647  return false;
648  }
649  }
650 
651  if constexpr (TypeT == kBytesType) {
652  des = src;
653  return true;
654  } else if constexpr (TypeT == kDynamicType) {
655  using ReturnT = decltype(deref(des) << src);
656 
657  if constexpr (std::is_convertible_v<ReturnT, bool>) {
658  if VUNLIKELY (!(deref(des) << src)) {
659  VLOG_T("Serializer: Dynamic deserialize failed.");
660  return false;
661  }
662  } else {
663  deref(des) << src;
664  }
665 #ifdef VLINK_HAS_CDR
666  } else if constexpr (TypeT == kCdrType) {
667  if VUNLIKELY (!src.data() || src.size() < 4U || src.size() > std::numeric_limits<uint32_t>::max()) {
668  VLOG_T("Serializer: FastBuffer payload has no CDR encapsulation.");
669  return false;
670  }
671 
672  try {
673  eprosima::fastcdr::FastBuffer buffer(reinterpret_cast<char*>(const_cast<uint8_t*>(src.data())), src.size());
674 #if FASTCDR_VERSION_MAJOR >= 2
675  eprosima::fastcdr::Cdr cdr(buffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN,
676  eprosima::fastcdr::CdrVersion::DDS_CDR);
677 #else
678  eprosima::fastcdr::Cdr cdr(buffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, eprosima::fastcdr::Cdr::DDS_CDR);
679 #endif
680  cdr.read_encapsulation();
681 
682 #ifdef VLINK_HAS_ROS2
683  if constexpr (is_ros2_msg_type<RealType>()) {
684  const auto* callbacks = get_ros2_msg_callbacks<RealType>();
685 
686  if VUNLIKELY (!callbacks || !callbacks->cdr_deserialize || !callbacks->cdr_deserialize(cdr, &deref(des))) {
687  return false;
688  }
689  } else {
690 #endif
691  if constexpr (VLINK_HAS_MEMBER(RealType, deserialize(cdr))) {
692  deref(des).deserialize(cdr);
693 #if FASTCDR_VERSION_MAJOR >= 2
694  } else {
695  cdr >> deref(des);
696 #endif
697  }
698 #ifdef VLINK_HAS_ROS2
699  }
700 #endif
701  } catch (const eprosima::fastcdr::exception::Exception& e) {
702  VLOG_T("Serializer: FastBuffer deserialize failed: ", e.what(), ".");
703  return false;
704  } catch (const std::exception& e) {
705  VLOG_T("Serializer: CDR deserialize failed: ", e.what(), ".");
706  return false;
707  }
708 #endif
709 #ifdef VLINK_HAS_PROTOBUF
710  } else if constexpr (TypeT == kProtoType) {
711  if (!src.empty()) {
712  if VUNLIKELY (!deref(des).ParseFromArray(src.data(), src.size())) {
713  VLOG_T("Serializer: Protobuf deserialize failed.");
714  return false;
715  }
716  } else {
717  deref(des).Clear();
718  }
719  } else if constexpr (TypeT == kProtoPtrType) {
720  if (!src.empty()) {
721  if VUNLIKELY (!des->ParseFromArray(src.data(), src.size())) {
722  VLOG_T("Serializer: Protobuf ptr deserialize failed.");
723  return false;
724  }
725  } else {
726  des->Clear();
727  }
728 #endif
729 #ifdef VLINK_HAS_FLATBUFFERS
730  } else if constexpr (TypeT == kFlatTableType) {
731  deref(des) = RealType{};
732 
733  if VLIKELY (!src.empty()) {
734  flatbuffers::Verifier verifier(src.data(), src.size());
735 
736  if VUNLIKELY (!verifier.VerifyBuffer<typename RealType::TableType>(nullptr)) {
737  VLOG_T("Serializer: Flatbuffers table deserialize failed.");
738  return false;
739  }
740 
741  auto target = flatbuffers::GetRoot<typename RealType::TableType>(src.data());
742  target->UnPackTo(&deref(des));
743  }
744  } else if constexpr (TypeT == kFlatPtrType) {
745  flatbuffers::Verifier verifier(src.data(), src.size());
746 
747  if VUNLIKELY (!verifier.VerifyBuffer<std::remove_pointer_t<T>>(nullptr)) {
748  VLOG_T("Serializer: Flatbuffers ptr verify failed.");
749  return false;
750  }
751 
752  des = const_cast<T>(flatbuffers::GetRoot<std::remove_pointer_t<T>>(src.data()));
753 
754  if VUNLIKELY (!des) {
755  VLOG_T("Serializer: Flatbuffers ptr deserialize failed.");
756  return false;
757  }
758 #endif
759  } else if constexpr (TypeT == kSomeipType) {
760  if VUNLIKELY (!deref(des).deserialize(src)) {
761  VLOG_T("Serializer: SOME/IP deserialize failed.");
762  return false;
763  }
764  } else if constexpr (TypeT == kCustomType) {
765  using ReturnT = decltype(deref(des) << src);
766 
767  if constexpr (std::is_convertible_v<ReturnT, bool>) {
768  if VUNLIKELY (!(deref(des) << src)) {
769  VLOG_T("Serializer: Custom deserialize failed.");
770  return false;
771  }
772  } else {
773  deref(des) << src;
774  }
775  } else if constexpr (TypeT == kStringType) {
776  if VLIKELY (!src.empty()) {
777  deref(des).assign(reinterpret_cast<const char*>(src.data()), src.size());
778  } else {
779  deref(des).clear();
780  }
781  } else if constexpr (TypeT == kCharsType) {
782  (void)src;
783  (void)des;
784  VLOG_E("Serializer: Chars deserialization is not supported; use std::string.");
785  return false;
786  } else if constexpr (TypeT == kStreamType) {
787  std::stringstream ss(std::string(reinterpret_cast<const char*>(src.data()), src.size()));
788 
789  ss >> deref(des);
790 
791  if VUNLIKELY (ss.fail()) {
792  VLOG_T("Serializer: Stream deserialize failed.");
793  return false;
794  }
795  } else if constexpr (TypeT == kStandardType) {
796  if VLIKELY (!src.empty() && src.size() == sizeof(RealType)) {
797  std::memcpy(&deref(des), src.data(), src.size());
798  } else {
799  VLOG_T("Serializer: Standard layout deserialize failed.");
800  return false;
801  }
802  } else if constexpr (TypeT == kStandardPtrType) {
803  if VLIKELY (!src.empty() && src.size() == sizeof(std::remove_pointer_t<T>)) {
804  des = reinterpret_cast<T>(const_cast<uint8_t*>(src.data()));
805  } else {
806  VLOG_T("Serializer: Standard ptr layout deserialize failed.");
807  return false;
808  }
809  } else {
810  static_assert(Traits::ExpectFalse<T>(), "Not support deserialize.");
811  return false;
812  }
813 
814  return true;
815 }
816 
817 template <typename T>
818 inline bool deserialize(const Bytes& src, T& des) {
819  constexpr auto kType = get_type_of<T>();
820  return deserialize<kType>(src, des, TransportType::kUnknown);
821 }
822 
823 template <typename SrcT, typename DesT>
824 inline bool convert(const SrcT& src, DesT& des) {
825  static_assert(is_bytes_type<SrcT>() || is_bytes_type<DesT>(), "SrcT or DesT must be Bytes.");
826 
827  if constexpr (is_bytes_type<SrcT>() && is_bytes_type<DesT>()) {
828  des.shallow_copy(src);
829  return true;
830  } else if constexpr (is_bytes_type<DesT>()) {
831  return serialize(src, des);
832  } else {
833  return deserialize(src, des);
834  }
835 }
836 
837 template <typename T>
838 inline constexpr auto& deref(const T& t) noexcept {
839  if constexpr (Traits::IsSharedPtr<T>()) {
840  return *const_cast<T&>(t).get();
841  } else {
842  return const_cast<T&>(t);
843  }
844 }
845 
846 template <typename T>
847 inline constexpr bool is_bytes_type() noexcept {
848  return std::is_same_v<T, Bytes>;
849 }
850 
851 template <typename T>
852 inline constexpr bool is_dynamic_type() noexcept {
853  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
854  return VLINK_HAS_MEMBER(RealType, is_vlink_dynamic_data());
855 }
856 
857 template <typename T>
858 inline constexpr bool is_cdr_type() noexcept {
859 #ifdef VLINK_HAS_CDR
860  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
861 
862 #ifdef VLINK_HAS_ROS2
863  if constexpr (is_ros2_msg_type<RealType>()) {
864  return true;
865  }
866 #endif
867 
868  return (VLINK_HAS_MEMBER(RealType, serialize(std::declval<eprosima::fastcdr::Cdr&>())) &&
869  VLINK_HAS_MEMBER(RealType, deserialize(std::declval<eprosima::fastcdr::Cdr&>()))) ||
870  Helpers::contains_substring(NameDetector::get<RealType>(), VLINK_DDS_IDL_PREFIX);
871 #else
872  return false;
873 #endif
874 }
875 
876 template <typename T>
877 inline constexpr bool is_proto_type() noexcept {
878 #ifdef VLINK_HAS_PROTOBUF
879  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
880  return VLINK_HAS_MEMBER(RealType, SerializeToArray(0, 0)) && VLINK_HAS_MEMBER(RealType, ParseFromArray(0, 0));
881 #else
882  return false;
883 #endif
884 }
885 
886 template <typename T>
887 inline constexpr bool is_proto_ptr_type() noexcept {
888 #ifdef VLINK_HAS_PROTOBUF
889  return std::is_pointer_v<T> && VLINK_HAS_MEMBER(std::remove_pointer_t<T>, SerializeToArray(0, 0)) &&
890  VLINK_HAS_MEMBER(std::remove_pointer_t<T>, ParseFromArray(0, 0));
891 #else
892  return false;
893 #endif
894 }
895 
896 template <typename T>
897 inline constexpr bool is_flat_table_type() noexcept {
898 #ifdef VLINK_HAS_FLATBUFFERS
899  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
900  return std::is_base_of_v<flatbuffers::NativeTable, RealType>;
901 #else
902  return false;
903 #endif
904 }
905 
906 template <typename T>
907 inline constexpr bool is_flat_builder_type() noexcept {
908 #ifdef VLINK_HAS_FLATBUFFERS
909  return VLINK_HAS_MEMBER(T, fbb_) && VLINK_HAS_MEMBER(T, Finish());
910 #else
911  return false;
912 #endif
913 }
914 
915 template <typename T>
916 inline constexpr bool is_flat_ptr_type() noexcept {
917 #ifdef VLINK_HAS_FLATBUFFERS
918  return std::is_pointer_v<T> && std::is_base_of_v<flatbuffers::Table, std::remove_pointer_t<T>>;
919 #else
920  return false;
921 #endif
922 }
923 
924 template <typename T>
925 inline constexpr bool is_someip_type() noexcept {
926  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
927  return VLINK_HAS_MEMBER(RealType, is_vlink_someip_type());
928 }
929 
930 template <typename T>
931 inline constexpr bool is_custom_type() noexcept {
932  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
934 }
935 
936 template <typename T>
937 inline constexpr bool is_string_type() noexcept {
938  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
939  return std::is_same_v<RealType, std::string>;
940 }
941 
942 template <typename T>
943 inline constexpr bool is_chars_type() noexcept {
944  using DecayedType = std::decay_t<T>;
945  using CharType = std::remove_pointer_t<DecayedType>;
946 
947  return std::is_pointer_v<DecayedType> && std::is_same_v<std::remove_cv_t<CharType>, char> &&
948  !std::is_volatile_v<CharType>;
949 }
950 
951 template <typename T>
952 inline constexpr bool is_stream_type() noexcept {
953  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
954  return !std::is_pointer_v<RealType> && Traits::Operatorable<std::stringstream, std::decay_t<RealType>>();
955 }
956 
957 template <typename T>
958 inline constexpr bool is_standard_type() noexcept {
959  using RealType = typename Traits::RemoveSharedPtr<T>::Type;
960  return !std::is_pointer_v<RealType> && std::is_trivial_v<RealType> && std::is_standard_layout_v<RealType>;
961 }
962 
963 template <typename T>
964 inline constexpr bool is_standard_ptr_type() noexcept {
965  return std::is_pointer_v<T> && std::is_trivial_v<std::remove_pointer_t<T>> &&
966  std::is_standard_layout_v<std::remove_pointer_t<T>>;
967 }
968 
969 } // namespace Serializer
970 
971 } // namespace vlink
#define VLOG_E(...)
Definition: logger.h:904
#define VLOG_W(...)
Definition: logger.h:902
#define VLOG_T(...)
Definition: logger.h:896
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284
Compile-time codec detection and dispatch for VLink message payloads.
#define VLINK_HAS_MEMBER(T, member)
Macro Definitions
Definition: traits.h:325