SNode.C
Loading...
Searching...
No Matches
UIntV.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - a slim toolkit for network communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "iot/mqtt/types/UIntV.h"
21
22#include "iot/mqtt/MqttContext.h"
23#include "iot/mqtt/types/TypeBase.hpp" // IWYU pragma: keep
24
25#ifndef DOXYGEN_SHOULD_SKIP_THIS
26
27#include <vector>
28
29#endif // DOXYGEN_SHOULD_SKIP_THIS
30
31namespace iot::mqtt::types {
32
34 : TypeBase(0) {
35 }
36
38 }
39
40 std::size_t UIntV::deserialize(MqttContext* mqttContext) {
41 std::size_t consumed = 0;
42
43 do {
44 char byte = 0;
45 consumed = mqttContext->recv(&byte, 1);
46
47 if (consumed > 0) {
48 value.push_back(byte);
49
50 if (value.size() > sizeof(uint32_t)) {
51 error = true;
52 } else {
53 complete = (byte & 0x80) == 0;
54 }
55 }
56 } while (consumed > 0 && !complete && !error);
57
58 return consumed;
59 }
60
61 UIntV& UIntV::operator=(const uint32_t& newValue) {
62 uint32_t remainingValue = newValue;
63 value.clear();
64
65 do {
66 char encodedByte = static_cast<char>(remainingValue % 0x80);
67
68 remainingValue /= 0x80;
69 if (remainingValue > 0) {
70 encodedByte |= static_cast<char>(0x80);
71 }
72
73 value.push_back(encodedByte);
74 } while (remainingValue > 0);
75
76 return *this;
77 }
78
79 UIntV::operator uint32_t() const {
80 uint32_t uint32Value = 0;
81 uint32_t multiplicator = 1;
82
83 for (std::size_t i = 0; i < value.size(); i++, multiplicator *= 0x80) {
84 uint32Value += static_cast<uint8_t>(value[i] & 0x7F) * multiplicator;
85 }
86
87 return uint32Value;
88 }
89
90 bool UIntV::isError() const {
91 return error;
92 }
93
94 void UIntV::reset([[maybe_unused]] std::size_t size) {
95 error = false;
96
97 TypeBase::reset(0);
98 }
99
100} // namespace iot::mqtt::types
std::size_t deserialize(iot::mqtt::MqttContext *mqttContext) override
Definition UIntV.cpp:40
bool isError() const
Definition UIntV.cpp:90
UIntV & operator=(const uint32_t &newValue)
Definition UIntV.cpp:61
operator uint32_t() const
Definition UIntV.cpp:79
void reset(std::size_t size=sizeof(ValueType)) override
Definition UIntV.cpp:94