1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2024 Google LLC. All rights reserved. 3 // 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file or at 6 // https://developers.google.com/open-source/licenses/bsd 7 8 #ifndef GOOGLE_PROTOBUF_RUST_CPP_KERNEL_SERIALIZED_DATA_H__ 9 #define GOOGLE_PROTOBUF_RUST_CPP_KERNEL_SERIALIZED_DATA_H__ 10 11 #include <climits> 12 #include <cstddef> 13 #include <cstdint> 14 #include <cstring> 15 16 #include "absl/log/absl_check.h" 17 #include "absl/log/absl_log.h" 18 #include "google/protobuf/message_lite.h" 19 #include "rust/cpp_kernel/rust_alloc_for_cpp_api.h" 20 21 namespace google { 22 namespace protobuf { 23 namespace rust { 24 25 // Represents serialized Protobuf wire format data. 26 // 27 // Only to be used to transfer serialized data from C++ to Rust under these 28 // assumptions: 29 // * Rust and C++ versions of this struct are ABI compatible. 30 // * Rust version owns and frees its data. 31 // * The data were allocated using the Rust allocator. 32 // 33 extern "C" struct SerializedData { 34 // Owns the memory, must be freed by Rust. 35 const uint8_t* data; 36 size_t len; 37 }; 38 SerializeMsg(const google::protobuf::MessageLite * msg,SerializedData * out)39inline bool SerializeMsg(const google::protobuf::MessageLite* msg, SerializedData* out) { 40 ABSL_DCHECK(msg->IsInitialized()); 41 size_t len = msg->ByteSizeLong(); 42 if (len > INT_MAX) { 43 ABSL_LOG(ERROR) << msg->GetTypeName() 44 << " exceeded maximum protobuf size of 2GB: " << len; 45 return false; 46 } 47 uint8_t* bytes = static_cast<uint8_t*>(proto2_rust_alloc(len, alignof(char))); 48 if (bytes == nullptr) { 49 ABSL_LOG(FATAL) << "Rust allocator failed to allocate memory."; 50 } 51 if (!msg->SerializeWithCachedSizesToArray(bytes)) { 52 return false; 53 } 54 out->data = bytes; 55 out->len = len; 56 return true; 57 } 58 59 } // namespace rust 60 } // namespace protobuf 61 } // namespace google 62 63 #endif // GOOGLE_PROTOBUF_RUST_CPP_KERNEL_SERIALIZED_DATA_H__ 64