1 | // Copyright (C) 2022 The Qt Company Ltd. |
2 | // Copyright (C) 2019 Alexey Edelev <semlanik@gmail.com> |
3 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
4 | |
5 | #ifndef QABSTRACTPROTOBUFSERIALIZER_H |
6 | #define QABSTRACTPROTOBUFSERIALIZER_H |
7 | |
8 | #include <QtProtobuf/qtprotobufglobal.h> |
9 | #include <QtProtobuf/qtprotobuftypes.h> |
10 | #include <QtProtobuf/qprotobufmessage.h> |
11 | |
12 | #include <type_traits> |
13 | |
14 | QT_BEGIN_NAMESPACE |
15 | |
16 | class Q_PROTOBUF_EXPORT QAbstractProtobufSerializer |
17 | { |
18 | |
19 | public: |
20 | enum DeserializationError { |
21 | NoError, |
22 | , |
23 | NoDeserializerError, |
24 | UnexpectedEndOfStreamError, |
25 | }; |
26 | |
27 | template<typename T> |
28 | QByteArray serialize(const QProtobufMessage *message) const |
29 | { |
30 | static_assert(QtProtobufPrivate::HasProtobufPropertyOrdering<T>, |
31 | "T must have the Q_PROTOBUF_OBJECT macro" ); |
32 | return doSerialize(message, ordering: T::propertyOrdering); |
33 | } |
34 | |
35 | template<typename T> |
36 | bool deserialize(T *object, QByteArrayView data) const |
37 | { |
38 | static_assert(QtProtobufPrivate::HasProtobufPropertyOrdering<T>, |
39 | "T must have the Q_PROTOBUF_OBJECT macro" ); |
40 | static_assert(std::is_base_of_v<QProtobufMessage, T>, |
41 | "T must be derived from QProtobufMessage" ); |
42 | // Initialize default object first and make copy afterwards, it's necessary to set default |
43 | // values of properties that was not stored in data. |
44 | T newValue; |
45 | bool success = doDeserialize(message: &newValue, ordering: T::propertyOrdering, data); |
46 | *object = newValue; |
47 | return success; |
48 | } |
49 | |
50 | virtual ~QAbstractProtobufSerializer(); |
51 | |
52 | virtual QAbstractProtobufSerializer::DeserializationError deserializationError() const = 0; |
53 | virtual QString deserializationErrorString() const = 0; |
54 | |
55 | QByteArray serializeRawMessage(const QProtobufMessage *message) const; |
56 | bool deserializeRawMessage(QProtobufMessage *message, QByteArrayView data) const; |
57 | |
58 | protected: |
59 | virtual QByteArray |
60 | serializeMessage(const QProtobufMessage *message, |
61 | const QtProtobufPrivate::QProtobufPropertyOrdering &ordering) const = 0; |
62 | virtual bool deserializeMessage(QProtobufMessage *message, |
63 | const QtProtobufPrivate::QProtobufPropertyOrdering &ordering, |
64 | QByteArrayView data) const = 0; |
65 | |
66 | private: |
67 | QByteArray doSerialize(const QProtobufMessage *message, |
68 | const QtProtobufPrivate::QProtobufPropertyOrdering &ordering) const; |
69 | bool doDeserialize(QProtobufMessage *message, |
70 | const QtProtobufPrivate::QProtobufPropertyOrdering &ordering, |
71 | QByteArrayView data) const; |
72 | }; |
73 | |
74 | QT_END_NAMESPACE |
75 | #endif // QABSTRACTPROTOBUFSERIALIZER_H |
76 | |