Belle II Software development
Stream.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8#include <framework/utilities/Stream.h>
9
10#include <TBase64.h>
11#include <TObject.h>
12#include <TMessage.h>
13
14using namespace Belle2;
15
16namespace {
18 class StreamMsg : public TMessage {
19 public:
20 StreamMsg(const void* buf, int len) : TMessage(const_cast<void*>(buf), len)
21 {
22 this->SetBit(kIsOwner, false);
23 }
24 };
25}
26
27std::string Stream::serializeAndEncode(const TObject* obj)
28{
29 TMessage::EnableSchemaEvolutionForAll();
30
31 TMessage msg(kMESS_OBJECT);
32 msg.SetWriteMode();
33
34 msg.SetCompressionLevel(1);
35
36 msg.WriteObject(obj);
37 msg.Compress(); //only does something if compression active
38
39 //convert TMessage into base64-encoded string
40 char* buf = msg.Buffer();
41 UInt_t len = msg.Length();
42
43 // using the compressed buffer causes a seg fault (double free)
44 // this can be tested with the unit-test StreamTest.raw
45 // if (msg.CompBuffer()) {
46 // buf = msg.CompBuffer();
47 // len = msg.CompLength();
48 // }
49
50 const std::string& encodedStr(TBase64::Encode(buf, len).Data());
51 return encodedStr;
52}
53
54TObject* Stream::deserializeEncodedRawData(const std::string& base64Data)
55{
56 if (base64Data.empty())
57 return nullptr;
58
59 //convert data back into raw byte stream
60 const TString& data(TBase64::Decode(base64Data.c_str()));
61
62 StreamMsg msg(data.Data(), data.Length());
63 //some checking
64 if (msg.What() != kMESS_OBJECT or msg.GetClass() == nullptr) {
65 return nullptr;
66 }
67 auto* obj = static_cast<TObject*>(msg.ReadObjectAny(msg.GetClass()));
68
69 return obj;
70}
std::string serializeAndEncode(const TObject *obj)
Convert given TObject into encoded byte stream (for storing in XML).
Definition Stream.cc:27
TObject * deserializeEncodedRawData(const std::string &base64Data)
Convert given serialized raw data back into TObject.
Definition Stream.cc:54
Abstract base class for different kinds of events.