summaryrefslogtreecommitdiff
path: root/include/CommonAPI/DBus/DBusInputStream.hpp
blob: a4f3609d26af8af24fd17837827f18a33634da2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
// Copyright (C) 2013-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#if !defined (COMMONAPI_INTERNAL_COMPILATION)
#error "Only <CommonAPI/CommonAPI.hpp> can be included directly, this file may disappear or change contents."
#endif

#ifndef COMMONAPI_DBUS_DBUSINPUTSTREAM_HPP_
#define COMMONAPI_DBUS_DBUSINPUTSTREAM_HPP_

#include <iostream>
#include <iomanip>
#include <sstream>

#include <cstdint>
#include <stack>
#include <string>
#include <vector>
#include <cstring>

#include <CommonAPI/Export.hpp>
#include <CommonAPI/InputStream.hpp>
#include <CommonAPI/Struct.hpp>
#include <CommonAPI/DBus/DBusDeployment.hpp>
#include <CommonAPI/DBus/DBusError.hpp>
#include <CommonAPI/DBus/DBusFreedesktopVariant.hpp>
#include <CommonAPI/DBus/DBusHelper.hpp>
#include <CommonAPI/DBus/DBusMessage.hpp>

namespace CommonAPI {
namespace DBus {

// Used to mark the position of a pointer within an array of bytes.
typedef uint32_t position_t;

/**
 * @class DBusInputMessageStream
 *
 * Used to deserialize and read data from a #DBusMessage. For all data types that can be read from a #DBusMessage, a ">>"-operator should be defined to handle the reading
 * (this operator is predefined for all basic data types and for vectors).
 */
class DBusInputStream
    : public InputStream<DBusInputStream> {
public:
    COMMONAPI_EXPORT bool hasError() const {
        return isErrorSet();
    }

    COMMONAPI_EXPORT InputStream &readValue(bool &_value, const EmptyDeployment *_depl);

    COMMONAPI_EXPORT InputStream &readValue(int8_t &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(int16_t &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(int32_t &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(int64_t &_value, const EmptyDeployment *_depl);

    COMMONAPI_EXPORT InputStream &readValue(uint8_t &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(uint16_t &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(uint32_t &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(uint64_t &_value, const EmptyDeployment *_depl);

    COMMONAPI_EXPORT InputStream &readValue(float &_value, const EmptyDeployment *_depl);
    COMMONAPI_EXPORT InputStream &readValue(double &_value, const EmptyDeployment *_depl);

    COMMONAPI_EXPORT InputStream &readValue(std::string &_value, const EmptyDeployment *_depl);

    COMMONAPI_EXPORT InputStream &readValue(std::string &_value, const CommonAPI::DBus::StringDeployment* _depl) {
        (void)_depl;
        return readValue(_value, static_cast<EmptyDeployment *>(nullptr));
    }
    COMMONAPI_EXPORT InputStream &readValue(int32_t &_value, const CommonAPI::DBus::IntegerDeployment* _depl) {
        (void)_depl;
        return readValue(_value, static_cast<EmptyDeployment *>(nullptr));
    }
    COMMONAPI_EXPORT InputStream &readValue(uint32_t &_value, const CommonAPI::DBus::IntegerDeployment* _depl) {
        (void)_depl;
        return readValue(_value, static_cast<EmptyDeployment *>(nullptr));
    }
    COMMONAPI_EXPORT InputStream &readValue(Version &_value, const EmptyDeployment *_depl);

    COMMONAPI_EXPORT void beginReadMapOfSerializableStructs() {
        uint32_t itsSize(0);
        _readValue(itsSize);
        pushSize(itsSize);
        align(8); /* correct alignment for first DICT_ENTRY */
        pushPosition();
    }

    COMMONAPI_EXPORT bool readMapCompleted() {
        return (sizes_.back() <= (current_ - positions_.back()));
    }

    COMMONAPI_EXPORT void endReadMapOfSerializableStructs() {
        (void)popSize();
        (void)popPosition();
    }

    COMMONAPI_EXPORT InputStream &skipMap() {
        uint32_t itsSize(0);
        _readValue(itsSize);
        align(8); /* skip padding (if any) */
        if (itsSize > (sizes_.back() + positions_.back() - current_)) {
            COMMONAPI_ERROR(std::string(__FUNCTION__) + ": size ", itsSize, " exceeds remaining ", (sizes_.back() + positions_.back() - current_));
        }
        _readRaw(itsSize);
        return (*this);
    }

    template<int minimum, int maximum>
    COMMONAPI_EXPORT InputStream &readValue(RangedInteger<minimum, maximum> &_value, const EmptyDeployment *) {
        int tmpValue;
        readValue(tmpValue, static_cast<EmptyDeployment *>(nullptr));
        if(!_value.validate()) {
            setError();
        }
        if (!hasError()) {
            _value = tmpValue;
        }
        return (*this);
    }

    template<class Deployment_, typename Base_>
    COMMONAPI_EXPORT InputStream &readValue(Enumeration<Base_> &_value, const Deployment_ *_depl) {
        Base_ tmpValue;
        readValue(tmpValue, _depl);
        _value = tmpValue;

        if(!_value.validate()) {
            setError();
        }
        return (*this);
    }

    template<class Deployment_, typename... Types_>
    COMMONAPI_EXPORT InputStream &readValue(Struct<Types_...> &_value, const Deployment_ *_depl) {
        align(8);
        const auto itsSize(std::tuple_size<std::tuple<Types_...>>::value);
        StructReader<itsSize-1, DBusInputStream, Struct<Types_...>, Deployment_>{}(
            (*this), _value, _depl);
        return (*this);
    }

    template<class Deployment_, class PolymorphicStruct_>
    COMMONAPI_EXPORT InputStream &readValue(std::shared_ptr<PolymorphicStruct_> &_value,
                           const Deployment_ *_depl) {
        uint32_t serial(0);
        align(8);
        _readValue(serial);
        skipSignature();
        align(8);
        if (!hasError()) {
            _value = PolymorphicStruct_::create(serial);
            _value->template readValue<>(*this, _depl);
        }

        return (*this);
    }

    template<typename... Types_>
    COMMONAPI_EXPORT InputStream &readValue(Variant<Types_...> &_value, const CommonAPI::EmptyDeployment *_depl = nullptr) {
        (void)_depl;
        if(_value.hasValue()) {
#if _MSC_VER < 1900
            const auto maxSize = Variant<Types_...>::maxSize;
#else
            constexpr auto maxSize = Variant<Types_...>::maxSize;
#endif
            DeleteVisitor<maxSize> visitor(_value.valueStorage_);
            ApplyVoidVisitor<DeleteVisitor<maxSize>,
                Variant<Types_...>, Types_... >::visit(visitor, _value);
        }

        align(8);
        readValue(_value.valueType_, static_cast<EmptyDeployment *>(nullptr));
        skipSignature();

        InputStreamReadVisitor<DBusInputStream, Types_...> visitor((*this), _value);
        ApplyVoidVisitor<InputStreamReadVisitor<DBusInputStream, Types_... >,
            Variant<Types_...>, Types_...>::visit(visitor, _value);

        return (*this);
    }

    template<typename Deployment_, typename... Types_>
    COMMONAPI_EXPORT InputStream &readValue(Variant<Types_...> &_value, const Deployment_ *_depl) {
        if(_value.hasValue()) {
#if _MSC_VER < 1900
            const auto maxSize = Variant<Types_...>::maxSize;
#else
            constexpr auto maxSize = Variant<Types_...>::maxSize;
#endif
            DeleteVisitor<maxSize> visitor(_value.valueStorage_);
            ApplyVoidVisitor<DeleteVisitor<maxSize>,
                Variant<Types_...>, Types_... >::visit(visitor, _value);
        }

        if (_depl != nullptr && _depl->isDBus_) {
            // Read signature
            uint8_t signatureLength(0);
            readValue(signatureLength, static_cast<EmptyDeployment *>(nullptr));
            char * raw = _readRaw(signatureLength+1);
            if (hasError()) {
                return (*this);
            } else  {
                std::string signature(raw, signatureLength);

                // Determine index (value type) from signature
                TypeCompareVisitor<Types_...> visitor(signature);
                bool success = ApplyTypeCompareVisitor<
                                        TypeCompareVisitor<Types_...>,
                                        Variant<Types_...>,
                                        Deployment_,
                                        Types_...
                                    >::visit(visitor, _value, _depl, _value.valueType_);
                /*
                 * It is possible that this ApplyTypeCompareVisitor fails on purpose,
                 * if the data type of the variant does not match the data type in the stream.
                 * This can happen for instance with the Freedesktop messages that return
                 * data in variants, but we don't have any idea _which variant_ until we've
                 * tried to stream the value in the ApplyTypeComputerVisitor.
                 */
                if (!success) {
                    _value.valueType_ = 0; // Invalid index signifying 'no value'
                    setError();
                    return (*this);
                }
            }
        } else {
            align(8);
            readValue(_value.valueType_, static_cast<EmptyDeployment *>(nullptr));
            skipSignature();
        }


        InputStreamReadVisitor<DBusInputStream, Types_...> visitor((*this), _value);
        ApplyStreamVisitor<InputStreamReadVisitor<DBusInputStream, Types_... >,
            Variant<Types_...>, Deployment_, Types_...>::visit(visitor, _value, _depl);

        return (*this);
    }

    template<typename ElementType_>
    COMMONAPI_EXPORT InputStream &readValue(std::vector<ElementType_> &_value, const EmptyDeployment *_depl) {
        (void)_depl;

        uint32_t itsSize(0);
        _readValue(itsSize);
        pushSize(itsSize);

        alignVector<ElementType_>();

        pushPosition();

        _value.clear();
        while (sizes_.back() > current_ - positions_.back()) {
            ElementType_ itsElement;
            readValue(itsElement, static_cast<EmptyDeployment *>(nullptr));

            if (hasError()) {
                break;
            }

            _value.push_back(std::move(itsElement));
        }

        popSize();
        popPosition();

        return (*this);
    }

    COMMONAPI_EXPORT InputStream &readValue(std::vector<uint8_t> &_value, const EmptyDeployment *_depl) {
        (void)_depl;

        uint32_t itsSize(0);
        _readValue(itsSize);

        alignVector<uint8_t>();

        uint8_t *data = reinterpret_cast<uint8_t *>(_readRaw(itsSize));
        if (!hasError()) {
            _value.resize(itsSize);
            std::memcpy(_value.data(), data, itsSize);
        }

        return (*this);
    }


    template<class Deployment_, typename ElementType_>
    COMMONAPI_EXPORT InputStream &readValue(std::vector<ElementType_> &_value, const Deployment_ *_depl) {
        uint32_t itsSize(0);
        _readValue(itsSize);
        pushSize(itsSize);

        alignVector<ElementType_>();

        pushPosition();

        _value.clear();
        while (sizes_.back() > current_ - positions_.back()) {
            ElementType_ itsElement;
            readValue(itsElement, (_depl ? _depl->elementDepl_ : nullptr));

            if (hasError()) {
                break;
            }

            _value.push_back(std::move(itsElement));
        }

        popSize();
        popPosition();

        return (*this);
    }

    template<typename KeyType_, typename ValueType_, typename HasherType_>
    COMMONAPI_EXPORT InputStream &readValue(std::unordered_map<KeyType_, ValueType_, HasherType_> &_value,
                           const EmptyDeployment *_depl) {

        typedef typename std::unordered_map<KeyType_, ValueType_, HasherType_>::value_type MapElement;

        uint32_t itsSize(0);
        _readValue(itsSize);
        pushSize(itsSize);

        align(8);
        pushPosition();

        _value.clear();
        while (sizes_.back() > current_ - positions_.back()) {
            KeyType_ itsKey;
            ValueType_ itsValue;

            align(8);
            readValue(itsKey, _depl);
            readValue(itsValue, _depl);

            if (hasError()) {
                break;
            }

            _value.insert(MapElement(std::move(itsKey), std::move(itsValue)));
        }

        (void)popSize();
        (void)popPosition();

        return (*this);
    }

    template<class Deployment_, typename KeyType_, typename ValueType_, typename HasherType_>
    COMMONAPI_EXPORT InputStream &readValue(std::unordered_map<KeyType_, ValueType_, HasherType_> &_value,
                           const Deployment_ *_depl) {

        typedef typename std::unordered_map<KeyType_, ValueType_, HasherType_>::value_type MapElement;

        uint32_t itsSize(0);
        _readValue(itsSize);
        pushSize(itsSize);

        align(8);
        pushPosition();

        _value.clear();
        while (sizes_.back() > current_ - positions_.back()) {
            KeyType_ itsKey;
            ValueType_ itsValue;

            align(8);
            readValue(itsKey, (_depl ? _depl->key_ : nullptr));
            readValue(itsValue, (_depl ? _depl->value_ : nullptr));

            if (hasError()) {
                break;
            }

            _value.insert(MapElement(std::move(itsKey), std::move(itsValue)));
        }

        (void)popSize();
        (void)popPosition();

        return (*this);
    }

    /**
     * Creates a #DBusInputMessageStream which can be used to deserialize and read data from the given #DBusMessage.
     * As no message-signature is checked, the user is responsible to ensure that the correct data types are read in the correct order.
     *
     * @param message the #DBusMessage from which data should be read.
     */
    COMMONAPI_EXPORT DBusInputStream(const CommonAPI::DBus::DBusMessage &_message);
    COMMONAPI_EXPORT DBusInputStream(const DBusInputStream &_stream) = delete;

    /**
     * Destructor; does not call the destructor of the referred #DBusMessage. Make sure to maintain a reference to the
     * #DBusMessage outside of the stream if you intend to make further use of the message.
     */
    COMMONAPI_EXPORT ~DBusInputStream();

    // Marks the stream as erroneous.
    COMMONAPI_EXPORT void setError();

    /**
     * @return An instance of #DBusError if this stream is in an erroneous state, NULL otherwise
     */
    COMMONAPI_EXPORT const DBusError &getError() const;

    /**
     * @return true if this stream is in an erroneous state, false otherwise.
     */
    COMMONAPI_EXPORT bool isErrorSet() const;

    // Marks the state of the stream as cleared from all errors. Further reading is possible afterwards.
    // The stream will have maintained the last valid position from before its state became erroneous.
    COMMONAPI_EXPORT void clearError();

    /**
     * Aligns the stream to the given byte boundary, i.e. the stream skips as many bytes as are necessary to execute the next read
     * starting from the given boundary.
     *
     * @param _boundary the byte boundary to which the stream needs to be aligned.
     */
    COMMONAPI_EXPORT void align(const size_t _boundary);

    /**
     * Reads the given number of bytes and returns them as an array of characters.
     *
     * Actually, for performance reasons this command only returns a pointer to the current position in the stream,
     * and then increases the position of this pointer by the number of bytes indicated by the given parameter.
     * It is the user's responsibility to actually use only the number of bytes he indicated he would use.
     * It is assumed the user knows what kind of value is stored next in the #DBusMessage the data is streamed from.
     * Using a reinterpret_cast on the returned pointer should then restore the original value.
     *
     * Example use case:
     * @code
     * ...
     * inputMessageStream.alignForBasicType(sizeof(int32_t));
     * char* const dataPtr = inputMessageStream.read(sizeof(int32_t));
     * int32_t val = *(reinterpret_cast<int32_t*>(dataPtr));
     * ...
     * @endcode
     */
    COMMONAPI_EXPORT char *_readRaw(const size_t _size);

    /**
     * Handles all reading of basic types from a given #DBusInputMessageStream.
     * Basic types in this context are: uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t, float, double.
     * Any types not listed here (especially all complex types, e.g. structs, unions etc.) need to provide a
     * specialized implementation of this operator.
     *
     * @tparam Type_ The type of the value that is to be read from the given stream.
     * @param _value The variable in which the retrieved value is to be stored
     * @return The given inputMessageStream to allow for successive reading
     */
    template<typename Type_>
    COMMONAPI_EXPORT DBusInputStream &_readValue(Type_ &_value) {
        if (sizeof(_value) > 1)
            align(sizeof(Type_));

        char * raw = _readRaw(sizeof(Type_));
        if (!hasError()) {
            _value = *(reinterpret_cast<Type_ *>(raw));
        }

        return (*this);
    }

    COMMONAPI_EXPORT DBusInputStream &_readValue(float &_value) {
        align(sizeof(double));

        char * raw = _readRaw(sizeof(double));
        if (!hasError()) {
            _value = float(*(reinterpret_cast<double*>(raw)));
        }
        return (*this);
    }

private:
    COMMONAPI_EXPORT void pushPosition();
    COMMONAPI_EXPORT size_t popPosition();

    COMMONAPI_EXPORT void pushSize(size_t _size);
    COMMONAPI_EXPORT size_t popSize();

    inline void skipSignature() {
        uint8_t length(0);
        _readValue(length);
        _readRaw(length + 1);
    }

    template<typename Type_,
        typename std::enable_if<(!std::is_class<Type_>::value &&
                                 !is_std_vector<Type_>::value &&
                                 !is_std_unordered_map<Type_>::value), int>::type = 0>
    COMMONAPI_EXPORT void alignVector() {
        if (4 < sizeof(Type_)) align(8);
    }

    template<typename Type_,
        typename std::enable_if<(!std::is_same<Type_, std::string>::value &&
                                std::is_class<Type_>::value && 
                                !is_std_vector<Type_>::value &&
                                !is_std_unordered_map<Type_>::value &&
                                !std::is_base_of<Enumeration<uint8_t>, Type_>::value &&
                                !std::is_base_of<Enumeration<uint16_t>, Type_>::value &&
                                !std::is_base_of<Enumeration<uint32_t>, Type_>::value &&
                                !std::is_base_of<Enumeration<int8_t>, Type_>::value &&
                                !std::is_base_of<Enumeration<int16_t>, Type_>::value &&
                                !std::is_base_of<Enumeration<int32_t>, Type_>::value), int>::type = 0>
    COMMONAPI_EXPORT void alignVector() {
        align(8);
    }

    template<typename Type_,
        typename std::enable_if<(std::is_same<Type_, std::string>::value ||
                                 is_std_vector<Type_>::value ||
                                 std::is_base_of<Enumeration<uint8_t>, Type_>::value ||
                                 std::is_base_of<Enumeration<int8_t>, Type_>::value), int>::type = 0>
    COMMONAPI_EXPORT void alignVector() {
        // Intentionally do nothing
    }

    template<typename Type_,
        typename std::enable_if<(is_std_unordered_map<Type_>::value ||
                                 std::is_base_of<Enumeration<uint32_t>, Type_>::value ||
                                 std::is_base_of<Enumeration<int32_t>, Type_>::value), int>::type = 0>
    COMMONAPI_EXPORT void alignVector() {
        align(4);
    }

    template<typename Type_,
        typename std::enable_if<(std::is_base_of<Enumeration<uint16_t>, Type_>::value ||
                                 std::is_base_of<Enumeration<int16_t>, Type_>::value), int>::type = 0>
    COMMONAPI_EXPORT void alignVector() {
        align(2);
    }

    char *begin_;
    size_t current_;
    size_t size_;
    CommonAPI::DBus::DBusError* exception_;
    CommonAPI::DBus::DBusMessage message_;

    std::vector<uint32_t> sizes_;
    std::vector<size_t> positions_;
};

} // namespace DBus
} // namespace CommonAPI

#endif // COMMONAPI_DBUS_DBUS_INPUTSTREAM_HPP_