Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-06-18 02:20:25

0001 // C++ headers
0002 #include <iomanip>
0003 #include <ios>
0004 #include <iostream>
0005 #include <vector>
0006 
0007 // ROOT headers
0008 #include <TBufferFile.h>
0009 #include <TClass.h>
0010 
0011 template <typename T>
0012 void print_vector(std::vector<T> const& v) {
0013   if (v.empty()) {
0014     std::cout << "{}";
0015     return;
0016   }
0017 
0018   std::cout << "{ " << v[0];
0019   for (unsigned int i = 1; i < v.size(); ++i) {
0020     std::cout << ", " << v[i];
0021   }
0022   std::cout << " }";
0023 }
0024 
0025 void print_buffer(const char* buffer, int size) {
0026   auto flags = std::cout.flags();
0027   for (int i = 0; i < size; ++i) {
0028     if (i % 16 == 0)
0029       std::cout << '\t';
0030     unsigned char value = buffer[i];
0031     std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)value;
0032     std::cout << ((i % 16 == 15 or i == size - 1) ? '\n' : ' ');
0033   }
0034   std::cout.flags(flags);
0035 }
0036 
0037 int main() {
0038   // Type of the object to serialise and deserialise
0039   using Type = std::vector<float>;
0040 
0041   // Original vector to serialize
0042   Type send_object = {1.1, 2.2, 3.3, 4.4, 5.5};
0043 
0044   // Display the contents of the original vector
0045   std::cout << "Original object:     ";
0046   print_vector(send_object);
0047   std::cout << "\n";
0048 
0049   // Create a buffer for serialization
0050   TBufferFile send_buffer(TBuffer::kWrite);
0051 
0052   // Get the TClass for the type to serialise
0053   //TClass* type = TClass::GetClass<Type>();
0054   TClass* type = TClass::GetClass(typeid(Type));
0055 
0056   // Serialize the vector into the buffer
0057   send_buffer.WriteObjectAny((void*)&send_object, type, false);
0058   int size = send_buffer.Length();
0059 
0060   // Display the contents of the buffer
0061   std::cout << "Serialised object is " << size << " bytes long:\n";
0062   print_buffer(send_buffer.Buffer(), size);
0063 
0064   // Create a new buffer for deserialization
0065   TBufferFile recv_buffer(TBuffer::kRead, size);
0066 
0067   // Copy the buffer
0068   std::memcpy(recv_buffer.Buffer(), send_buffer.Buffer(), size);
0069 
0070   // Deserialize into a new vector
0071   std::unique_ptr<Type> recv_object{reinterpret_cast<Type*>(recv_buffer.ReadObjectAny(type))};
0072 
0073   // Display the contents of the new vector
0074   std::cout << "Deserialized object: ";
0075   print_vector(*recv_object);
0076   std::cout << "\n";
0077 
0078   return 0;
0079 }